Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / machine_code.ml @ 70df2f87

History | View | Annotate | Download (18.5 KB)

1
(********************************************************************)
2
(*                                                                  *)
3
(*  The LustreC compiler toolset   /  The LustreC Development Team  *)
4
(*  Copyright 2012 -    --   ONERA - CNRS - INPT                    *)
5
(*                                                                  *)
6
(*  LustreC is free software, distributed WITHOUT ANY WARRANTY      *)
7
(*  under the terms of the GNU Lesser General Public License        *)
8
(*  version 2.1.                                                    *)
9
(*                                                                  *)
10
(********************************************************************)
11

    
12
open LustreSpec
13
open Corelang
14
open Clocks
15
open Causality
16

    
17
exception NormalizationError
18

    
19
module OrdVarDecl:Map.OrderedType with type t=var_decl =
20
  struct type t = var_decl;; let compare = compare end
21

    
22
module ISet = Set.Make(OrdVarDecl)
23

    
24
type value_t = 
25
  | Cst of constant
26
  | LocalVar of var_decl
27
  | StateVar of var_decl
28
  | Fun of ident * value_t list 
29
  | Array of value_t list
30
  | Access of value_t * value_t
31
  | Power of value_t * value_t
32

    
33
type instr_t =
34
  | MLocalAssign of var_decl * value_t
35
  | MStateAssign of var_decl * value_t
36
  | MReset of ident
37
  | MStep of var_decl list * ident * value_t list
38
  | MBranch of value_t * (label * instr_t list) list
39
 
40
let rec pp_val fmt v =
41
  match v with
42
    | Cst c         -> Printers.pp_const fmt c 
43
    | LocalVar v    -> Format.pp_print_string fmt v.var_id
44
    | StateVar v    -> Format.pp_print_string fmt v.var_id
45
    | Array vl      -> Format.fprintf fmt "[%a]" (Utils.fprintf_list ~sep:", " pp_val)  vl
46
    | Access (t, i) -> Format.fprintf fmt "%a[%a]" pp_val t pp_val i
47
    | Power (v, n)  -> Format.fprintf fmt "(%a^%a)" pp_val v pp_val n
48
    | Fun (n, vl)   -> Format.fprintf fmt "%s (%a)" n (Utils.fprintf_list ~sep:", " pp_val)  vl
49

    
50
let rec pp_instr fmt i =
51
  match i with 
52
    | MLocalAssign (i,v) -> Format.fprintf fmt "%s<-l- %a" i.var_id pp_val v
53
    | MStateAssign (i,v) -> Format.fprintf fmt "%s<-s- %a" i.var_id pp_val v
54
    | MReset i           -> Format.fprintf fmt "reset %s" i
55
    | MStep (il, i, vl)  ->
56
      Format.fprintf fmt "%a = %s (%a)"
57
	(Utils.fprintf_list ~sep:", " (fun fmt v -> Format.pp_print_string fmt v.var_id)) il
58
	i      
59
	(Utils.fprintf_list ~sep:", " pp_val) vl
60
    | MBranch (g,hl)     ->
61
      Format.fprintf fmt "@[<v 2>case(%a) {@,%a@,}@]"
62
	pp_val g
63
	(Utils.fprintf_list ~sep:"@," pp_branch) hl
64

    
65
and pp_branch fmt (t, h) =
66
  Format.fprintf fmt "@[<v 2>%s:@,%a@]" t (Utils.fprintf_list ~sep:"@," pp_instr) h
67

    
68
type step_t = {
69
  step_checks: (Location.t * value_t) list;
70
  step_inputs: var_decl list;
71
  step_outputs: var_decl list;
72
  step_locals: var_decl list;
73
  step_instrs: instr_t list;
74
  step_asserts: value_t list;
75
}
76

    
77
type static_call = top_decl * (Dimension.dim_expr list)
78

    
79
type machine_t = {
80
  mname: node_desc;
81
  mmemory: var_decl list;
82
  mcalls: (ident * static_call) list; (* map from stateful/stateless instance to node, no internals *)
83
  minstances: (ident * static_call) list; (* sub-map of mcalls, from stateful instance to node *)
84
  minit: instr_t list;
85
  mstatic: var_decl list; (* static inputs only *)
86
  mstep: step_t;
87
  mspec: node_annot option;
88
  mannot: expr_annot list;
89
}
90

    
91
let pp_step fmt s =
92
  Format.fprintf fmt "@[<v>inputs : %a@ outputs: %a@ locals : %a@ checks : %a@ instrs : @[%a@]@ asserts : @[%a@]@]@ "
