Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / backends / C / c_backend_src.ml @ cd670fe1

History | View | Annotate | Download (15.4 KB)

1
open Format
2
open LustreSpec
3
open Corelang
4
open Machine_code
5
open C_backend_common
6

    
7
(********************************************************************************************)
8
(*                    Instruction Printing functions                                        *)
9
(********************************************************************************************)
10

    
11
(* Computes the depth to which multi-dimension array assignments should be expanded.
12
   It equals the maximum number of nested static array constructions accessible from root [v].
13
*)
14
let rec expansion_depth v =
15
 match v with
16
 | Cst (Const_array cl) -> 1 + List.fold_right (fun c -> max (expansion_depth (Cst c))) cl 0
17
 | Cst _
18
 | LocalVar _
19
 | StateVar _  -> 0
20
 | Fun (_, vl) -> List.fold_right (fun v -> max (expansion_depth v)) vl 0
21
 | Array vl    -> 1 + List.fold_right (fun v -> max (expansion_depth v)) vl 0
22
 | Access (v, i) -> max 0 (expansion_depth v - 1)
23
 | Power (v, n)  -> 0 (*1 + expansion_depth v*)
24

    
25
type loop_index = LVar of ident | LInt of int ref
26

    
27
(* Computes the list of nested loop variables together with their dimension bounds.
28
   - LInt r stands for loop expansion (no loop variable, but int loop index)
29
   - LVar v stands for loop variable v
30
*)
31
let rec mk_loop_variables m ty depth =
32
 match (Types.repr ty).Types.tdesc, depth with
