Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / main_lustre_compiler.ml @ ca88e660

History | View | Annotate | Download (15.6 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 Format
13
open Log
14

    
15
open Utils
16
open LustreSpec
17
open Compiler_common
18
 
19
exception StopPhase1 of program
20

    
21
let usage = "Usage: lustrec [options] \x1b[4msource-file\x1b[0m"
22

    
23
let extensions = [".ec"; ".lus"; ".lusi"]
24

    
25
(* print a .lusi header file from a source prog *)
26
let print_lusi prog dirname basename extension =
27
  let header = Lusic.extract_header dirname basename prog in
28
  let header_name = dirname ^ "/" ^ basename ^ extension in
29
  let h_out = open_out header_name in
30
  let h_fmt = formatter_of_out_channel h_out in
31
  begin
32
    Typing.uneval_prog_generics header;
33
    Clock_calculus.uneval_prog_generics header;
34
    Printers.pp_lusi_header h_fmt basename header;
35
    close_out h_out
36
  end
37

    
38
(* compile a .lusi header file *)
39
let compile_header dirname basename extension =
40
  let destname = !Options.dest_dir ^ "/" ^ basename in
41
  let header_name = basename ^ extension in
42
  let lusic_ext = extension ^ "c" in
43
  begin
44
    Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v>");
45
    let header = parse_header true (dirname ^ "/" ^ header_name) in
46
    ignore (Modules.load_header ISet.empty header);
47
    ignore (check_top_decls header);
48
    create_dest_dir ();
49
    Log.report ~level:1
50
      (fun fmt -> fprintf fmt ".. generating compiled header file %sc@," (destname ^ extension));
51
    Lusic.write_lusic true header destname lusic_ext;
52
    Lusic.print_lusic_to_h destname lusic_ext;
53
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.")
54
  end
55

    
56
(* check whether a source file has a compiled header,
57
   if not, generate the compiled header *)
58
let compile_source_to_header prog computed_types_env computed_clocks_env dirname basename extension =
59
  let destname = !Options.dest_dir ^ "/" ^ basename in
60
  let lusic_ext = extension ^ "c" in
61
  let header_name = destname ^ lusic_ext in
62
  begin
63
    if not (Sys.file_exists header_name) then
64
      begin
65
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating compiled header file %s@," header_name);
66
	Lusic.write_lusic false (Lusic.extract_header dirname basename prog) destname lusic_ext;
67
	Lusic.print_lusic_to_h destname lusic_ext
68
      end
69
    else
70
      let lusic = Lusic.read_lusic destname lusic_ext in
71
      if not lusic.Lusic.from_lusi then
72
	begin
73
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating compiled header file %s@," header_name);
74
       	  Lusic.write_lusic false (Lusic.extract_header dirname basename prog) destname lusic_ext;
75
(*List.iter (fun top_decl -> Format.eprintf "lusic: %a@." Printers.pp_decl top_decl) lusic.Lusic.contents;*)
76
	  Lusic.print_lusic_to_h destname lusic_ext
77
	end
78
      else
79
	begin
80
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. loading compiled header file %s@," header_name);
81
	  Modules.check_dependency lusic destname;
82
	  let header = lusic.Lusic.contents in
83
	  let (declared_types_env, declared_clocks_env) = get_envs_from_top_decls header in
84
	  check_compatibility
85
	    (prog, computed_types_env, computed_clocks_env)
86
	    (header, declared_types_env, declared_clocks_env)
87
	end
88
  end
89

    
90

    
91
let functional_backend () = 
92
  match !Options.output with
93
  | "horn" | "lustre" | "acsl" -> true
94
  | _ -> false
95

    
96
(* From prog to prog *)
97
let stage1 prog dirname basename =
98
  (* Removing automata *) 
99
  let prog = Automata.expand_decls prog in
100

    
101
  (* Importing source *)
102
  let _ = Modules.load_program ISet.empty prog in
103

    
104
  (* Extracting dependencies *)
105
  let dependencies, type_env, clock_env = import_dependencies prog in
106

    
107
  (* Sorting nodes *)
108
  let prog = SortProg.sort prog in
109

    
110
  (* Perform inlining before any analysis *)
111
  let orig, prog =
112
    if !Options.global_inline && !Options.main_node <> "" then
113
      (if !Options.witnesses then prog else []),
114
      Inliner.global_inline basename prog type_env clock_env
115
    else (* if !Option.has_local_inline *)
116
      [],
117
      Inliner.local_inline basename prog type_env clock_env
118
  in
119

    
120
  (* Checking stateless/stateful status *)
121
  if Plugins.check_force_stateful () then
122
    force_stateful_decls prog
123
  else
124
    check_stateless_decls prog;
125

    
126
  (* Typing *)
127
  let computed_types_env = type_decls type_env prog in
128

    
129
  (* Clock calculus *)
130
  let computed_clocks_env = clock_decls clock_env prog in
131

    
132
  (* Generating a .lusi header file only *)
133
  if !Options.lusi then
134
    (* We stop here the processing and produce the current prog. It will be
135
       exported as a lusi *)
136
    raise (StopPhase1 prog);
137

    
138
  (* Delay calculus *)
139
  (* TO BE DONE LATER (Xavier)
140
    if(!Options.delay_calculus)
141
    then
142
    begin
143
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. initialisation analysis@?");
144
    try
145
    Delay_calculus.delay_prog Basic_library.delay_env prog
146
    with (Delay.Error (loc,err)) as exc ->
147
    Location.print loc;
148
    eprintf "%a" Delay.pp_error err;
149
    Utils.track_exception ();
150
    raise exc
151
    end;
152
  *)
153

    
154
  (* Creating destination directory if needed *)
155
  create_dest_dir ();
156

    
157
  (* Compatibility with Lusi *)
158
  (* Checking the existence of a lusi (Lustre Interface file) *)
159
  let extension = ".lusi" in
160
  compile_source_to_header prog computed_types_env computed_clocks_env dirname basename extension;
161

    
162
  Typing.uneval_prog_generics prog;
163
  Clock_calculus.uneval_prog_generics prog;
164

    
165
  if !Options.global_inline && !Options.main_node <> "" && !Options.witnesses then
166
    begin
167
      let orig = Corelang.copy_prog orig in
168
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating witness file@,");
169
      check_stateless_decls orig;
170
      let _ = Typing.type_prog type_env orig in
171
      let _ = Clock_calculus.clock_prog clock_env orig in
172
      Typing.uneval_prog_generics orig;
173
      Clock_calculus.uneval_prog_generics orig;
174
      Inliner.witness
175
	basename
176
	!Options.main_node
177
	orig prog type_env clock_env
178
    end;
179

    
180
  (* Computes and stores generic calls for each node,
181
     only useful for ANSI C90 compliant generic node compilation *)
182
  if !Options.ansi then Causality.NodeDep.compute_generic_calls prog;
183
  (*Hashtbl.iter (fun id td -> match td.Corelang.top_decl_desc with
184
    Corelang.Node nd -> Format.eprintf "%s calls %a" id
185
    Causality.NodeDep.pp_generic_calls nd | _ -> ()) Corelang.node_table;*)
186

    
187
  (* Optimization of prog: 
188
     - Unfold consts 
189
     - eliminate trivial expressions
190
  *)
191
  let prog = 
192
    if !Options.const_unfold || !Options.optimization >= 4 then 
193
      Optimize_prog.prog_unfold_consts prog 
194
    else
195
      prog
196
  in
197

    
198
  (* Normalization phase *)
199
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. normalization@,");
200
  (* Special treatment of arrows in lustre backend. We want to keep them *)
201
  if !Options.output = "lustre" then
202
    Normalization.unfold_arrow_active := false;
203
  let prog = Normalization.normalize_prog prog in
204
  Log.report ~level:2 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
205

    
206
  let prog =
207
    if !Options.mpfr
208
    then
209
      begin
210
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. targetting MPFR library@,");
211
	Mpfr.inject_prog prog
212
      end
213
    else
214
      begin
215
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. keeping FP numbers@,");
216
	prog
217
      end in
218
  Log.report ~level:2 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
219

    
220
  (* Checking array accesses *)
221
  if !Options.check then
222
    begin
223
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. array access checks@,");
224
      Access.check_prog prog;
225
    end;
226

    
227
  prog, dependencies
228

    
229
(* prog -> machine *)
230

    
231
let stage2 prog =    
232

    
233
  (* Computation of node equation scheduling. It also breaks dependency cycles
234
     and warns about unused input or memory variables *)
235
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. scheduling@,");
236
  let prog, node_schs = Scheduling.schedule_prog prog in
237
  Log.report ~level:1 (fun fmt -> fprintf fmt "%a"              Scheduling.pp_warning_unused node_schs);
238
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_schedule node_schs);
239
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_fanin_table node_schs);
240
  Log.report ~level:5 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_dep_graph node_schs);