93
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_inputs
94
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_outputs
95
    (Utils.fprintf_list ~sep:", " Printers.pp_var) s.step_locals
96
    (Utils.fprintf_list ~sep:", " (fun fmt (_, c) -> pp_val fmt c)) s.step_checks
97
    (Utils.fprintf_list ~sep:"@ " pp_instr) s.step_instrs
98
    (Utils.fprintf_list ~sep:", " pp_val) s.step_asserts
99

    
100

    
101
let pp_static_call fmt (node, args) =
102
 Format.fprintf fmt "%s<%a>"
103
   (node_name node)
104
   (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) args
105

    
106
let pp_machine fmt m =
107
  Format.fprintf fmt 
108
    "@[<v 2>machine %s@ mem      : %a@ instances: %a@ init     : %a@ step     :@   @[<v 2>%a@]@ @  spec : @[%t@]@  annot : @[%a@]@]@ "
109
    m.mname.node_id
110
    (Utils.fprintf_list ~sep:", " Printers.pp_var) m.mmemory
111
    (Utils.fprintf_list ~sep:", " (fun fmt (o1, o2) -> Format.fprintf fmt "(%s, %a)" o1 pp_static_call o2)) m.minstances
112
    (Utils.fprintf_list ~sep:"@ " pp_instr) m.minit
113
    pp_step m.mstep
114
    (fun fmt -> match m.mspec with | None -> () | Some spec -> Printers.pp_spec fmt spec)
115
    (Utils.fprintf_list ~sep:"@ " Printers.pp_expr_annot) m.mannot
116

    
117
(* Returns the declared stateless status and the computed one. *)
118
let get_stateless_status m =
119
 (m.mname.node_dec_stateless, Utils.desome m.mname.node_stateless)
120

    
121
let is_input m id =
122
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_inputs
123

    
124
let is_output m id =
125
  List.exists (fun o -> o.var_id = id.var_id) m.mstep.step_outputs
126

    
127
let is_memory m id =
128
  List.exists (fun o -> o.var_id = id.var_id) m.mmemory
129

    
130
let conditional c t e =
131
  MBranch(c, [ (tag_true, t); (tag_false, e) ])
132

    
133
let dummy_var_decl name typ =
134
  {
135
    var_id = name;
136
    var_dec_type = dummy_type_dec;
137
    var_dec_clock = dummy_clock_dec;
138
    var_dec_const = false;
139
    var_type =  typ;
140
    var_clock = Clocks.new_ck (Clocks.Cvar Clocks.CSet_all) true;
141
    var_loc = Location.dummy_loc
142
  }
143

    
144
let arrow_id = "_arrow"
145

    
146
let arrow_typ = Types.new_ty Types.Tunivar
147

    
148
let arrow_desc =
149
  {
150
    node_id = arrow_id;
151
    node_type = Type_predef.type_bin_poly_op;
152
    node_clock = Clock_predef.ck_bin_univ;
153
    node_inputs= [dummy_var_decl "_in1" arrow_typ; dummy_var_decl "_in2" arrow_typ];
154
    node_outputs= [dummy_var_decl "_out" arrow_typ];
155
    node_locals= [];
156
    node_gencalls = [];
157
    node_checks = [];
158
    node_asserts = [];
159
    node_eqs= [];
160
    node_dec_stateless = false;
161
    node_stateless = Some false;
162
    node_spec = None;
163
    node_annot = [];  }
164

    
165
let arrow_top_decl =
166
  {
167
    top_decl_desc = Node arrow_desc;
168
    top_decl_owner = Version.prefix;
169
    top_decl_itf = false;
170
    top_decl_loc = Location.dummy_loc
171
  }