33
 | Types.Tarray (d, ty'), 0       ->
34
   let v = mk_loop_var m () in
35
   (d, LVar v) :: mk_loop_variables m ty' 0
36
 | Types.Tarray (d, ty'), _       ->
37
   let r = ref (-1) in
38
   (d, LInt r) :: mk_loop_variables m ty' (depth - 1)
39
 | _                    , 0       -> []
40
 | _                              -> assert false
41

    
42
let reorder_loop_variables loop_vars =
43
  let (int_loops, var_loops) = 
44
    List.partition (function (d, LInt _) -> true | _ -> false) loop_vars 
45
  in
46
  var_loops @ int_loops
47
    
48
(* Prints a one loop variable suffix for arrays *)
49
let pp_loop_var fmt lv =
50
 match snd lv with
51
 | LVar v -> fprintf fmt "[%s]" v
52
 | LInt r -> fprintf fmt "[%d]" !r
53

    
54
(* Prints a suffix of loop variables for arrays *)
55
let pp_suffix fmt loop_vars =
56
 Utils.fprintf_list ~sep:"" pp_loop_var fmt loop_vars
57

    
58
(* Prints a [value] indexed by the suffix list [loop_vars] *)
59
let rec pp_value_suffix self loop_vars pp_value fmt value =
60
 match loop_vars, value with
61
 | (_, LInt r) :: q, Array vl     ->
62
   pp_value_suffix self q pp_value fmt (List.nth vl !r)
63
 | _           :: q, Power (v, n) ->
64
   pp_value_suffix self loop_vars pp_value fmt v
65
 | _               , Fun (n, vl)  ->
66
   Basic_library.pp_c n (pp_value_suffix self loop_vars pp_value) fmt vl
67
 | _               , _            ->
68
   let pp_var_suffix fmt v = fprintf fmt "%a%a" pp_value v pp_suffix loop_vars in
69
   pp_c_val self pp_var_suffix fmt value
70

    
71
(* type_directed assignment: array vs. statically sized type
72
   - [var_type]: type of variable to be assigned
73
   - [var_name]: name of variable to be assigned
74
   - [value]: assigned value
75
   - [pp_var]: printer for variables
76
*)
77
let pp_assign m self pp_var fmt var_type var_name value =
78
  let depth = expansion_depth value in
79
(*eprintf "pp_assign %a %a %d@." Types.print_ty var_type pp_val value depth;*)
80
  let loop_vars = mk_loop_variables m var_type depth in
81
  let reordered_loop_vars = reorder_loop_variables loop_vars in
82
  let rec aux fmt vars =
83
    match vars with
84
    | [] ->
85
      fprintf fmt "%a = %a;" 
86
	(pp_value_suffix self loop_vars pp_var) var_name
87
	(pp_value_suffix self loop_vars pp_var) value
88
    | (d, LVar i) :: q ->
89
(*eprintf "pp_aux %a %s@." Dimension.pp_dimension d i;*)
90
      fprintf fmt "@[<v 2>{@,int %s;@,for(%s=0;%s<%a;%s++)@,%a @]@,}"
91
	i i i Dimension.pp_dimension d i
92
	aux q
93
    | (d, LInt r) :: q ->
94
(*eprintf "pp_aux %a %d@." Dimension.pp_dimension d (!r);*)
95
      let szl = Utils.enumerate (Dimension.size_const_dimension d) in
96
      fprintf fmt "@[<v 2>{@,%a@]@,}"
97
	(Utils.fprintf_list ~sep:"@," (fun fmt i -> r := i; aux fmt q)) szl
98
  in
99
  begin
100
    reset_loop_counter ();
101
    (*reset_addr_counter ();*)
102
    aux fmt reordered_loop_vars
103
  end
104

    
105
let pp_instance_call m self fmt i (inputs: value_t list) (outputs: var_decl list) =
106
 try (* stateful node instance *)
107
   let (n,_) = List.assoc i m.minstances in
108
   fprintf fmt "%a (%a%t%a%t%s->%s);"
109
     pp_machine_step_name (node_name n)
110
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
111
     (Utils.pp_final_char_if_non_empty ", " inputs) 
112
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs
113
     (Utils.pp_final_char_if_non_empty ", " outputs)
114
     self
115
     i
116
 with Not_found -> (* stateless node instance *)
117
   let (n,_) = List.assoc i m.mcalls in
118
   fprintf fmt "%a (%a%t%a);"
119
     pp_machine_step_name (node_name n)
120
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
121
     (Utils.pp_final_char_if_non_empty ", " inputs) 
122
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs 
123

    
124
let pp_machine_reset (m: machine_t) self fmt inst =
125
  let (node, static) = List.assoc inst m.minstances in
126
  fprintf fmt "%a(%a%t%s->%s);"
127
    pp_machine_reset_name (node_name node)
128
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
129
    (Utils.pp_final_char_if_non_empty ", " static)
130
    self inst
131

    
132
let has_c_prototype funname dependencies =
133
  let imported_node_opt = (* We select the last imported node with the name funname.
134
			       The order of evaluation of dependencies should be
135
			       compatible with overloading. (Not checked yet) *) 
136
      List.fold_left
137
	(fun res (_, _, decls) -> 
138
	  match res with
139
	  | Some _ -> res
140
	  | None -> 
141
	    let matched = fun t -> match t.top_decl_desc with 
142
	      | ImportedNode nd -> nd.nodei_id = funname 
143
	      | _ -> false
144
	    in
145
	    if List.exists matched decls then (
146
	      match (List.find matched decls).top_decl_desc with
147
	      | ImportedNode nd -> Some nd
148
	      | _ -> assert false
149
	    )
150
	    else
151
	      None
152
	) None dependencies in
153
    match imported_node_opt with
154
    | None -> false
155
    | Some nd -> (match nd.nodei_prototype with Some "C" -> true | _ -> false)
156

    
157
let rec pp_conditional dependencies (m: machine_t) self fmt c tl el =
158
  fprintf fmt "@[<v 2>if (%a) {%t%a@]@,@[<v 2>} else {%t%a@]@,}"
159
    (pp_c_val self (pp_c_var_read m)) c
160
    (Utils.pp_newline_if_non_empty tl)
161
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) tl
162
    (Utils.pp_newline_if_non_empty el)
163
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) el
164

    
165
and pp_machine_instr dependencies (m: machine_t) self fmt instr =
166
  match instr with 
167
  | MReset i ->
168
    pp_machine_reset m self fmt i
169
  | MLocalAssign (i,v) ->
170
    pp_assign
171
      m self (pp_c_var_read m) fmt
172
      i.var_type (LocalVar i) v
173
  | MStateAssign (i,v) ->
174
    pp_assign
175
      m self (pp_c_var_read m) fmt