241
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
242

    
243
 (* Optimization of prog:
244
    - Unfold consts
245
    - eliminate trivial expressions
246
	TODO (PL): should we keep this phase or just remove it 
247
 *)
248
  let prog =
249
    if !Options.optimization >= 5 then
250
      begin
251
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. constants elimination@,");
252
	Optimize_prog.prog_unfold_consts prog
253
      end
254
    else
255
      prog
256
  in
257

    
258
  (* TODO Salsa optimize prog: 
259
     - emits warning for programs with pre inside expressions
260
     - make sure each node arguments and memory is bounded by a local annotation
261
     - introduce fresh local variables for each real pure subexpression
262
  *)
263
 (*  let prog =  *)
264
 (*    if true then *)
265
 (*      Salsa.Prog.normalize prog *)
266
 (*    else *)
267
 (*      prog *)
268
 (* in *)
269

    
270
  (* DFS with modular code generation *)
271
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines generation@ ");
272
  let machine_code = Machine_code.translate_prog prog node_schs in
273

    
274
   (* Optimize machine code *)
275
  let machine_code =
276
    if !Options.optimization >= 4 (* && !Options.output <> "horn" *) then
277
      begin
278
	Log.report ~level:1 
279
	  (fun fmt -> fprintf fmt ".. machines optimization: sub-expression elimination@,");