172

    
173
let arrow_machine =
174
  let state = "_first" in
175
  let var_state = dummy_var_decl state (Types.new_ty Types.Tbool) in
176
  let var_input1 = List.nth arrow_desc.node_inputs 0 in
177
  let var_input2 = List.nth arrow_desc.node_inputs 1 in
178
  let var_output = List.nth arrow_desc.node_outputs 0 in
179
  {
180
    mname = arrow_desc;
181
    mmemory = [var_state];
182
    mcalls = [];
183
    minstances = [];
184
    minit = [MStateAssign(var_state, Cst (const_of_bool true))];
185
    mstatic = [];
186
    mstep = {
187
      step_inputs = arrow_desc.node_inputs;
188
      step_outputs = arrow_desc.node_outputs;
189
      step_locals = [];
190
      step_checks = [];
191
      step_instrs = [conditional (StateVar var_state)
192
			         [MStateAssign(var_state, Cst (const_of_bool false));
193
                                  MLocalAssign(var_output, LocalVar var_input1)]
194
                                 [MLocalAssign(var_output, LocalVar var_input2)] ];
195
      step_asserts = [];
196
    };
197
    mspec = None;
198
    mannot = [];
199
  }
200

    
201
let new_instance =
202
  let cpt = ref (-1) in
203
  fun caller callee tag ->
204
    begin
205
      let o =
206
	if Stateless.check_node callee then
207
	  node_name callee
208
	else
209
	  Printf.sprintf "ni_%d" (incr cpt; !cpt) in
210
      let o =
211
	if !Options.ansi && is_generic_node callee
212
	then Printf.sprintf "%s_inst_%d" o (Utils.position (fun e -> e.expr_tag = tag) caller.node_gencalls)
213
	else o in
214
      o
215
    end
216

    
217
(* translate_<foo> : node -> context -> <foo> -> machine code/expression *)
218
(* the context contains  m : state aka memory variables  *)
219
(*                      si : initialization instructions *)
220
(*                       j : node aka machine instances  *)
221
(*                       d : local variables             *)
222
(*                       s : step instructions           *)
223
let translate_ident node (m, si, j, d, s) id =
224
  try (* id is a node var *)
225
    let var_id = get_node_var id node in
226
    if ISet.exists (fun v -> v.var_id = id) m
227
    then StateVar var_id
228
    else LocalVar var_id
229
  with Not_found ->
230
    try (* id is a constant *)
231
      LocalVar (Corelang.var_decl_of_const (const_of_top (Hashtbl.find Corelang.consts_table id)))
232
    with Not_found ->
233
      (* id is a tag *)
234
      Cst (Const_tag id)
235

    
236
let rec control_on_clock node ((m, si, j, d, s) as args) ck inst =
237
 match (Clocks.repr ck).cdesc with
238
 | Con    (ck1, cr, l) ->
239
   let id  = Clocks.const_of_carrier cr in
240
   control_on_clock node args ck1 (MBranch (translate_ident node args id,
241
					    [l, [inst]] ))
242
 | _                   -> inst
243

    
244
let rec join_branches hl1 hl2 =
245
 match hl1, hl2 with
246
 | []          , _            -> hl2
247
 | _           , []           -> hl1
248
 | (t1, h1)::q1, (t2, h2)::q2 ->
249
   if t1 < t2 then (t1, h1) :: join_branches q1 hl2 else
250
   if t1 > t2 then (t2, h2) :: join_branches hl1 q2
251
   else (t1, List.fold_right join_guards h1 h2) :: join_branches q1 q2
252

    
253
and join_guards inst1 insts2 =
254
 match inst1, insts2 with
255
 | _                   , []                               ->
256
   [inst1]
257
 | MBranch (x1, hl1), MBranch (x2, hl2) :: q when x1 = x2 ->
258
   MBranch (x1, join_branches (sort_handlers hl1) (sort_handlers hl2))
259
   :: q
260
 | _ -> inst1 :: insts2
261

    
262
let join_guards_list insts =
263
 List.fold_right join_guards insts []
