Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / c_backend.ml @ 22fe1c93

History | View | Annotate | Download (33.5 KB)

1
(* ----------------------------------------------------------------------------
2
 * SchedMCore - A MultiCore Scheduling Framework
3
 * Copyright (C) 2009-2013, ONERA, Toulouse, FRANCE - LIFL, Lille, FRANCE
4
 * Copyright (C) 2012-2013, INPT, Toulouse, FRANCE
5
 *
6
 * This file is part of Prelude
7
 *
8
 * Prelude is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public License
10
 * as published by the Free Software Foundation ; either version 2 of
11
 * the License, or (at your option) any later version.
12
 *
13
 * Prelude is distributed in the hope that it will be useful, but
14
 * WITHOUT ANY WARRANTY ; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this program ; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21
 * USA
22
 *---------------------------------------------------------------------------- *)
23

    
24
(* This module is used for the lustre to C compiler *)
25

    
26
open Format
27
open LustreSpec
28
open Corelang
29
open Machine_code
30

    
31

    
32
(********************************************************************************************)
33
(*                     Basic      Printing functions                                        *)
34
(********************************************************************************************)
35

    
36
let print_version fmt =
37
  Format.fprintf fmt "/* @[<v>C code generated by %s@,SVN version number %s@,Code is %s compliant */@,@]@."
38
    (Filename.basename Sys.executable_name) Version.number (if !Options.ansi then "ANSI C90" else "C99")
39

    
40
let mk_self m =
41
  mk_new_name (m.mstep.step_inputs@m.mstep.step_outputs@m.mstep.step_locals@m.mmemory) "self"
42

    
43
let mk_call_var_decl loc id =
44
  { var_id = id;
45
    var_dec_type = mktyp Location.dummy_loc Tydec_any;
46
    var_dec_clock = mkclock Location.dummy_loc Ckdec_any;
47
    var_dec_const = false;
48
    var_type = Type_predef.type_arrow (Types.new_var ()) (Types.new_var ());
49
    var_clock = Clocks.new_var true;
50
    var_loc = loc }
51

    
52
(* counter for loop variable creation *)
53
let loop_cpt = ref (-1)
54

    
55
let reset_loop_counter () =
56
 loop_cpt := -1
57

    
58
let mk_loop_var m () =
59
  let vars = m.mstep.step_inputs@m.mstep.step_outputs@m.mstep.step_locals@m.mmemory in
60
  let rec aux () =
61
    incr loop_cpt;
62
    let s = Printf.sprintf "__%s_%d" "i" !loop_cpt in
63
    if List.exists (fun v -> v.var_id = s) vars then aux () else s
64
  in aux ()
65
(*
66
let addr_cpt = ref (-1)
67

    
68
let reset_addr_counter () =
69
 addr_cpt := -1
70

    
71
let mk_addr_var m var =
72
  let vars = m.mmemory in
73
  let rec aux () =
74
    incr addr_cpt;
75
    let s = Printf.sprintf "%s_%s_%d" var "addr" !addr_cpt in
76
    if List.exists (fun v -> v.var_id = s) vars then aux () else s
77
  in aux ()
78
*)
79
let pp_machine_memtype_name fmt id = fprintf fmt "struct %s_mem" id
80
let pp_machine_regtype_name fmt id = fprintf fmt "struct %s_reg" id
81
let pp_machine_alloc_name fmt id = fprintf fmt "%s_alloc" id
82
let pp_machine_static_declare_name fmt id = fprintf fmt "%s_DECLARE" id
83
let pp_machine_static_link_name fmt id = fprintf fmt "%s_LINK" id
84
let pp_machine_static_alloc_name fmt id = fprintf fmt "%s_ALLOC" id
85
let pp_machine_reset_name fmt id = fprintf fmt "%s_reset" id
86
let pp_machine_step_name fmt id = fprintf fmt "%s_step" id
87

    
88
let pp_c_dimension fmt d =
89
 fprintf fmt "%a" Dimension.pp_dimension d
90

    
91
let pp_c_type var fmt t =
92
  let rec aux t pp_suffix =
93
  match (Types.repr t).Types.tdesc with
94
  | Types.Tclock t'       -> aux t' pp_suffix
95
  | Types.Tbool           -> Format.fprintf fmt "_Bool %s%a" var pp_suffix ()
96
  | Types.Treal           -> Format.fprintf fmt "double %s%a" var pp_suffix ()
97
  | Types.Tint            -> Format.fprintf fmt "int %s%a" var pp_suffix ()