280
	Optimize_machine.machines_cse machine_code
281
      end
282
    else
283
      machine_code
284
  in
285
  
286
  (* Optimize machine code *)
287
  let machine_code, removed_table = 
288
    if !Options.optimization >= 2 (*&& !Options.output <> "horn"*) then
289
      begin
290
	Log.report ~level:1 (fun fmt -> fprintf fmt 
291
    ".. machines optimization: const. inlining (partial eval. with const)@,");
292
	Optimize_machine.machines_unfold (Corelang.get_consts prog) node_schs machine_code
293
      end
294
    else
295
      machine_code, IMap.empty
296
  in  
297
  (* Optimize machine code *)
298
  let machine_code =  (* TODO reactivate. I disabled it because output variables were removed *)
299
    if false && !Options.optimization >= 3 && not (functional_backend ()) then
300
      begin
301
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines optimization: minimize heap alloc by reusing vars@,");
302
	let node_schs    = Scheduling.remove_prog_inlined_locals removed_table node_schs in
303
	let reuse_tables = Scheduling.compute_prog_reuse_table node_schs in
304
	Optimize_machine.machines_fusion (Optimize_machine.machines_reuse_variables machine_code reuse_tables)
305
      end
306
    else
307
      machine_code
308
  in
309
  
310
  (* Salsa optimize machine code *)
311
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@ "
312
    (Utils.fprintf_list ~sep:"@ " Machine_code.pp_machine)
313
    machine_code);
314

    
315
  machine_code
316

    
317

    
318
let stage3 prog machine_code dependencies basename =
319
  (* Printing code *)
320
  let basename    =  Filename.basename basename in
321
  let destname = !Options.dest_dir ^ "/" ^ basename in
322
  match !Options.output with
323
      "C" -> 
324
	begin
325
	  let alloc_header_file = destname ^ "_alloc.h" in (* Could be changed *)
326
	  let source_lib_file = destname ^ ".c" in (* Could be changed *)
327
	  let source_main_file = destname ^ "_main.c" in (* Could be changed *)
328
	  let makefile_file = destname ^ ".makefile" in (* Could be changed *)
329
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. C code generation@,");
330
	  C_backend.translate_to_c
331
	    alloc_header_file source_lib_file source_main_file makefile_file
332
	    basename prog machine_code dependencies
333
	end
334
    | "java" ->
335
      begin
336
	failwith "Sorry, but not yet supported !"