176
      i.var_type (StateVar i) v
177
  | MStep ([i0], i, vl) when Basic_library.is_internal_fun i  ->
178
    pp_machine_instr dependencies m self fmt (MLocalAssign (i0, Fun (i, vl)))
179
  | MStep ([i0], i, vl) when has_c_prototype i dependencies -> 
180
    fprintf fmt "%a = %s(%a);" 
181
      (pp_c_val self (pp_c_var_read m)) (LocalVar i0) 
182
      i
183
      (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) vl
184
  | MStep (il, i, vl) ->
185
    pp_instance_call m self fmt i vl il
186
  | MBranch (g,hl) ->
187
    if hl <> [] && let t = fst (List.hd hl) in t = tag_true || t = tag_false
188
    then (* boolean case, needs special treatment in C because truth value is not unique *)
189
	 (* may disappear if we optimize code by replacing last branch test with default *)
190
      let tl = try List.assoc tag_true  hl with Not_found -> [] in
191
      let el = try List.assoc tag_false hl with Not_found -> [] in
192
      pp_conditional dependencies m self fmt g tl el
193
    else (* enum type case *)
194
      fprintf fmt "@[<v 2>switch(%a) {@,%a@,}@]"
195
	(pp_c_val self (pp_c_var_read m)) g
196
	(Utils.fprintf_list ~sep:"@," (pp_machine_branch dependencies m self)) hl
197

    
198
and pp_machine_branch dependencies m self fmt (t, h) =
199
  fprintf fmt "@[<v 2>case %a:@,%a@,break;@]" pp_c_tag t (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) h
200

    
201

    
202
(********************************************************************************************)
203
(*                         C file Printing functions                                        *)
204
(********************************************************************************************)
205

    
206
let print_const_def fmt cdecl =
207
  fprintf fmt "%a = %a;@." 
208
    (pp_c_type cdecl.const_id) cdecl.const_type
209
    pp_c_const cdecl.const_value 
210

    
211

    
212
let print_alloc_instance fmt (i, (m, static)) =
213
  fprintf fmt "_alloc->%s = %a (%a);@,"
214
    i
215
    pp_machine_alloc_name (node_name m)
216
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
217

    
218
let print_alloc_array fmt vdecl =
219
  let base_type = Types.array_base_type vdecl.var_type in
220
  let size_types = Types.array_type_multi_dimension vdecl.var_type in
221
  let size_type = Dimension.multi_dimension_product vdecl.var_loc size_types in
222
  fprintf fmt "_alloc->_reg.%s = (%a*) malloc((%a)*sizeof(%a));@,assert(_alloc->%s);@,"
223
    vdecl.var_id
224
    (pp_c_type "") base_type
225
    Dimension.pp_dimension size_type
226
    (pp_c_type "") base_type
227
    vdecl.var_id
228

    
229
let print_alloc_code fmt m =
230
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
231
  fprintf fmt "%a *_alloc;@,_alloc = (%a *) malloc(sizeof(%a));@,assert(_alloc);@,%a%areturn _alloc;"
232
    pp_machine_memtype_name m.mname.node_id
233
    pp_machine_memtype_name m.mname.node_id
234
    pp_machine_memtype_name m.mname.node_id
235
    (Utils.fprintf_list ~sep:"" print_alloc_array) array_mem
236
    (Utils.fprintf_list ~sep:"" print_alloc_instance) m.minstances
237

    
238
let print_stateless_code dependencies fmt m =
239
  let self = "__ERROR__" in
240
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
241
  then
242
    (* C99 code *)