264

    
265
(* specialize predefined (polymorphic) operators
266
   wrt their instances, so that the C semantics 
267
   is preserved *)
268
let specialize_to_c expr =
269
 match expr.expr_desc with
270
 | Expr_appl (id, e, r) ->
271
   if List.exists (fun e -> Types.is_bool_type e.expr_type) (expr_list_of_expr e)
272
   then let id =
273
	  match id with
274
	  | "="  -> "equi"
275
	  | "!=" -> "xor"
276
	  | _    -> id in
277
	{ expr with expr_desc = Expr_appl (id, e, r) }
278
   else expr
279
 | _ -> expr
280

    
281
let specialize_op expr =
282
  match !Options.output with
283
  | "C" -> specialize_to_c expr
284
  | _   -> expr
285

    
286
let rec translate_expr node ((m, si, j, d, s) as args) expr =
287
 let expr = specialize_op expr in
288
 match expr.expr_desc with
289
 | Expr_const v                     -> Cst v
290
 | Expr_ident x                     -> translate_ident node args x
291
 | Expr_array el                    -> Array (List.map (translate_expr node args) el)
292
 | Expr_access (t, i)               -> Access (translate_expr node args t, translate_expr node args (expr_of_dimension i))
293
 | Expr_power  (e, n)               -> Power  (translate_expr node args e, translate_expr node args (expr_of_dimension n))
294
 | Expr_tuple _
295
 | Expr_arrow _ 
296
 | Expr_fby _
297
 | Expr_pre _                       -> (Printers.pp_expr Format.err_formatter expr; Format.pp_print_flush Format.err_formatter (); raise NormalizationError)
298
 | Expr_when    (e1, _, _)          -> translate_expr node args e1
299
 | Expr_merge   (x, _)              -> raise NormalizationError
300
 | Expr_appl (id, e, _) when Basic_library.is_internal_fun id ->
301
   let nd = node_from_name id in
302
   Fun (node_name nd, List.map (translate_expr node args) (expr_list_of_expr e))
303
 | Expr_ite (g,t,e) -> (
304
   (* special treatment depending on the active backend. For horn backend, ite
305
      are preserved in expression. While they are removed for C or Java
306
      backends. *)
307
   match !Options.output with | "horn" -> 
308
     Fun ("ite", [translate_expr node args g; translate_expr node args t; translate_expr node args e])
309
   | "C" | "java" | _ -> 
310
     (Printers.pp_expr Format.err_formatter expr; Format.pp_print_flush Format.err_formatter (); raise NormalizationError)
311
 )
312
 | _                   -> raise NormalizationError
313

    
314
let translate_guard node args expr =
315
  match expr.expr_desc with
316
  | Expr_ident x  -> translate_ident node args x
317
  | _ -> (Format.eprintf "internal error: translate_guard %s %a@." node.node_id Printers.pp_expr expr;assert false)
318

    
319
let rec translate_act node ((m, si, j, d, s) as args) (y, expr) =
320
  match expr.expr_desc with
321
  | Expr_ite   (c, t, e) -> let g = translate_guard node args c in
322
			    conditional g [translate_act node args (y, t)]
323
                              [translate_act node args (y, e)]
324
  | Expr_merge (x, hl)   -> MBranch (translate_ident node args x, List.map (fun (t,  h) -> t, [translate_act node args (y, h)]) hl)
325
  | _                    -> MLocalAssign (y, translate_expr node args expr)
326

    
327
let reset_instance node args i r c =
328
  match r with
329
  | None        -> []
330
  | Some (x, l) -> [control_on_clock node args c (MBranch (translate_ident node args x, [l, [MReset i]]))]
331

    
332
let translate_eq node ((m, si, j, d, s) as args) eq =
333
  (*Format.eprintf "translate_eq %a with clock %a@." Printers.pp_node_eq eq Clocks.print_ck eq.eq_rhs.expr_clock;*)
334
  match eq.eq_lhs, eq.eq_rhs.expr_desc with
335
  | [x], Expr_arrow (e1, e2)                     ->
336
    let var_x = get_node_var x node in
337
    let o = new_instance node arrow_top_decl eq.eq_rhs.expr_tag in