337
    (*let source_file = basename ^ ".java" in
338
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. opening file %s@,@?" source_file);
339
      let source_out = open_out source_file in
340
      let source_fmt = formatter_of_out_channel source_out in
341
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. java code generation@,@?");
342
      Java_backend.translate_to_java source_fmt basename normalized_prog machine_code;*)
343
      end
344
    | "horn" ->
345
      begin
346
	let source_file = destname ^ ".smt2" in (* Could be changed *)
347
	let source_out = open_out source_file in
348
	let fmt = formatter_of_out_channel source_out in
349
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. hornification@,");
350
        Horn_backend.translate fmt basename prog (Machine_code.arrow_machine::machine_code);
351
	(* Tracability file if option is activated *)
352
	if !Options.horntraces then (
353
	let traces_file = destname ^ ".traces.xml" in (* Could be changed *)
354
	let traces_out = open_out traces_file in
355
	let fmt = formatter_of_out_channel traces_out in
356
        Log.report ~level:1 (fun fmt -> fprintf fmt ".. tracing info@,");
357
	Horn_backend_traces.traces_file fmt basename prog machine_code;
358
	)
359
      end
360
    | "lustre" ->
361
      begin
362
	let source_file = destname ^ ".lustrec.lus" in (* Could be changed *)
363
	let source_out = open_out source_file in
364
	let fmt = formatter_of_out_channel source_out in
365
	Printers.pp_prog fmt prog;
366
(*	Lustre_backend.translate fmt basename normalized_prog machine_code *)
367
	()
368
      end
369

    
370
    | _ -> assert false
371

    
372
(* compile a .lus source file *)
373
let compile_source dirname basename extension =
374

    
375
  Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v>");
376

    
377
  (* Parsing source *)
378
  let prog = parse_source (dirname ^ "/" ^ basename ^ extension) in
379

    
380
  let prog =
381
    if !Options.mpfr then
382
      Mpfr.mpfr_module::prog
383
    else
384
      prog
385
  in
386
  let prog, dependencies = 
387
    try 
388
      stage1 prog dirname basename
389
    with StopPhase1 prog -> (
390
      if !Options.lusi then
391
	begin
392
	  let lusi_ext = ".lusi" (* extension ^ "i" *) in
393
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating interface file %s@," (dirname ^ "/" ^ basename ^ lusi_ext));
394
	  print_lusi prog dirname basename lusi_ext;
395
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.");
396
	  exit 0
397
	end
398
      else
399
        assert false
400
    )
401
  in
402

    
403
  let machine_code = 
404
    stage2 prog 
405
  in
406

    
407
  let machine_code = Plugins.refine_machine_code prog machine_code in
408
  
409
  stage3 prog machine_code dependencies basename;
410
  begin
411
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.");
412
    (* We stop the process here *)
413
    exit 0
414
  end
415

    
416
let compile dirname basename extension =
417
  match extension with
418
  | ".lusi"  -> compile_header dirname basename extension
419
  | ".lus"   -> compile_source dirname basename extension
420
  | _        -> assert false
421

    
422
let anonymous filename =
423
  let ok_ext, ext = List.fold_left
424
    (fun (ok, ext) ext' ->
425
      if not ok && Filename.check_suffix filename ext' then
426
	true, ext'
427
      else
428
	ok, ext)
429
    (false, "") extensions in
430
  if ok_ext then
431
    let dirname = Filename.dirname filename in
432
    let basename = Filename.chop_suffix (Filename.basename filename) ext in
433
    compile dirname basename ext
434
  else
435
    raise (Arg.Bad ("Can only compile *.lusi, *.lus or *.ec files"))
436

    
437
let _ =
438
  Global.initialize ();
439
  Corelang.add_internal_funs ();
440
  try
441
    Printexc.record_backtrace true;
442

    
443
    let options = Options.options @ (Plugins.options ()) in
444
    
445
    Arg.parse options anonymous usage
446
  with
447
  | Parse.Syntax_err _ | Lexer_lustre.Error _
448
  | Types.Error (_,_) | Clocks.Error (_,_)
449
  | Corelang.Error _ (*| Task_set.Error _*)
450
  | Causality.Cycle _ -> exit 1
451
  | Sys_error msg -> (eprintf "Failure: %s@." msg)
452
  | exc -> (Utils.track_exception (); raise exc)
453

    
454
(* Local Variables: *)
455
(* compile-command:"make -C .." *)
456
(* End: *)