243
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
244
      print_stateless_prototype (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
245
      (* locals *)
246
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
247
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
248
      (* check assertions *)
249
      (pp_c_checks self) m
250
      (* instrs *)
251
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
252
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
253
      (fun fmt -> fprintf fmt "return;")
254
  else
255
    (* C90 code *)
256
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
257
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
258
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
259
      print_stateless_prototype (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
260
      (* locals *)
261
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
262
      (Utils.pp_final_char_if_non_empty ";" base_locals)
263
      (* check assertions *)
264
      (pp_c_checks self) m
265
      (* instrs *)
266
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
267
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
268
      (fun fmt -> fprintf fmt "return;")
269

    
270
let print_reset_code dependencies fmt m self =
271
  fprintf fmt "@[<v 2>%a {@,%a%treturn;@]@,}@.@."
272
    (print_reset_prototype self) (m.mname.node_id, m.mstatic)
273
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.minit
274
    (Utils.pp_newline_if_non_empty m.minit)
275

    
276
let print_step_code dependencies fmt m self =
277
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
278
  then
279
    (* C99 code *)
280
    let array_mems = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
281
    fprintf fmt "@[<v 2>%a {@,%a%t%a%t@,%a%a%t%t@]@,}@.@."
282
      (print_step_prototype self) (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
283
      (* locals *)
284
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
285
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
286
      (* array mems *)
287
      (Utils.fprintf_list ~sep:";@," (pp_c_decl_array_mem self)) array_mems
288
      (Utils.pp_final_char_if_non_empty ";@," array_mems)
289
      (* check assertions *)
290
      (pp_c_checks self) m
291
      (* instrs *)
292
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
293
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
294
      (fun fmt -> fprintf fmt "return;")
295
  else
296
    (* C90 code *)
297
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
298
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
299
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
300
      (print_step_prototype self) (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
301
      (* locals *)
302
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
303
      (Utils.pp_final_char_if_non_empty ";" base_locals)
304
      (* check assertions *)
305
      (pp_c_checks self) m
306
      (* instrs *)
307
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
308
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
309
      (fun fmt -> fprintf fmt "return;")
310

    
311

    
312
(********************************************************************************************)
313
(*                     MAIN C file Printing functions                                       *)
314
(********************************************************************************************)
315

    
316
let print_machine dependencies fmt m =
317
  if fst (get_stateless_status m) then
318
    begin
319
      (* Step function *)
320
      print_stateless_code dependencies fmt m
321
    end
322
  else
323
    begin
324
      (* Alloc function, only if non static mode *)
325
      if (not !Options.static_mem) then  
326
	(
327
	  fprintf fmt "@[<v 2>%a {@,%a@]@,}@.@."
328
	    print_alloc_prototype (m.mname.node_id, m.mstatic)
329
	    print_alloc_code m;
330
	);
331
      let self = mk_self m in
332
      (* Reset function *)
333
      print_reset_code dependencies fmt m self;
334
      (* Step function *)
335
      print_step_code dependencies fmt m self
336
    end
337

    
338

    
339

    
340

    
341
let print_c source_fmt basename prog machines dependencies =
342

    
343
  (* If a main node is identified, generate a main function for it *)
344
  let main_include, main_print =
345
    match !Options.main_node with
346
      | "" -> (fun _ -> ()), (fun _ -> ())
347
      | main_node -> (
348
	match Machine_code.get_machine_opt main_node machines with
349
	| None -> (
350
	  eprintf "Unable to find a main node named %s@.@?" main_node; 
351
	  (fun _ -> ()), (fun _ -> ())
352
	)
353
	| Some m -> 
354
	  C_backend_main.print_main_header, C_backend_main.print_main_fun machines m
355
      )
356
  in
357
  main_include source_fmt;
358
  fprintf source_fmt "#include <stdlib.h>@.#include <assert.h>@.#include \"%s\"@.@." (basename^".h");
359
  (* Print the svn version number and the supported C standard (C90 or C99) *)
360
  print_version source_fmt;
361
  (* Print the prototype of imported nodes *)
362
  fprintf source_fmt "/* Imported nodes declarations */@.";
363
  fprintf source_fmt "@[<v>";
364
  List.iter (print_import_prototype source_fmt) dependencies;
365
  fprintf source_fmt "@]@.";
366
  (* Print consts *)
367
  fprintf source_fmt "/* Global constants (definitions) */@.";
368
  List.iter (fun c -> print_const_def source_fmt c) (get_consts prog);
369
  pp_print_newline source_fmt ();
370
  (* Print nodes one by one (in the previous order) *)
371
  List.iter (print_machine dependencies source_fmt) machines;
372
  main_print source_fmt
373

    
374

    
375
(* Local Variables: *)
376
(* compile-command:"make -C ../../.." *)
377
(* End: *)