338
    let c1 = translate_expr node args e1 in
339
    let c2 = translate_expr node args e2 in
340
    (m,
341
     MReset o :: si,
342
     Utils.IMap.add o (arrow_top_decl, []) j,
343
     d,
344
     (control_on_clock node args eq.eq_rhs.expr_clock (MStep ([var_x], o, [c1;c2]))) :: s)
345
  | [x], Expr_pre e1 when ISet.mem (get_node_var x node) d     ->
346
    let var_x = get_node_var x node in
347
    (ISet.add var_x m,
348
     si,
349
     j,
350
     d,
351
     control_on_clock node args eq.eq_rhs.expr_clock (MStateAssign (var_x, translate_expr node args e1)) :: s)
352
  | [x], Expr_fby (e1, e2) when ISet.mem (get_node_var x node) d ->
353
    let var_x = get_node_var x node in
354
    (ISet.add var_x m,
355
     MStateAssign (var_x, translate_expr node args e1) :: si,
356
     j,
357
     d,
358
     control_on_clock node args eq.eq_rhs.expr_clock (MStateAssign (var_x, translate_expr node args e2)) :: s)
359

    
360
  | p  , Expr_appl (f, arg, r) when not (Basic_library.is_internal_fun f) ->
361
    let var_p = List.map (fun v -> get_node_var v node) p in
362
    let el = expr_list_of_expr arg in
363
    let vl = List.map (translate_expr node args) el in
364
    let node_f = node_from_name f in
365
    let call_f =
366
      node_f,
367
      NodeDep.filter_static_inputs (node_inputs node_f) el in 
368
    let o = new_instance node node_f eq.eq_rhs.expr_tag in
369
    let call_ck = Clocks.new_var true in
370
    Clock_calculus.unify_imported_clock (Some call_ck) eq.eq_rhs.expr_clock eq.eq_rhs.expr_loc;
371
    (m,
372
     (if Stateless.check_node node_f then si else MReset o :: si),
373
     Utils.IMap.add o call_f j,
374
     d,
375
     reset_instance node args o r eq.eq_rhs.expr_clock @
376
       (control_on_clock node args call_ck (MStep (var_p, o, vl))) :: s)
377

    
378
   (* special treatment depending on the active backend. For horn backend, x = ite (g,t,e)
379
      are preserved. While they are replaced as if g then x = t else x = e in  C or Java
380
      backends. *)
381
  | [x], Expr_ite   (c, t, e) 
382
    when (match !Options.output with | "horn" -> true | "C" | "java" | _ -> false)
383
      -> 
384
    let var_x = get_node_var x node in
385
    (m, 
386
     si, 
387
     j, 
388
     d, 
389
     (control_on_clock node args eq.eq_rhs.expr_clock 
390
	(MLocalAssign (var_x, translate_expr node args eq.eq_rhs))::s)
391
    )
392
      
393
  | [x], _                                       -> (
394
    let var_x = get_node_var x node in
395
    (m, si, j, d, 
396
     control_on_clock 
397
       node
398
       args
399
       eq.eq_rhs.expr_clock
400
       (translate_act node args (var_x, eq.eq_rhs)) :: s
401
    )
402
  )
403
  | _                                            ->
404
    begin
405
      Format.eprintf "unsupported equation: %a@?" Printers.pp_node_eq eq;
406
      assert false
407
    end
408

    
409
let find_eq xl eqs =
410
  let rec aux accu eqs =
411
      match eqs with
412
	| [] ->
413
	  begin
414
	    Format.eprintf "Looking for variables %a in the following equations@.%a@."
415
	      (Utils.fprintf_list ~sep:" , " (fun fmt v -> Format.fprintf fmt "%s" v)) xl
416
	      Printers.pp_node_eqs eqs;
417
	    assert false
418
	  end
419
	| hd::tl -> 
420
	  if List.exists (fun x -> List.mem x hd.eq_lhs) xl then hd, accu@tl else aux (hd::accu) tl
421
    in
422
    aux [] eqs
