source: Deliverables/D2.2/8051-indexed-labels-branch/src/ERTL/ERTLInterpret.ml @ 1357

Last change on this file since 1357 was 1357, checked in by tranquil, 9 years ago
  • changed implementation of constant indexings with extensible arrays
  • work on ASM completed
  • next: optimizations!
File size: 16.2 KB
Line 
1
2(** This module provides an interpreter for the ERTL language. *)
3
4
5let error_prefix = "ERTL interpret"
6let error s = Error.global_error error_prefix s
7
8
9module Mem = Driver.ERTLMemory
10module Val = Mem.Value
11let chunk = Driver.ERTLMemory.int_size
12module Eval = I8051.Eval (Val)
13
14
15(* Memory *)
16
17type memory = ERTL.function_def Mem.memory
18
19(* Local environments. They associate a value to the pseudo-registers of the
20   function being executed. *)
21
22type local_env = Val.t Register.Map.t
23
24(* Hardware registers environments. They associate a value to each hardware
25   register. *)
26
27type hdw_reg_env = Val.t I8051.RegisterMap.t
28
29(* Call frames. The execution state has a call stack, each element of the stack
30   being composed of the local environment to resume the execution of the
31   caller. *)
32
33type stack_frame = local_env
34
35type indexing = CostLabel.const_indexing
36
37(* Execution states. *)
38
39type state =
40    { st_frs : stack_frame list ;
41      pc     : Val.address ;
42      isp    : Val.address ;
43      exit   : Val.address ;
44      lenv   : local_env ;
45      carry  : Val.t ;
46      renv   : hdw_reg_env ;
47      mem    : memory ;
48                        inds   : indexing list;
49      trace  : CostLabel.t list }
50
51
52(* Helpers *)
53
54let add_st_frs st frame = { st with st_frs = frame :: st.st_frs }
55let pop_st_frs st = match st.st_frs with
56  | [] -> error "Empty stack frames."
57  | lenv :: st_frs -> { st with st_frs = st_frs ; lenv = lenv }
58let change_pc st pc = { st with pc = pc }
59let change_isp st isp = { st with isp = isp }
60let change_exit st exit = { st with exit = exit }
61let change_lenv st lenv = { st with lenv = lenv }
62let change_carry st carry = { st with carry = carry }
63let change_renv st renv = { st with renv = renv }
64let change_mem st mem = { st with mem = mem }
65let change_trace st trace = { st with trace = trace }
66let add_trace st cost_lbl = change_trace st (cost_lbl :: st.trace)
67let ev_label st = CostLabel.ev_indexing (CostLabel.curr_const_ind st.inds)
68let new_ind st = { st with inds = CostLabel.new_const_ind st.inds }
69let forget_ind st = { st with inds = CostLabel.forget_const_ind st.inds }
70let enter_loop st = CostLabel.enter_loop st.inds
71let continue_loop st = CostLabel.continue_loop st.inds
72
73let empty_state =
74  { st_frs = [] ;
75    pc     = Val.null ;
76    isp    = Val.null ;
77    exit   = Val.null ;
78    lenv   = Register.Map.empty ;
79    carry  = Val.undef ;
80    renv   = I8051.RegisterMap.empty ;
81    mem    = Mem.empty ;
82                inds   = [] ;
83    trace  = [] }
84
85
86(* Each label of each function is associated an address. The base of this
87   address is the base of the function in memory. Inside a function, offsets are
88   bijectively associated to labels. *)
89
90module Labels_Offsets = Bijection.Make (Label) (Val.Offset)
91
92let labels_offsets_internal int_fun =
93  let f lbl _ (lbls_offs, i) =
94    (Labels_Offsets.add1 lbl i lbls_offs, Val.Offset.succ i) in
95  Label.Map.fold f int_fun.ERTL.f_graph
96
97(* [labels_offsets p] builds a bijection between the labels found in the
98   functions of [p] and some memory addresses. *)
99
100let labels_offsets p =
101  let f (lbls_offs, i) (_, def) = match def with
102    | ERTL.F_int int_fun -> labels_offsets_internal int_fun (lbls_offs, i)
103    | _ -> (lbls_offs, i) in
104  fst (List.fold_left f (Labels_Offsets.empty, Val.Offset.zero) p.ERTL.functs)
105
106let fun_def_of_ptr mem ptr = match Mem.find_fun_def mem ptr with
107  | ERTL.F_int def -> def
108  | _ -> error "Trying to fetch the definition of an external function."
109
110let fetch_stmt lbls_offs st =
111  let msg =
112    Printf.sprintf "%s does not point to a statement."
113      (Val.string_of_address st.pc) in
114  if Val.is_mem_address st.pc then
115    let off = Val.offset_of_address st.pc in
116    let def = fun_def_of_ptr st.mem st.pc in
117    let lbl = Labels_Offsets.find2 off lbls_offs in
118    Label.Map.find lbl def.ERTL.f_graph
119  else error msg
120
121let entry_pc lbls_offs ptr def =
122  let off = Labels_Offsets.find1 def.ERTL.f_entry lbls_offs in
123  Val.change_address_offset ptr off
124
125let init_fun_call lbls_offs st ptr def =
126  let f r lenv = Register.Map.add r Val.undef lenv in
127  let lenv = Register.Set.fold f def.ERTL.f_locals Register.Map.empty in
128  let pc = entry_pc lbls_offs ptr def in
129        let st = new_ind st in
130  change_lenv (change_pc st pc) lenv
131
132let next_pc lbls_offs st lbl =
133  let off = Labels_Offsets.find1 lbl lbls_offs in
134  change_pc st (Val.change_address_offset st.pc off)
135
136let framesize st =
137  if Val.is_mem_address st.pc then
138    let def = fun_def_of_ptr st.mem st.pc in
139    def.ERTL.f_stacksize
140  else error "No function at the given address."
141
142type register = Hdw of I8051.register | Psd of Register.t
143
144let add_reg r v st = match r with
145  | Hdw r ->
146    let renv = I8051.RegisterMap.add r v st.renv in
147    change_renv st renv
148  | Psd r ->
149    let lenv = Register.Map.add r v st.lenv in
150    change_lenv st lenv
151
152let get_reg r st = match r with
153  | Hdw r ->
154    if I8051.RegisterMap.mem r st.renv then I8051.RegisterMap.find r st.renv
155    else error ("Unknown hardware register " ^ (I8051.print_register r) ^ ".")
156  | Psd r ->
157    if Register.Map.mem r st.lenv then Register.Map.find r st.lenv
158    else error ("Unknown local register " ^ (Register.print r) ^ ".")
159
160let push st v =
161  let mem = Mem.store st.mem chunk st.isp v in
162  let isp = Val.add_address st.isp (Val.Offset.of_int chunk) in
163  change_mem (change_isp st isp) mem
164
165let pop st =
166  let isp = Val.add_address st.isp (Val.Offset.of_int (-chunk)) in
167  let st = change_isp st isp in
168  let v = Mem.load st.mem chunk st.isp in
169  (st, v)
170
171let get_ra st =
172  let (st, pch) = pop st in
173  let (st, pcl) = pop st in
174  [pcl ; pch]
175
176let save_ra lbls_offs st lbl =
177  let ra =
178    Val.change_address_offset st.pc (Labels_Offsets.find1 lbl lbls_offs) in
179  let st = push st (List.nth ra 0) in
180  let st = push st (List.nth ra 1) in
181  st
182
183let save_frame st = add_st_frs st st.lenv
184
185let label_of_pointer lbls_offs ptr =
186(*
187  Printf.printf "Retrieving label of %s\n%!" (Val.to_string ptr) ;
188*)
189  let off = Val.offset_of_address ptr in
190  Labels_Offsets.find2 off lbls_offs
191
192let pointer_of_label lbls_offs ptr lbl =
193  Val.change_address_offset ptr (Labels_Offsets.find1 lbl lbls_offs)
194
195let get_sp st =
196  List.map (fun r -> get_reg (Hdw r) st) [I8051.spl ; I8051.sph]
197
198let set_sp vs st =
199  let spl = List.nth vs 0 in
200  let sph = List.nth vs 1 in
201  let st = add_reg (Hdw I8051.spl) spl st in
202  let st = add_reg (Hdw I8051.sph) sph st in
203  st
204
205
206module InterpretExternal = Primitive.Interpret (Mem)
207
208let interpret_external mem f args = match InterpretExternal.t mem f args with
209  | (mem', InterpretExternal.V vs) -> (mem', vs)
210  | (mem', InterpretExternal.A addr) -> (mem', addr)
211
212let fetch_external_args f st =
213  let size = Mem.size_of_quantity (Primitive.args_byte_size f) in
214  let params = MiscPottier.prefix size I8051.parameters in
215  List.map (fun r -> get_reg (Hdw r) st) params
216
217let set_result st vs =
218  let f st (r, v) = add_reg (Hdw r) v st in
219  List.fold_left f st (MiscPottier.combine I8051.rets vs)
220
221let interpret_external_call st f next_pc =
222  let args = fetch_external_args f st in
223  let (mem, vs) = interpret_external st.mem f args in
224  let st = change_mem st mem in
225  let st = set_result st vs in
226  change_pc st next_pc
227
228let interpret_call lbls_offs st f ra =
229  let ptr = Mem.find_global st.mem f in
230  match Mem.find_fun_def st.mem ptr with
231    | ERTL.F_int def ->
232      let st = save_ra lbls_offs st ra in
233      let st = save_frame st in
234      init_fun_call lbls_offs st ptr def
235    | ERTL.F_ext def ->
236      let next_pc = 
237        Val.change_address_offset st.pc (Labels_Offsets.find1 ra lbls_offs) in
238      interpret_external_call st def.AST.ef_tag next_pc
239
240let interpret_return lbls_offs st =
241        let st = forget_ind st in
242  let st = pop_st_frs st in
243  let (st, pch) = pop st in
244  let (st, pcl) = pop st in
245  let pc = [pcl ; pch] in
246  change_pc st pc
247
248
249(* Interpret statements. *)
250
251let interpret_stmt lbls_offs st stmt =
252  let next_pc = next_pc lbls_offs in
253  match stmt with
254
255    | ERTL.St_skip lbl ->
256      next_pc st lbl
257
258    | ERTL.St_comment (s, lbl) ->
259(*
260      Printf.printf "*** %s ***\n\n%!" s ;
261*)
262      next_pc st lbl
263
264    | ERTL.St_cost (cost_lbl, lbl) ->
265                        let cost_lbl = ev_label st cost_lbl in 
266      let st = add_trace st cost_lbl in
267      next_pc st lbl
268
269    | ERTL.St_ind_0 (i, lbl) ->
270                        enter_loop st i;
271                        next_pc st lbl
272
273    | ERTL.St_ind_inc (i, lbl) ->
274      continue_loop st i; 
275      next_pc st lbl
276
277    | ERTL.St_get_hdw (destr, srcr, lbl) ->
278      let st = add_reg (Psd destr) (get_reg (Hdw srcr) st) st in
279      next_pc st lbl
280
281    | ERTL.St_set_hdw (destr, srcr, lbl) ->
282      let st = add_reg (Hdw destr) (get_reg (Psd srcr) st) st in
283      next_pc st lbl
284
285    | ERTL.St_hdw_to_hdw (destr, srcr, lbl) ->
286      let st = add_reg (Hdw destr) (get_reg (Hdw srcr) st) st in
287      next_pc st lbl
288
289    | ERTL.St_newframe lbl ->
290      let size = framesize st in
291      let sp = get_sp st in
292      let new_sp = Val.add_address sp (Val.Offset.of_int (-size)) in
293      let st = set_sp new_sp st in
294      next_pc st lbl
295
296    | ERTL.St_delframe lbl ->
297      let size = framesize st in
298      let sp = get_sp st in
299      let new_sp = Val.add_address sp (Val.Offset.of_int size) in
300      let st = set_sp new_sp st in
301      next_pc st lbl
302
303    | ERTL.St_framesize (destr, lbl) ->
304      let size = framesize st in
305      let st = add_reg (Psd destr) (Val.of_int size) st in
306      next_pc st lbl
307
308    | ERTL.St_pop (destr, lbl) ->
309      let (st, v) = pop st in
310      let st = add_reg (Psd destr) v st in
311      next_pc st lbl
312
313    | ERTL.St_push (srcr, lbl) ->
314      let v = get_reg (Psd srcr) st in
315      let st = push st v in
316      next_pc st lbl
317
318    | ERTL.St_addrH (r, x, lbl) ->
319      let vs = Mem.find_global st.mem x in
320      let st = add_reg (Psd r) (List.nth vs 1) st in
321      next_pc st lbl
322
323    | ERTL.St_addrL (r, x, lbl) ->
324      let vs = Mem.find_global st.mem x in
325      let st = add_reg (Psd r) (List.nth vs 0) st in
326      next_pc st lbl
327
328    | ERTL.St_int (r, i, lbl) ->
329      let st = add_reg (Psd r) (Val.of_int i) st in
330      next_pc st lbl
331
332    | ERTL.St_move (destr, srcr, lbl) ->
333      let st = add_reg (Psd destr) (get_reg (Psd srcr) st) st in
334      next_pc st lbl
335
336    | ERTL.St_opaccsA (opaccs, destr, srcr1, srcr2, lbl) ->
337      let (v, _) =
338        Eval.opaccs opaccs
339          (get_reg (Psd srcr1) st)
340          (get_reg (Psd srcr2) st) in
341      let st = add_reg (Psd destr) v st in
342      next_pc st lbl
343
344    | ERTL.St_opaccsB (opaccs, destr, srcr1, srcr2, lbl) ->
345      let (_, v) =
346        Eval.opaccs opaccs
347          (get_reg (Psd srcr1) st)
348          (get_reg (Psd srcr2) st) in
349      let st = add_reg (Psd destr) v st in
350      next_pc st lbl
351
352    | ERTL.St_op1 (op1, destr, srcr, lbl) ->
353      let v = Eval.op1 op1 (get_reg (Psd srcr) st) in
354      let st = add_reg (Psd destr) v st in
355      next_pc st lbl
356
357    | ERTL.St_op2 (op2, destr, srcr1, srcr2, lbl) ->
358      let (v, carry) =
359        Eval.op2 st.carry op2
360          (get_reg (Psd srcr1) st)
361          (get_reg (Psd srcr2) st) in
362      let st = change_carry st carry in
363      let st = add_reg (Psd destr) v st in
364      next_pc st lbl
365
366    | ERTL.St_clear_carry lbl ->
367      let st = change_carry st Val.zero in
368      next_pc st lbl
369
370    | ERTL.St_set_carry lbl ->
371      let st = change_carry st (Val.of_int 1) in
372      next_pc st lbl
373
374    | ERTL.St_load (destr, addr1, addr2, lbl) ->
375      let addr = List.map (fun r -> get_reg (Psd r) st) [addr1 ; addr2] in
376      let v = Mem.load st.mem chunk addr in
377      let st = add_reg (Psd destr) v st in
378      next_pc st lbl
379
380    | ERTL.St_store (addr1, addr2, srcr, lbl) ->
381      let addr = List.map (fun r -> get_reg (Psd r) st) [addr1 ; addr2] in
382      let mem = Mem.store st.mem chunk addr (get_reg (Psd srcr) st) in
383      let st = change_mem st mem in
384      next_pc st lbl
385
386    | ERTL.St_call_id (f, _, lbl) ->
387      interpret_call lbls_offs st f lbl
388
389    | ERTL.St_cond (srcr, lbl_true, lbl_false) ->
390      let v = get_reg (Psd srcr) st in
391      let lbl =
392        if Val.is_true v then lbl_true
393        else
394          if Val.is_false v then lbl_false
395          else error "Undecidable branchment." in
396      next_pc st lbl
397
398    | ERTL.St_return _ ->
399      interpret_return lbls_offs st
400
401
402let print_lenv lenv =
403  let f r v =
404    if not (Val.eq v Val.undef) then
405      Printf.printf "\n%s = %s%!" (Register.print r) (Val.to_string v) in
406  Register.Map.iter f lenv
407
408let print_renv renv =
409  let f r v =
410    if not (Val.eq v Val.undef) then
411    Printf.printf "\n%s = %s%!" (I8051.print_register r) (Val.to_string v) in
412  I8051.RegisterMap.iter f renv
413
414let current_label lbls_offs st =
415  Labels_Offsets.find2 (Val.offset_of_address st.pc) lbls_offs
416
417let print_state lbls_offs st =
418  Printf.printf "PC: %s (%s)\n%!"
419    (Val.string_of_address st.pc) (current_label lbls_offs st) ;
420  Printf.printf "SP: %s\n%!" (Val.string_of_address (get_sp st)) ;
421  Printf.printf "ISP: %s%!" (Val.string_of_address st.isp) ;
422  Printf.printf "Carry: %s%!" (Val.to_string st.carry) ;
423  print_lenv st.lenv ;
424  print_renv st.renv ;
425  Mem.print st.mem ;
426  Printf.printf "\n%!"
427
428let compute_result st ret_regs =
429  let vs = List.map (fun r -> get_reg (Psd r) st) ret_regs in
430  let f res v = res && (Val.is_int v) in
431  let is_int vs = (List.length vs > 0) && (List.fold_left f true vs) in
432  if is_int vs then
433    let chunks =
434      List.map (fun v -> IntValue.Int32.cast (Val.to_int_repr v)) vs in
435    IntValue.Int32.merge chunks
436  else IntValue.Int32.zero
437
438let rec iter_small_step debug lbls_offs st =
439  let print_and_return_result (res, cost_labels) =
440    if debug then Printf.printf "Result = %s\n%!"
441      (IntValue.Int32.to_string res) ;
442    (res, cost_labels) in
443  if debug then print_state lbls_offs st ;
444  match fetch_stmt lbls_offs st with
445    | ERTL.St_return ret_regs when Val.eq_address (get_ra st) st.exit ->
446      print_and_return_result (compute_result st ret_regs, List.rev st.trace)
447    | stmt ->
448      let st' = interpret_stmt lbls_offs st stmt in
449      iter_small_step debug lbls_offs st'
450
451
452let add_global_vars =
453  List.fold_left
454    (fun mem (id, size) -> Mem.add_var mem id (AST.SQ (AST.QInt size)) None)
455
456let add_fun_defs =
457  List.fold_left (fun mem (f_id, f_def) -> Mem.add_fun_def mem f_id f_def)
458
459let init_prog (st : state) (p : ERTL.program) : state =
460  let mem = add_global_vars (add_fun_defs st.mem p.ERTL.functs) p.ERTL.vars in
461  change_mem st mem
462
463let init_sp st =
464  let (mem, sp) = Mem.alloc st.mem I8051.ext_ram_size in
465  let sp =
466    Val.change_address_offset sp (Val.Offset.of_int I8051.ext_ram_size) in
467  let st = change_mem st mem in
468  (st, sp)
469
470let init_isp st =
471  let (mem, isp) = Mem.alloc st.mem I8051.int_ram_size in
472  let st = change_mem (change_isp st isp) mem in
473  let (mem, exit) = Mem.alloc st.mem 1 in
474  let st = change_exit st exit in
475  let st = push st (List.nth exit 0) in
476  let st = push st (List.nth exit 1) in
477  st 
478
479let init_renv st sp =
480  let f r renv = I8051.RegisterMap.add r Val.undef renv in
481  let renv = I8051.RegisterSet.fold f I8051.registers I8051.RegisterMap.empty in
482  let spl = List.nth sp 0 in
483  let sph = List.nth sp 1 in
484  let renv = I8051.RegisterMap.add I8051.sph sph renv in
485  let renv = I8051.RegisterMap.add I8051.spl spl renv in
486  change_renv st renv
487
488let init_main_call lbls_offs st main =
489  let ptr = Mem.find_global st.mem main in
490  match Mem.find_fun_def st.mem ptr with
491    | ERTL.F_int def ->
492      init_fun_call lbls_offs st ptr def
493    | _ -> error ("Cannot execute the main (\"" ^ main ^ "\"): it is external.")
494
495
496(* Before interpreting, the environment is initialized:
497   - Build a bijection between the labels in the program and some values (taken
498     amongst the offsets).
499   - Add function definitions to the memory and reserve space for the globals.
500   - Allocate memory to emulate the external stack and initialize the external
501     stack pointer.
502   - Allocate memory to emulate the internal stack and initialize the internal
503     stack pointer.
504   - Initialiaze the physical register environment. All are set to 0, except for
505     the stack pointer registers that take the high and low bits of the external
506     stack pointer.
507   - Initialize a call to the main (set the current program counter to the
508     beginning of the function).
509   - Initialize the carry flag to 0. *)
510
511let interpret debug p =
512  Printf.printf "*** ERTL interpret ***\n%!" ;
513  match p.ERTL.main with
514    | None -> (IntValue.Int32.zero, [])
515    | Some main ->
516      let lbls_offs = labels_offsets p in
517      let st = empty_state in
518      let st = init_prog st p in
519      let (st, sp) = init_sp st in
520      let st = init_isp st in
521      let st = init_renv st sp in
522      let st = init_main_call lbls_offs st main in
523      let st = change_carry st Val.zero in
524      iter_small_step debug lbls_offs st
Note: See TracBrowser for help on using the repository browser.