98
  | Types.Tarray (d, t')  ->
99
    let pp_suffix' fmt () = Format.fprintf fmt "%a[%a]" pp_suffix () pp_c_dimension d in
100
    aux t' pp_suffix'
101
  | Types.Tstatic (_, t') -> Format.fprintf fmt "const "; aux t' pp_suffix
102
  | Types.Tconst ty       -> Format.fprintf fmt "%s %s" ty var
103
  | Types.Tarrow (_, _)   -> Format.fprintf fmt "void (*%s)()" var
104
  | _                     -> Format.eprintf "internal error: pp_c_type %a@." Types.print_ty t; assert false
105
  in aux t (fun fmt () -> ())
106

    
107
let rec pp_c_initialize fmt t = 
108
  match (Types.repr t).Types.tdesc with
109
  | Types.Tint -> pp_print_string fmt "0"
110
  | Types.Tclock t' -> pp_c_initialize fmt t'
111
  | Types.Tbool -> pp_print_string fmt "0" 
112
  | Types.Treal -> pp_print_string fmt "0."
113
  | Types.Tarray (d, t') when Dimension.is_dimension_const d ->
114
    Format.fprintf fmt "{%a}"
115
      (Utils.fprintf_list ~sep:"," (fun fmt _ -> pp_c_initialize fmt t'))
116
      (Utils.duplicate 0 (Dimension.size_const_dimension d))
117
  | _ -> assert false
118

    
119
(* Declaration of an input variable:
120
   - if its type is array/matrix/etc, then declare it as a mere pointer,
121
     in order to cope with unknown/parametric array dimensions, 
122
     as it is the case for generics
123
*)
124
let pp_c_decl_input_var fmt id =
125
  if !Options.ansi && Types.is_array_type id.var_type
126
  then pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
127
  else pp_c_type id.var_id fmt id.var_type
128

    
129
(* Declaration of an output variable:
130
   - if its type is scalar, then pass its address
131
   - if its type is array/matrix/etc, then declare it as a mere pointer,
132
     in order to cope with unknown/parametric array dimensions, 
133
     as it is the case for generics
134
*)
135
let pp_c_decl_output_var fmt id =
136
  if (not !Options.ansi) && Types.is_array_type id.var_type
137
  then pp_c_type                  id.var_id  fmt id.var_type
138
  else pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
139

    
140
(* Declaration of a local/mem variable:
141
   - if it's an array/matrix/etc, its size(s) should be
142
     known in order to statically allocate memory, 
143
     so we print the full type
144
*)
145
let pp_c_decl_local_var fmt id =
146
  pp_c_type id.var_id fmt id.var_type
147

    
148
let pp_c_decl_array_mem self fmt id =
149
  Format.fprintf fmt "%a = (%a) (%s->_reg.%s)"
150
    (pp_c_type (sprintf "(*%s)" id.var_id)) id.var_type
151
    (pp_c_type "(*)") id.var_type
152
    self
153
    id.var_id
154

    
155
(* Declaration of a struct variable:
156
   - if it's an array/matrix/etc, we declare it as a pointer
157
*)
158
let pp_c_decl_struct_var fmt id =
159
  if Types.is_array_type id.var_type
160
  then pp_c_type (sprintf "(*%s)" id.var_id) fmt (Types.array_base_type id.var_type)
161
  else pp_c_type                  id.var_id  fmt id.var_type
162

    
163
(* Access to the value of a variable:
164
   - if it's not a scalar output, then its name is enough
165
   - otherwise, dereference it (it has been declared as a pointer,
166
     despite its scalar Lustre type)
167
   - moreover, cast arrays variables into their original array type.
168
*)
169
let pp_c_var_read m fmt id =
170
  if Types.is_array_type id.var_type
171
  then
172
    Format.fprintf fmt "%s" id.var_id
173
  else
174
    if List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs (* id is output *)
175
    then Format.fprintf fmt "*%s" id.var_id
176
    else Format.fprintf fmt "%s" id.var_id
177

    
178
(* Addressable value of a variable, the one that is passed around in calls:
179
   - if it's not a scalar non-output, then its name is enough
180
   - otherwise, reference it (it must be passed as a pointer,
181
     despite its scalar Lustre type)
182
*)
183
let pp_c_var_write m fmt id =
184
  if Types.is_array_type id.var_type
185
  then
186
    Format.fprintf fmt "%s" id.var_id
187
  else
188
    if List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs (* id is output *)
189
    then
190
      Format.fprintf fmt "%s" id.var_id
191
    else
192
      Format.fprintf fmt "&%s" id.var_id
193

    
194
let pp_c_decl_instance_var fmt (name, (node, static)) = 
195
  Format.fprintf fmt "%a *%s" pp_machine_memtype_name (node_name node) name
196

    
197
let pp_c_tag fmt t =
198
 pp_print_string fmt (if t = tag_true then "1" else if t = tag_false then "0" else t)
199

    
200
(* Prints a constant value *)
201
let rec pp_c_const fmt c =
202
  match c with
203
    | Const_int i    -> pp_print_int fmt i
204
    | Const_real r   -> pp_print_string fmt r
205
    | Const_float r  -> pp_print_float fmt r
206
    | Const_tag t    -> pp_c_tag fmt t
207
    | Const_array ca -> Format.fprintf fmt "{%a}" (Utils.fprintf_list ~sep:"," pp_c_const) ca
208

    
209
(* Prints a value expression [v], with internal function calls only.
210
   [pp_var] is a printer for variables (typically [pp_c_var_read]),
211
   but an offset suffix may be added for array variables
212
*)
213
let rec pp_c_val self pp_var fmt v =
214
  match v with
215
    | Cst c         -> pp_c_const fmt c
216
    | Array vl      -> Format.fprintf fmt "{%a}" (Utils.fprintf_list ~sep:", " (pp_c_val self pp_var)) vl
217
    | Access (t, i) -> Format.fprintf fmt "%a[%a]" (pp_c_val self pp_var) t (pp_c_val self pp_var) i
218
    | Power (v, n)  -> assert false
219
    | LocalVar v    -> pp_var fmt v
220
    | StateVar v    ->
221
      if Types.is_array_type v.var_type
222
      then Format.fprintf fmt "*%a" pp_var v
223
      else Format.fprintf fmt "%s->_reg.%a" self pp_var v
224
    | Fun (n, vl)   -> Basic_library.pp_c n (pp_c_val self pp_var) fmt vl
225

    
226
let pp_c_checks self fmt m =
227
  Utils.fprintf_list ~sep:"" (fun fmt (loc, check) -> Format.fprintf fmt "@[<v>%a@,assert (%a);@]@," Location.pp_c_loc loc (pp_c_val self (pp_c_var_read m)) check) fmt m.mstep.step_checks
228

    
229

    
230
(********************************************************************************************)
231
(*                    Instruction Printing functions                                        *)
232
(********************************************************************************************)
233

    
234
(* Computes the depth to which multi-dimension array assignments should be expanded.
235
   It equals the maximum number of nested static array constructions accessible from root [v].
236
*)
237
let rec expansion_depth v =
238
 match v with
239
 | Cst (Const_array cl) -> 1 + List.fold_right (fun c -> max (expansion_depth (Cst c))) cl 0
240
 | Cst _
241
 | LocalVar _
242
 | StateVar _  -> 0
243
 | Fun (_, vl) -> List.fold_right (fun v -> max (expansion_depth v)) vl 0
244
 | Array vl    -> 1 + List.fold_right (fun v -> max (expansion_depth v)) vl 0
245
 | Access (v, i) -> max 0 (expansion_depth v - 1)
246
 | Power (v, n)  -> 0 (*1 + expansion_depth v*)
247

    
248
type loop_index = LVar of ident | LInt of int ref
249

    
250
(* Computes the list of nested loop variables together with their dimension bounds.
251
   - LInt r stands for loop expansion (no loop variable, but int loop index)
252
   - LVar v stands for loop variable v
253
*)
254
let rec mk_loop_variables m ty depth =
255
 match (Types.repr ty).Types.tdesc, depth with
256
 | Types.Tarray (d, ty'), 0       ->
257
   let v = mk_loop_var m () in
258
   (d, LVar v) :: mk_loop_variables m ty' 0
259
 | Types.Tarray (d, ty'), _       ->
260
   let r = ref (-1) in
261
   (d, LInt r) :: mk_loop_variables m ty' (depth - 1)
262
 | _                    , 0       -> []
263
 | _                              -> assert false
264

    
265
let reorder_loop_variables loop_vars =
266
  let (int_loops, var_loops) = List.partition (function (d, LInt _) -> true | _ -> false) loop_vars in
267
  var_loops @ int_loops
268

    
269
(* Prints a one loop variable suffix for arrays *)
270
let pp_loop_var fmt lv =
271
 match snd lv with
272
 | LVar v -> Format.fprintf fmt "[%s]" v
273
 | LInt r -> Format.fprintf fmt "[%d]" !r
274

    
275
(* Prints a suffix of loop variables for arrays *)
276
let pp_suffix fmt loop_vars =
277
 Utils.fprintf_list ~sep:"" pp_loop_var fmt loop_vars
278

    
279
(* Prints a [value] indexed by the suffix list [loop_vars] *)
280
let rec pp_value_suffix self loop_vars pp_value fmt value =
281
 match loop_vars, value with
282
 | (_, LInt r) :: q, Array vl     ->
283
   pp_value_suffix self q pp_value fmt (List.nth vl !r)
284
 | _           :: q, Power (v, n) ->
285
   pp_value_suffix self loop_vars pp_value fmt v
286
 | _               , Fun (n, vl)  ->
287
   Basic_library.pp_c n (pp_value_suffix self loop_vars pp_value) fmt vl
288
 | _               , _            ->
289
   let pp_var_suffix fmt v = Format.fprintf fmt "%a%a" pp_value v pp_suffix loop_vars in
290
   pp_c_val self pp_var_suffix fmt value
291

    
292
(* type_directed assignment: array vs. statically sized type
293
   - [var_type]: type of variable to be assigned
294
   - [var_name]: name of variable to be assigned
295
   - [value]: assigned value
296
   - [pp_var]: printer for variables
297
*)
298
let pp_assign m self pp_var fmt var_type var_name value =
299
  let depth = expansion_depth value in
300
(*Format.eprintf "pp_assign %a %a %d@." Types.print_ty var_type pp_val value depth;*)
301
  let loop_vars = mk_loop_variables m var_type depth in
302
  let reordered_loop_vars = reorder_loop_variables loop_vars in
303
  let rec aux fmt vars =
304
    match vars with
305
    | [] ->
306
      fprintf fmt "%a = %a;" (pp_value_suffix self loop_vars pp_var) var_name (pp_value_suffix self loop_vars pp_var) value
307
    | (d, LVar i) :: q ->
308
(*Format.eprintf "pp_aux %a %s@." Dimension.pp_dimension d i;*)
309
      Format.fprintf fmt "@[<v 2>{@,int %s;@,for(%s=0;%s<%a;%s++)@,%a @]@,}"
310
	i i i Dimension.pp_dimension d i
311
	aux q
312
    | (d, LInt r) :: q ->
313
(*Format.eprintf "pp_aux %a %d@." Dimension.pp_dimension d (!r);*)
314
      let szl = Utils.enumerate (Dimension.size_const_dimension d) in
315
      Format.fprintf fmt "@[<v 2>{@,%a@]@,}"
316
	(Utils.fprintf_list ~sep:"@," (fun fmt i -> r := i; aux fmt q)) szl
317
  in
318
  begin
319
    reset_loop_counter ();
320
    (*reset_addr_counter ();*)
321
    aux fmt reordered_loop_vars
322
  end
323

    
324
let pp_instance_call m self fmt i (inputs: value_t list) (outputs: var_decl list) =
325
 try (* stateful node instance *)
326
   let (n,_) = List.assoc i m.minstances in
327
   Format.fprintf fmt "%s_step (%a%t%a%t%s->%s);"
328
     (node_name n)
329
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
330
     (Utils.pp_final_char_if_non_empty ", " inputs) 
331
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs
332
     (Utils.pp_final_char_if_non_empty ", " outputs)
333
     self
334
     i
335
 with Not_found -> (* stateless node instance *)
336
   let (n,_) = List.assoc i m.mcalls in
337
   Format.fprintf fmt "%s (%a%t%a);"
338
     (node_name n)
339
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
340
     (Utils.pp_final_char_if_non_empty ", " inputs) 
341
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs 
342

    
343
let pp_machine_reset (m: machine_t) self fmt inst =
344
  let (node, static) = List.assoc inst m.minstances in
345
  fprintf fmt "%a(%a%t%s->%s);"
346
    pp_machine_reset_name (node_name node)
347
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
348
    (Utils.pp_final_char_if_non_empty ", " static)
349
    self inst
350

    
351
let rec pp_conditional (m: machine_t) self fmt c tl el =
352
  fprintf fmt "@[<v 2>if (%a) {%t%a@]@,@[<v 2>} else {%t%a@]@,}"
353
    (pp_c_val self (pp_c_var_read m)) c
354
    (Utils.pp_newline_if_non_empty tl)
355
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr m self)) tl
356
    (Utils.pp_newline_if_non_empty el)
357
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr m self)) el
358

    
359
and pp_machine_instr (m: machine_t) self fmt instr =
360
  match instr with 
361
  | MReset i ->
362
    pp_machine_reset m self fmt i
363
  | MLocalAssign (i,v) ->
364
    pp_assign
365
      m self (pp_c_var_read m) fmt
366
      i.var_type (LocalVar i) v
367
  | MStateAssign (i,v) ->
368
    pp_assign
369
      m self (pp_c_var_read m) fmt
370
      i.var_type (StateVar i) v
371
  | MStep ([i0], i, vl) when Basic_library.is_internal_fun i  ->
372
    pp_machine_instr m self fmt (MLocalAssign (i0, Fun (i, vl)))
373
  | MStep (il, i, vl) ->
374
    pp_instance_call m self fmt i vl il
375
  | MBranch (g,hl) ->
376
    if hl <> [] && let t = fst (List.hd hl) in t = tag_true || t = tag_false
377
    then (* boolean case, needs special treatment in C because truth value is not unique *)
378
	 (* may disappear if we optimize code by replacing last branch test with default *)
379
      let tl = try List.assoc tag_true  hl with Not_found -> [] in
380
      let el = try List.assoc tag_false hl with Not_found -> [] in
381
      pp_conditional m self fmt g tl el
382
    else (* enum type case *)
383
      fprintf fmt "@[<v 2>switch(%a) {@,%a@,}@]"
384
	(pp_c_val self (pp_c_var_read m)) g
385
	(Utils.fprintf_list ~sep:"@," (pp_machine_branch m self)) hl
386

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

    
390
(********************************************************************************************)
391
(*                      Prototype Printing functions                                        *)
392
(********************************************************************************************)
393

    
394
let print_alloc_prototype fmt (name, static) =
395
  fprintf fmt "%a * %a (%a)"
396
    pp_machine_memtype_name name
397
    pp_machine_alloc_name name
398
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
399

    
400
let print_reset_prototype self fmt (name, static) =
401
  fprintf fmt "void %a (@[<v>%a%t%a *%s@])"
402
    pp_machine_reset_name name
403
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
404
    (Utils.pp_final_char_if_non_empty ",@," static) 
405
    pp_machine_memtype_name name
406
    self
407

    
408
let print_stateless_prototype fmt (name, inputs, outputs) =
409
match outputs with
410
(* DOESN'T WORK FOR ARRAYS
411
  | [o] -> fprintf fmt "%a (@[<v>%a@])"
412
    (pp_c_type name) o.var_type
413
    (Utils.fprintf_list ~sep:",@ " pp_c_var) inputs
414
*)  
415
  | _ -> fprintf fmt "void %s (@[<v>@[%a%t@]@,@[%a@]@,@])"
416
    name
417
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
418
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
419
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
420

    
421
let print_step_prototype self fmt (name, inputs, outputs) =
422
  fprintf fmt "void %a (@[<v>@[%a%t@]@,@[%a@]%t@[%a *%s@]@])"
423
    pp_machine_step_name name
424
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
425
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
426
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
427
    (Utils.pp_final_char_if_non_empty ",@," outputs) 
428
    pp_machine_memtype_name name
429
    self
430

    
431
(********************************************************************************************)
432
(*                         Header Printing functions                                        *)
433
(********************************************************************************************)
434

    
435
let print_prototype fmt decl =
436
  match decl.top_decl_desc with
437
    | ImportedFun m -> (
438
        fprintf fmt "extern %a;@,"
439
	  print_stateless_prototype 
440
	  (m.fun_id, m.fun_inputs, m.fun_outputs)
441
    )
442
    | ImportedNode m -> (
443
      if m.nodei_stateless then (* It's a function not a node *)
444
        fprintf fmt "extern %a;@,"
445
	  print_stateless_prototype 
446
	  (m.nodei_id, m.nodei_inputs, m.nodei_outputs)
447
      else (
448
	let static = List.filter (fun v -> v.var_dec_const) m.nodei_inputs in
449
        fprintf fmt "extern %a;@,"
450
	  print_alloc_prototype (m.nodei_id, static);
451
	fprintf fmt "extern %a;@,"
452
	  (print_reset_prototype "self") (m.nodei_id, static);
453
	fprintf fmt "extern %a;@,"
454
	  (print_step_prototype "self") (m.nodei_id, m.nodei_inputs, m.nodei_outputs);
455
      )
456
    )
457
    | _ -> () (* We don't do anything here *)
458

    
459
let pp_registers_struct fmt m =
460
  if m.mmemory <> []
461
  then
462
    fprintf fmt "@[%a {@[%a; @]}@] _reg; "
463
      pp_machine_regtype_name m.mname.node_id
464
      (Utils.fprintf_list ~sep:"; " pp_c_decl_struct_var) m.mmemory
465
  else
466
    ()
467

    
468
let print_machine_struct fmt m =
469
  (* Define struct *)
470
  fprintf fmt "@[%a {@[%a%a%t@]};@]@."
471
    pp_machine_memtype_name m.mname.node_id
472
    pp_registers_struct m
473
    (Utils.fprintf_list ~sep:"; " pp_c_decl_instance_var) m.minstances
474
    (Utils.pp_final_char_if_non_empty "; " m.minstances) 
475
(*
476
let pp_static_array_instance fmt m (v, m) =
477
 fprintf fmt "%s" (mk_addr_var m v)
478
*)
479
let print_static_declare_instance fmt (i, (m, static)) =
480
  fprintf fmt "%a(%a%t%s)"
481
    pp_machine_static_declare_name (node_name m)
482
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
483
    (Utils.pp_final_char_if_non_empty ", " static)
484
    i
485

    
486
let print_static_declare_macro fmt m =
487
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
488
  fprintf fmt "@[<v 2>#define %a(%a%tinst)\\@,%a inst;\\@,%a%t%a;@,@]"
489
    pp_machine_static_declare_name m.mname.node_id
490
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
491
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
492
    pp_machine_memtype_name m.mname.node_id
493
    (Utils.fprintf_list ~sep:";\\@," pp_c_decl_local_var) array_mem
494
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
495
    (Utils.fprintf_list ~sep:";\\@,"
496
       (fun fmt (i',m') ->
497
	 let path = sprintf "inst ## _%s" i' in
498
	 fprintf fmt "%a"
499
	   print_static_declare_instance (path,m')
500
       )) m.minstances
501

    
502
      
503
let print_static_link_instance fmt (i, (m, _)) =
504
 fprintf fmt "%a(%s)" pp_machine_static_link_name (node_name m) i
505

    
506
let print_static_link_macro fmt m =
507
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
508
  fprintf fmt "@[<v>@[<v 2>#define %a(inst) do {\\@,%a%t%a;\\@]@,} while (0)@.@]"
509
    pp_machine_static_link_name m.mname.node_id
510
    (Utils.fprintf_list ~sep:";\\@,"
511
       (fun fmt v ->
512
	 fprintf fmt "inst.%s = &%s"
513
	   v.var_id
514
	   v.var_id
515
       )) array_mem
516
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
517
    (Utils.fprintf_list ~sep:";\\@,"
518
       (fun fmt (i',m') ->
519
	 let path = sprintf "inst ## _%s" i' in
520
	 fprintf fmt "%a;\\@,inst.%s = &%s"
521
	   print_static_link_instance (path,m')
522
	   i'
523
	   path
524
       )) m.minstances
525
      
526
let print_static_alloc_macro fmt m =
527
  fprintf fmt "@[<v>@[<v 2>#define %a(%a%tinst)\\@,%a(%a%tinst);\\@,%a(inst);@]@,@]@."
528
    pp_machine_static_alloc_name m.mname.node_id
529
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
530
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
531
    pp_machine_static_declare_name m.mname.node_id
532
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
533
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
534
    pp_machine_static_link_name m.mname.node_id
535

    
536
let print_machine_decl fmt m =
537
  (* Static allocation *)
538
  if !Options.static_mem then (
539
  fprintf fmt "%a@.%a@.%a@."
540
    print_static_declare_macro m
541
    print_static_link_macro m
542
    print_static_alloc_macro m;
543
  )
544
  else ( 
545
    (* Dynamic allocation *)
546
    fprintf fmt "extern %a;@.@."
547
      print_alloc_prototype (m.mname.node_id, m.mstatic);
548
  );
549
  if m.mname.node_id = arrow_id then (
550
  (* Arrow will be defined by a #define macro because of polymorphism *)
551
    fprintf fmt "#define _arrow_step(x,y,output,self) ((self)->_reg._first?((self)->_reg._first=0,(*output = x)):(*output = y))@.@.";
552
    fprintf fmt "#define _arrow_reset(self) {(self)->_reg._first = 1;}@.@."
553
  )
554
  else (
555
    let self = mk_self m in
556
    fprintf fmt "extern %a;@.@."
557
      (print_reset_prototype self) (m.mname.node_id, m.mstatic);
558
    (* Print specification if any *)
559
    (match m.mspec with
560
      | None -> ()
561
      | Some spec -> 
562
	Printers.pp_acsl_spec m.mstep.step_outputs fmt spec
563
    );
564
    fprintf fmt "extern %a;@.@."
565
      (print_step_prototype self)
566
      (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
567
  )
568

    
569

    
570
(********************************************************************************************)
571
(*                         C file Printing functions                                        *)
572
(********************************************************************************************)
573

    
574
let print_const fmt cdecl =
575
  fprintf fmt "%a = %a;@." (pp_c_type cdecl.const_id) cdecl.const_type pp_c_const cdecl.const_value 
576

    
577
let print_alloc_instance fmt (i, (m, static)) =
578
  fprintf fmt "_alloc->%s = %a (%a);@,"
579
    i
580
    pp_machine_alloc_name (node_name m)
581
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
582

    
583
let print_alloc_array fmt vdecl =
584
  let base_type = Types.array_base_type vdecl.var_type in
585
  let size_types = Types.array_type_multi_dimension vdecl.var_type in
586
  let size_type = Dimension.multi_dimension_product vdecl.var_loc size_types in
587
  fprintf fmt "_alloc->%s = (%a*) malloc((%a)*sizeof(%a));@,assert(_alloc->%s);@,"
588
    vdecl.var_id
589
    (pp_c_type "") base_type
590
    Dimension.pp_dimension size_type
591
    (pp_c_type "") base_type
592
    vdecl.var_id
593

    
594
let print_alloc_code fmt m =
595
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
596
  fprintf fmt "%a *_alloc;@,_alloc = (%a *) malloc(sizeof(%a));@,assert(_alloc);@,%a%areturn _alloc;"
597
    pp_machine_memtype_name m.mname.node_id
598
    pp_machine_memtype_name m.mname.node_id
599
    pp_machine_memtype_name m.mname.node_id
600
    (Utils.fprintf_list ~sep:"" print_alloc_array) array_mem
601
    (Utils.fprintf_list ~sep:"" print_alloc_instance) m.minstances
602

    
603
let print_step_code fmt m self =
604
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
605
  then
606
    (* C99 code *)
607
    let array_mems = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
608
    fprintf fmt "@[<v 2>%a {@,%a%t%a%t@,%a%a%t%t@]@,}@.@."
609
      (print_step_prototype self) (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
610
      (* locals *)
611
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
612
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
613
      (* array mems *)
614
      (Utils.fprintf_list ~sep:";@," (pp_c_decl_array_mem self)) array_mems
615
      (Utils.pp_final_char_if_non_empty ";@," array_mems)
616
      (* check assertions *)
617
      (pp_c_checks self) m
618
      (* instrs *)
619
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr m self)) m.mstep.step_instrs
620
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
621
      (fun fmt -> fprintf fmt "return;")
622
  else
623
    (* C90 code *)
624
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
625
    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
626
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
627
      (print_step_prototype self) (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
628
      (* locals *)
629
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
630
      (Utils.pp_final_char_if_non_empty ";" base_locals)
631
      (* check assertions *)
632
      (pp_c_checks self) m
633
      (* instrs *)
634
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr m self)) m.mstep.step_instrs
635
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
636
      (fun fmt -> fprintf fmt "return;")
637

    
638
let print_machine fmt m =
639
  (* Alloc function, only if non static mode *)
640
  if (not !Options.static_mem) then  
641
    (
642
      fprintf fmt "@[<v 2>%a {@,%a@]@,}@.@."
643
	print_alloc_prototype (m.mname.node_id, m.mstatic)
644
	print_alloc_code m;
645
    );
646
  if m.mname.node_id = arrow_id then () else ( (* We don't print arrow function *)
647
    let self = mk_self m in
648
    (* Reset function *)
649
    fprintf fmt "@[<v 2>%a {@,%a%treturn;@]@,}@.@."
650
      (print_reset_prototype self) (m.mname.node_id, m.mstatic)
651
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr m self)) m.minit
652
      (Utils.pp_newline_if_non_empty m.minit);
653
    (* Step function *)
654
    print_step_code fmt m self
655
  )
656

    
657
(********************************************************************************************)
658
(*                         Main related functions                                           *)
659
(********************************************************************************************)
660

    
661
let print_get_input fmt v =
662
  match v.var_type.Types.tdesc with
663
    | Types.Tint -> fprintf fmt "_get_int(\"%s\")" v.var_id
664
    | Types.Tbool -> fprintf fmt "_get_bool(\"%s\")" v.var_id
665
    | Types.Treal -> fprintf fmt "_get_double(\"%s\")" v.var_id
666
    | _ -> assert false
667

    
668
let print_put_outputs fmt ol = 
669
  let po fmt o =
670
    match o.var_type.Types.tdesc with
671
    | Types.Tint -> fprintf fmt "_put_int(\"%s\", %s)" o.var_id o.var_id
672
    | Types.Tbool -> fprintf fmt "_put_bool(\"%s\", %s)" o.var_id o.var_id
673
    | Types.Treal -> fprintf fmt "_put_double(\"%s\", %s)" o.var_id o.var_id
674
    | _ -> assert false
675
  in
676
  List.iter (fprintf fmt "@ %a;" po) ol
677

    
678
let print_main_fun machines m fmt =
679
  let mname = m.mname.node_id in
680
  let main_mem =
681
    if (!Options.static_mem && !Options.main_node <> "")
682
    then "&main_mem"
683
    else "main_mem" in
684
  fprintf fmt "@[<v 2>int main (int argc, char *argv[]) {@ ";
685
  fprintf fmt "/* Declaration of inputs/outputs variables */@ ";
686
  List.iter 
687
    (fun v -> fprintf fmt "%a = %a;@ " (pp_c_type v.var_id) v.var_type pp_c_initialize v.var_type
688
    ) m.mstep.step_inputs;
689
  List.iter 
690
    (fun v -> fprintf fmt "%a = %a;@ " (pp_c_type v.var_id) v.var_type pp_c_initialize v.var_type
691
    ) m.mstep.step_outputs;
692
  fprintf fmt "@ /* Main memory allocation */@ ";
693
  if (!Options.static_mem && !Options.main_node <> "")
694
  then (fprintf fmt "%a(main_mem);@ " pp_machine_static_alloc_name mname)
695
  else (fprintf fmt "%a *main_mem = %a();@ " pp_machine_memtype_name mname pp_machine_alloc_name mname);
696
  fprintf fmt "@ /* Initialize the main memory */@ ";
697
  fprintf fmt "%a(%s);@ " pp_machine_reset_name mname main_mem;
698
  fprintf fmt "@ ISATTY = isatty(0);@ ";
699
  fprintf fmt "@ /* Infinite loop */@ ";
700
  fprintf fmt "@[<v 2>while(1){@ ";
701
  fprintf fmt  "fflush(stdout);@ ";
702
  List.iter 
703
    (fun v -> fprintf fmt "%s = %a;@ "
704
      v.var_id
705
      print_get_input v
706
    ) m.mstep.step_inputs;
707
  (match m.mstep.step_outputs with
708
    (* | [] -> ( *)
709
    (*   fprintf fmt "%a(%a%t%s);@ "  *)
710
    (* 	pp_machine_step_name mname *)
711
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs *)
712
    (* 	(pp_final_char_if_non_empty ", " m.mstep.step_inputs) *)
713
    (* 	main_mem *)
714
    (* ) *)
715
    (* | [o] -> ( *)
716
    (*   fprintf fmt "%s = %a(%a%t%a, %s);%a" *)
717
    (* 	o.var_id *)
718
    (* 	pp_machine_step_name mname *)
719
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs *)
720
    (* 	(pp_final_char_if_non_empty ", " m.mstep.step_inputs) *)
721
    (* 	(Utils.fprintf_list ~sep:", " (fun fmt v -> fprintf fmt "&%s" v.var_id)) m.mstep.step_outputs *)
722
    (* 	main_mem *)
723
    (* 	print_put_outputs [o]) *)
724
    | _ -> (
725
      fprintf fmt "%a(%a%t%a, %s);%a"
726
	pp_machine_step_name mname
727
	(Utils.fprintf_list ~sep:", " (fun fmt v -> pp_print_string fmt v.var_id)) m.mstep.step_inputs
728
	(Utils.pp_final_char_if_non_empty ", " m.mstep.step_inputs)
729
	(Utils.fprintf_list ~sep:", " (fun fmt v -> fprintf fmt "&%s" v.var_id)) m.mstep.step_outputs
730
	main_mem
731
	print_put_outputs m.mstep.step_outputs)
732
  );
733
  fprintf fmt "@]@ }@ ";
734
  fprintf fmt "return 1;";
735
  fprintf fmt "@]@ }@."       
736

    
737
let print_main_header fmt =
738
  fprintf fmt "#include <stdio.h>@.#include <unistd.h>@.#include \"io_frontend.h\"@."
739

    
740
let rec pp_c_type_decl cpt var fmt tdecl =
741
  match tdecl with
742
  | Tydec_any           -> assert false
743
  | Tydec_int           -> fprintf fmt "int %s" var
744
  | Tydec_real          -> fprintf fmt "double %s" var
745
  | Tydec_float         -> fprintf fmt "float %s" var
746
  | Tydec_bool          -> fprintf fmt "_Bool %s" var
747
  | Tydec_clock ty      -> pp_c_type_decl cpt var fmt ty
748
  | Tydec_const c       -> fprintf fmt "%s %s" c var
749
  | Tydec_array (d, ty) -> fprintf fmt "%a[%a]" (pp_c_type_decl cpt var) ty pp_c_dimension d
750
  | Tydec_enum tl ->
751
    begin
752
      incr cpt;
753
      fprintf fmt "enum _enum_%d { %a } %s" !cpt (Utils.fprintf_list ~sep:", " pp_print_string) tl var
754
    end
755

    
756
let print_type_definitions fmt =
757
  let cpt_type = ref 0 in
758
  Hashtbl.iter (fun typ def ->
759
    match typ with
760
    | Tydec_const var ->
761
      fprintf fmt "typedef %a;@.@."
762
	(pp_c_type_decl cpt_type var) def
763
    | _        -> ()) type_table
764

    
765
(********************************************************************************************)
766
(*                         Translation function                                             *)
767
(********************************************************************************************)
768
    
769
let translate_to_c header_fmt source_fmt spec_fmt_opt basename prog machines =
770
  (* Generating H file *)
771

    
772
  (* Include once: start *)
773
  let baseNAME = String.uppercase basename in
774
  let baseNAME = Str.global_replace (Str.regexp "\\.\\|\\ ") "_" baseNAME in
775
  (* Print the svn version number and the supported C standard (C90 or C99) *)
776
  print_version header_fmt;
777
  fprintf header_fmt "#ifndef _%s@.#define _%s@." baseNAME baseNAME;
778
(*
779
  let machine_iter = compute_dep_machines machines in
780
*)
781
  (* Print the struct of all machines. This need to be done following the good
782
     order. *)
783
  fprintf header_fmt "/* Struct declarations */@.";
784
  List.iter (print_machine_struct header_fmt) machines;
785
  pp_print_newline header_fmt ();
786

    
787
  (* Print the prototypes of all machines *)
788
  fprintf header_fmt "/* Nodes declarations */@.";
789
  List.iter (print_machine_decl header_fmt) machines;
790
  pp_print_newline header_fmt ();
791
  (* Include once: end *)
792
  fprintf header_fmt "#endif@.";
793
  pp_print_newline header_fmt ();
794

    
795
  (* Generating C file *)
796
  
797
  (* If a main node is identified, generate a main function for it *)
798
  let main_include, main_print =
799
    match !Options.main_node with
800
      | "" -> (fun _ -> ()), (fun _ -> ())
801
      | main_node -> ( 
802
	let main_node_opt = 
803
	  List.fold_left 
804
	  (fun res m -> 
805
	    match res with 
806
	      | Some _ -> res 
807
	      | None -> if m.mname.node_id = main_node then Some m else None)
808
	  None machines
809
      in 
810
      match main_node_opt with
811
	| None -> eprintf "Unable to find a main node named %s@.@?" main_node; (fun _ -> ()), (fun _ -> ())
812
	| Some m -> print_main_header, print_main_fun machines m
813
    )
814
  in
815
  main_include source_fmt;
816
  fprintf source_fmt "#include <stdlib.h>@.#include <assert.h>@.#include \"%s\"@.@." (basename^".h");
817
  (* Print the svn version number and the supported C standard (C90 or C99) *)
818
  print_version source_fmt;
819
  (* Print the prototype of imported nodes *)
820
  fprintf source_fmt "/* Imported nodes declarations */@.";
821
  fprintf source_fmt "@[<v>";
822
  List.iter (print_prototype source_fmt) prog;
823
  fprintf source_fmt "@]@.";
824
  (* Print the type definitions from the type table *)
825
  print_type_definitions source_fmt;
826
  (* Print consts *)
827
  fprintf source_fmt "/* Global constants */@.";
828
  List.iter (fun c -> print_const source_fmt c) (get_consts prog); 
829
  pp_print_newline source_fmt ();
830
  (* Print nodes one by one (in the previous order) *)
831
  List.iter (print_machine source_fmt) machines;
832
  main_print source_fmt
833
  
834

    
835

    
836

    
837

    
838
(* Local Variables: *)
839
(* compile-command:"make -C .." *)
840
(* End: *)