423

    
424
(* Sort the set of equations of node [nd] according 
425
   to the computed schedule [sch]
426
*)
427
let sort_equations_from_schedule nd sch =
428
(*  Format.eprintf "%s schedule: %a@."
429
		 nd.node_id
430
		 (Utils.fprintf_list ~sep:" ; " Scheduling.pp_eq_schedule) sch;*)
431
  let split_eqs = Splitting.tuple_split_eq_list nd.node_eqs in
432
  let eqs_rev, remainder =
433
    List.fold_left 
434
      (fun (accu, node_eqs_remainder) vl -> 
435
       if List.exists (fun eq -> List.exists (fun v -> List.mem v eq.eq_lhs) vl) accu
436
       then
437
	 (accu, node_eqs_remainder)
438
       else
439
	 let eq_v, remainder = find_eq vl node_eqs_remainder in
440
	 eq_v::accu, remainder
441
      ) 
442
      ([], split_eqs) 
443
      sch 
444
  in
445
  begin
446
    if List.length remainder > 0 then (
447
      Format.eprintf "Equations not used are@.%a@.Full equation set is:@.%a@.@?"
448
		     Printers.pp_node_eqs remainder
449
      		     Printers.pp_node_eqs nd.node_eqs;
450
      assert false);
451
    List.rev eqs_rev
452
  end
453

    
454
let translate_eqs node args eqs =
455
  List.fold_right (fun eq args -> translate_eq node args eq) eqs args;;
456

    
457
let translate_decl nd sch =
458
  (*Log.report ~level:1 (fun fmt -> Printers.pp_node fmt nd);*)
459

    
460
  let sorted_eqs = sort_equations_from_schedule nd sch in
461

    
462
  let init_args = ISet.empty, [], Utils.IMap.empty, List.fold_right (fun l -> ISet.add l) nd.node_locals ISet.empty, [] in
463
  (* memories, init instructions, node calls, local variables (including memories), step instrs *)
464
  let m, init, j, locals, s = translate_eqs nd init_args sorted_eqs in
465
  let mmap = Utils.IMap.fold (fun i n res -> (i, n)::res) j [] in
466
  {
467
    mname = nd;
468
    mmemory = ISet.elements m;
469
    mcalls = mmap;
470
    minstances = List.filter (fun (_, (n,_)) -> not (Stateless.check_node n)) mmap;
471
    minit = init;
472
    mstatic = List.filter (fun v -> v.var_dec_const) nd.node_inputs;
473
    mstep = {
474
      step_inputs = nd.node_inputs;
475
      step_outputs = nd.node_outputs;
476
      step_locals = ISet.elements (ISet.diff locals m);
477
      step_checks = List.map (fun d -> d.Dimension.dim_loc, translate_expr nd init_args (expr_of_dimension d)) nd.node_checks;
478
      step_instrs = (
479
	(* special treatment depending on the active backend. For horn backend,
480
	   common branches are not merged while they are in C or Java
481
	   backends. *)
482
	match !Options.output with
483
	| "horn" -> s
484
	| "C" | "java" | _ -> join_guards_list s
485
      );
486
      step_asserts = 
487
	let exprl = List.map (fun assert_ -> assert_.assert_expr ) nd.node_asserts in
488
	List.map (translate_expr nd init_args) exprl
489
	;
490
    };
491
    mspec = nd.node_spec;
492
    mannot = nd.node_annot;
493
  }
494

    
495
(** takes the global delcarations and the scheduling associated to each node *)
496
let translate_prog decls node_schs =
497
  let nodes = get_nodes decls in 
498
  List.map 
499
    (fun decl -> 
500
     let node = node_of_top decl in
501
      let sch = (Utils.IMap.find node.node_id node_schs).Scheduling.schedule in
502
      translate_decl node sch 
503
    ) nodes
504

    
505
let get_machine_opt name machines =  
506
  List.fold_left 
507
    (fun res m -> 
508
      match res with 
509
      | Some _ -> res 
510
      | None -> if m.mname.node_id = name then Some m else None)
511
    None machines
512
    
513

    
514
(* Local Variables: *)
515
(* compile-command:"make -C .." *)
516
(* End: *)