source: src/Clight/toCminor.ma @ 2565

Last change on this file since 2565 was 2565, checked in by garnier, 7 years ago

Cl to Cm progress.

File size: 76.2 KB
Line 
1include "Clight/ClassifyOp.ma".
2include "basics/lists/list.ma".
3include "Clight/fresh.ma".
4
5(* Identify local variables that must be allocated memory. *)
6(* These are the variables whose addresses are taken. *)
7let rec gather_mem_vars_expr (e:expr) : identifier_set SymbolTag ≝
8match e with
9[ Expr ed ty ⇒
10    match ed with
11    [ Ederef e1 ⇒ gather_mem_vars_expr e1
12    | Eaddrof e1 ⇒ gather_mem_vars_addr e1
13    | Eunop _ e1 ⇒ gather_mem_vars_expr e1
14    | Ebinop _ e1 e2 ⇒ gather_mem_vars_expr e1 ∪
15                       gather_mem_vars_expr e2
16    | Ecast _ e1 ⇒ gather_mem_vars_expr e1
17    | Econdition e1 e2 e3 ⇒ gather_mem_vars_expr e1 ∪
18                            gather_mem_vars_expr e2 ∪
19                            gather_mem_vars_expr e3
20    | Eandbool e1 e2 ⇒ gather_mem_vars_expr e1 ∪
21                       gather_mem_vars_expr e2
22    | Eorbool e1 e2 ⇒ gather_mem_vars_expr e1 ∪
23                      gather_mem_vars_expr e2
24    | Efield e1 _ ⇒ gather_mem_vars_expr e1
25    | Ecost _ e1 ⇒ gather_mem_vars_expr e1
26    | _ ⇒ ∅
27    ]
28]
29and gather_mem_vars_addr (e:expr) : identifier_set SymbolTag ≝
30match e with
31[ Expr ed ty ⇒
32    match ed with
33    [ Evar x ⇒ { (x) }
34    | Ederef e1 ⇒ gather_mem_vars_expr e1
35    | Efield e1 _ ⇒ gather_mem_vars_addr e1
36    | _ ⇒ ∅ (* not an lvalue *)
37    ]
38].
39
40let rec gather_mem_vars_stmt (s:statement) : identifier_set SymbolTag ≝
41match s with
42[ Sskip ⇒ ∅
43| Sassign e1 e2 ⇒ gather_mem_vars_expr e1 ∪
44                  gather_mem_vars_expr e2
45| Scall oe1 e2 es ⇒ match oe1 with [ None ⇒ ∅ | Some e1 ⇒ gather_mem_vars_expr e1 ] ∪
46                    gather_mem_vars_expr e2 ∪
47                    (foldl ?? (λs,e. s ∪ gather_mem_vars_expr e) ∅ es)
48| Ssequence s1 s2 ⇒ gather_mem_vars_stmt s1 ∪
49                    gather_mem_vars_stmt s2
50| Sifthenelse e1 s1 s2 ⇒ gather_mem_vars_expr e1 ∪
51                         gather_mem_vars_stmt s1 ∪
52                         gather_mem_vars_stmt s2
53| Swhile e1 s1 ⇒ gather_mem_vars_expr e1 ∪
54                 gather_mem_vars_stmt s1
55| Sdowhile e1 s1 ⇒ gather_mem_vars_expr e1 ∪
56                   gather_mem_vars_stmt s1
57| Sfor s1 e1 s2 s3 ⇒ gather_mem_vars_stmt s1 ∪
58                     gather_mem_vars_expr e1 ∪
59                     gather_mem_vars_stmt s2 ∪
60                     gather_mem_vars_stmt s3
61| Sbreak ⇒ ∅
62| Scontinue ⇒ ∅
63| Sreturn oe1 ⇒ match oe1 with [ None ⇒ ∅ | Some e1 ⇒ gather_mem_vars_expr e1 ]
64| Sswitch e1 ls ⇒ gather_mem_vars_expr e1 ∪
65                  gather_mem_vars_ls ls
66| Slabel _ s1 ⇒ gather_mem_vars_stmt s1
67| Sgoto _ ⇒ ∅
68| Scost _ s1 ⇒ gather_mem_vars_stmt s1
69]
70and gather_mem_vars_ls (ls:labeled_statements) on ls : identifier_set SymbolTag ≝
71match ls with
72[ LSdefault s1 ⇒ gather_mem_vars_stmt s1
73| LScase _ _ s1 ls1 ⇒ gather_mem_vars_stmt s1 ∪
74                      gather_mem_vars_ls ls1
75].
76
77(* Defines where a variable should be allocated. *)
78inductive var_type : Type[0] ≝
79| Global : region → var_type  (* A global, allocated statically in a given region (which one ???)  *)
80| Stack  : nat → var_type     (* On the stack, at a given height *)
81| Local  : var_type           (* Locally (hopefully, in a register) *)
82.
83
84(* A map associating each variable identifier to its allocation mode and its type. *)
85definition var_types ≝ identifier_map SymbolTag (var_type × type).
86
87axiom UndeclaredIdentifier : String.
88
89definition lookup' ≝
90λvars:var_types.λid. opt_to_res … [MSG UndeclaredIdentifier; CTX ? id] (lookup ?? vars id).
91
92(* Assert that an identifier is a local variable with the given typ. *)
93definition local_id : var_types → ident → typ → Prop ≝
94λvars,id,t. match lookup' vars id with [ OK vt ⇒ match (\fst vt) with [ Global _ ⇒ False | _ ⇒ t = typ_of_type (\snd vt) ] | _ ⇒ False ].
95
96(* Note that the semantics allows locals to shadow globals.
97   Parameters start out as locals, but get stack allocated if their address
98   is taken.  We will add code to store them if that's the case.
99 *)
100
101(* Some kind of data is never allocated in registers, even if it fits, typically structured data. *)
102definition always_alloc : type → bool ≝
103λt. match t with
104[ Tarray _ _ ⇒ true
105| Tstruct _ _ ⇒ true
106| Tunion _ _ ⇒ true
107| _ ⇒ false
108].
109
110(* This builds a [var_types] map characterizing the allocation mode, of variables,
111 * and it returns a stack usage for the function (in bytes, according to [sizeof]) *)
112definition characterise_vars : list (ident×region×type) → function → var_types × nat ≝
113λglobals, f.
114  (* globals are added into a map, with var_type Global, region π_2(idrt) and type π_3(idrt) *)
115  let m ≝ foldr ?? (λidrt,m. add ?? m (\fst (\fst idrt)) 〈Global (\snd (\fst idrt)), \snd idrt〉) (empty_map ??) globals in
116  (* variables whose addr is taken in the body of the function are gathered in [mem_vars] *)
117  let mem_vars ≝ gather_mem_vars_stmt (fn_body f) in
118  (* iterate on the parameters and local variables of the function, with a tuple (map, stack_high) as an accumulator *)
119  let 〈m,stacksize〉 ≝ foldr ?? (λv,ms.
120    let 〈m,stack_high〉 ≝ ms in
121    let 〈id,ty〉 ≝ v in         
122    let 〈c,stack_high〉 ≝
123      (* if the (local, parameter) variable is of a compound type OR if its adress is taken, we allocate it on the stack. *)
124      if always_alloc ty ∨ id ∈ mem_vars then
125        〈Stack stack_high,stack_high + sizeof ty〉
126      else
127        〈Local, stack_high〉
128    in
129      〈add ?? m id 〈c, ty〉, stack_high〉) 〈m,0〉 (fn_params f @ fn_vars f) in
130  〈m,stacksize〉.
131
132(* A local variable id' status is not modified by the removal of a global variable id : id' is still local *)
133lemma local_id_add_global : ∀vars,id,r,t,id',t'.
134  local_id (add ?? vars id 〈Global r, t〉) id' t' → local_id vars id' t'.
135#var #id #r #t #id' #t'
136whd in ⊢ (% → ?); whd in ⊢ (match % with [ _ ⇒ ? | _ ⇒ ?] → ?);
137cases (identifier_eq ? id id')
138[ #E >E >lookup_add_hit whd in ⊢ (% → ?); *
139| #NE >lookup_add_miss /2/
140] qed.
141
142(* If I add a variable id ≠ id', then id' is still local *)
143lemma local_id_add_miss : ∀vars,id,vt,id',t'.
144  id ≠ id' → local_id (add ?? vars id vt) id' t' → local_id vars id' t'.
145#vars #id #vt #id' #t' #NE
146whd in ⊢ (% → %);
147whd in ⊢ (match % with [ _ ⇒ ? | _ ⇒ ? ] → match % with [ _ ⇒ ? | _ ⇒ ? ]);
148>lookup_add_miss
149[ #H @H | /2/ ]
150qed.
151
152(* After characterise_vars, a variable in the resulting map is either a global or a "local"(register or stack allocated) *)
153lemma characterise_vars_src : ∀gl,f,vars,n.
154  characterise_vars gl f = 〈vars,n〉 →
155  ∀id. present ?? vars id →
156   (∃r,ty. lookup' vars id = OK ? 〈Global r,ty〉 ∧ Exists ? (λx.x = 〈〈id,r〉,ty〉) gl) ∨
157   ∃t.local_id vars id t.
158#globals #f
159whd in ⊢ (∀_.∀_.??%? → ?);
160elim (fn_params f @ fn_vars f)
161[ #vars #n whd in ⊢ (??%? → ?); #E destruct #i #H %1
162  elim globals in H ⊢ %;
163  [ normalize * #H cases (H (refl ??))
164  | * * #id #rg #ty #tl #IH #H
165    cases (identifier_eq ? i id)
166    [ #E <E %{rg} %{ty} % [ whd in ⊢ (??%?); >lookup_add_hit // | %1 // ]
167    | #NE cases (IH ?)
168      [ #rg' * #ty' * #H1 #H2 %{rg'} %{ty'} %
169        [ whd in ⊢ (??%?); >lookup_add_miss  [ @H1 | @NE ]
170        | %2 @H2
171        ]
172      | whd in H ⊢ %; >lookup_add_miss in H; //
173      ]
174    ]
175  ]
176| * #id #ty #tl #IH #vars #n whd in ⊢ (??(match % with [ _ ⇒ ? ])? → ?); #E #i
177  #H >(contract_pair var_types nat ?) in E;
178  whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
179  cases (always_alloc ty ∨ id ∈ ?) whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
180  #H' lapply (extract_pair ???????? H') -H' * #m0 * #n0 * #EQ #EQ2
181  cases (identifier_eq ? i id)
182  [ 1,3: #E' <E' in EQ2:%; #EQ2 %2 %{(typ_of_type ty)}
183         destruct (EQ2) whd whd in ⊢ (match % with [_ ⇒ ? | _ ⇒ ?]);
184         >lookup_add_hit @refl
185  | *: #NE cases (IH m0 n0 ? i ?)
186    [ 1,5: * #rg' * #ty' * #H1 #H2 %1 %{rg'} %{ty'} % //
187           destruct (EQ2) whd in ⊢ (??%?); >lookup_add_miss try @NE @H1
188    | 2,6: * #t #H1 %2 %{t} destruct (EQ2) whd whd in ⊢ (match % with [_ ⇒ ?|_ ⇒ ?]);
189           >lookup_add_miss //
190    | 3,7: <EQ @refl
191    | *: destruct (EQ2) whd in H; >lookup_add_miss in H; //
192    ]
193  ]
194] qed.
195
196(* A local variable in a function is either a parameter or a "local" (:=register or stack alloc'd)
197 * variable, with the right type *)
198lemma characterise_vars_all : ∀l,f,vars,n.
199  characterise_vars l f = 〈vars,n〉 →
200  ∀i,t. local_id vars i t →
201        Exists ? (λx.\fst x = i ∧ typ_of_type (\snd x) = t) (fn_params f @ fn_vars f).
202#globals #f
203whd in ⊢ (∀_.∀_.??%? → ?);
204elim (fn_params f @ fn_vars f)
205[ #vars #n whd in ⊢ (??%? → ?); #E destruct #i #t #H @False_ind
206  elim globals in H;
207  [ normalize //
208  | * * #id #rg #t #tl #IH whd in ⊢ (?%?? → ?); #H @IH @(local_id_add_global … H)
209  ]
210| * #id #ty #tl #IH #vars #n whd in ⊢ (??(match % with [ _ ⇒ ? ])? → ?); #E #i #t
211
212  #H >(contract_pair var_types nat ?) in E;
213  whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
214  cases (always_alloc ty ∨ id ∈ ?) whd in ⊢ (??(match ? with [ _ ⇒ (λ_.λ_.%) ])? → ?);
215  #H' lapply (extract_pair ???????? H') -H' * #m0 * #n0 * #EQ #EQ2
216
217  cases (identifier_eq ? id i)
218  [ 1,3: #E' >E' in EQ2:%; #EQ2 % %
219    [ 1,3: @refl
220    | *: destruct (EQ2) change with (add ?????) in H:(?%??);
221      whd in H; whd in H:(match % with [_ ⇒ ?|_ ⇒ ?]); >lookup_add_hit in H;
222      whd in ⊢ (% → ?); #E'' >E'' @refl
223    ]
224  | *: #NE %2 @(IH m0 n0)
225    [ 1,3: @sym_eq whd in ⊢ (???(match ?????% with [ _ ⇒ ? ])); >contract_pair @EQ
226    | 2,4: destruct (EQ2) @(local_id_add_miss … H) @NE
227    ]
228  ]
229] qed.
230
231(* The map generated by characterise_vars is "correct" wrt the fresh ident generator of tag [u],
232   i.e. by generating fresh idents with u, we risk no collision with the idents in the map domain. *)
233lemma characterise_vars_fresh : ∀gl,f,vars,n,u.
234  characterise_vars gl f = 〈vars,n〉 →              (* If we generate a map ... *)
235  globals_fresh_for_univ ? gl u →                  (* and the globals are out of the idents generated by u *)
236  fn_fresh_for_univ f u →                          (* and the variables of the function f are cool with u too ... *)
237  fresh_map_for_univ … vars u.                     (* then there won't be collisions between the map and idents made from u *)
238#gl #f #vars #n #u #CH #GL #FN
239#id #H
240cases (characterise_vars_src … CH … H)
241[ * #rg * #ty * #H1 #H2
242  cases (Exists_All … H2 GL) * * #id' #rg' #ty' * #E #H destruct //
243| * #t #H lapply (characterise_vars_all … CH id t H) #EX
244  cases (Exists_All … EX FN) * #id' #ty' * * #E1 #E2 #H' -H destruct //
245] qed.
246
247include "Cminor/syntax.ma".
248include "common/Errors.ma".
249
250alias id "CMexpr" = "cic:/matita/cerco/Cminor/syntax/expr.ind(1,0,0)".
251
252axiom BadlyTypedAccess : String.
253axiom BadLvalue : String.
254axiom MissingField : String.
255
256(* type_should_eq enforces that two types are equal and eliminates this equality by
257   transporting P ty1 to P ty2. If ty1 != ty2, then Error *)
258definition type_should_eq : ∀ty1,ty2. ∀P:type → Type[0]. P ty1 → res (P ty2) ≝
259λty1,ty2,P,p.
260  do E ← assert_type_eq ty1 ty2;
261  OK ? (match E return λx.λ_. P ty1 → P x with [ refl ⇒ λp.p ] p). 
262
263(* same gig for regions *)
264definition region_should_eq : ∀r1,r2. ∀P:region → Type[0]. P r1 → res (P r2).
265* * #P #p try @(OK ? p) @(Error ? (msg TypeMismatch))
266qed.
267
268(* same gig for AST typs *)
269definition typ_should_eq : ∀ty1,ty2. ∀P:typ → Type[0]. P ty1 → res (P ty2) ≝
270λty1,ty2,P,p.
271  match typ_eq ty1 ty2 with
272  [ inl E ⇒ OK ? (p⌈P ty1 ↦ P ty2⌉)
273  | inr _ ⇒ Error ? (msg TypeMismatch)
274  ].
275destruct %
276qed.
277
278alias id "CLunop" = "cic:/matita/cerco/Clight/Csyntax/unary_operation.ind(1,0,0)".
279alias id "CMunop" = "cic:/matita/cerco/common/FrontEndOps/unary_operation.ind(1,0,0)".
280
281(* XXX: For some reason matita refuses to pick the right one unless forced. *)
282alias id "CMnotbool" = "cic:/matita/cerco/common/FrontEndOps/unary_operation.con(0,3,0)".
283
284(* Translates a Clight unary operation into a Cminor one, while checking
285 * that the domain and codomain types are consistent. *)
286definition translate_unop : ∀t,t':typ. CLunop → res (CMunop t t') ≝
287λt,t'.λop:CLunop.
288  match op with
289  [ Onotbool ⇒
290      match t return λt. res (CMunop t t') with
291      [ ASTint sz sg ⇒
292          match t' return λt'. res (CMunop ? t') with
293          [ ASTint sz' sg' ⇒ OK ? (CMnotbool ????)
294          | _ ⇒ Error ? (msg TypeMismatch)
295          ]
296      | ASTptr ⇒
297          match t' return λt'. res (CMunop ? t') with
298          [ ASTint sz' sg' ⇒ OK ? (CMnotbool ????)
299          | _ ⇒ Error ? (msg TypeMismatch)
300          ]
301      | _ ⇒ Error ? (msg TypeMismatch)
302      ]
303  | Onotint ⇒
304      match t' return λt'. res (CMunop t t') with
305      [ ASTint sz sg ⇒ typ_should_eq ?? (λt. CMunop t (ASTint ??)) (Onotint sz sg)
306      | _ ⇒ Error ? (msg TypeMismatch)
307      ]
308  | Oneg ⇒
309      match t' return λt'. res (CMunop t t') with
310      [ ASTint sz sg ⇒ typ_should_eq ?? (λt.CMunop t (ASTint ??)) (Onegint sz sg)
311    (*  | ASTfloat sz ⇒ typ_should_eq ?? (λt.CMunop t (ASTfloat sz)) (Onegf sz) *)
312      | _ ⇒ Error ? (msg TypeMismatch)
313      ]
314  ]. @I qed.
315
316(* Translates a Clight addition into a Cminor one. Four cases to consider :
317  - integer/integer add
318  - fp/fp add
319  - pointer/integer
320  - integer/pointer.
321  Consistency of the type is enforced by explicit checks.
322*)
323
324(* First, how to get rid of a abstract-away pointer or array type *)
325definition fix_ptr_type : ∀ty,n. expr (typ_of_type (ptr_type ty n)) → expr ASTptr ≝
326λty,n,e. e⌈expr (typ_of_type (ptr_type ty n)) ↦ expr ASTptr⌉.
327cases n //
328qed.
329
330definition translate_add ≝
331λty1,ty2,ty'.
332let ty1' ≝ typ_of_type ty1 in
333let ty2' ≝ typ_of_type ty2 in
334match classify_add ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
335[ add_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Oadd ??) e1 e2)
336(* XXX we cast up to I16 Signed to prevent overflow, but often we could use I8 *)
337| add_case_pi n ty sz sg ⇒
338    λe1,e2. typ_should_eq ??? (Op2 ??? (Oaddp I16) (fix_ptr_type … e1) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e2) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))))
339| add_case_ip n sz sg ty ⇒
340    λe1,e2. typ_should_eq ??? (Op2 ??? (Oaddp I16) (fix_ptr_type … e2) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e1) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))))
341| add_default _ _ ⇒ λe1,e2. Error ? (msg TypeMismatch)
342].
343
344definition translate_sub ≝
345λty1,ty2,ty'.
346let ty1' ≝ typ_of_type ty1 in
347let ty2' ≝ typ_of_type ty2 in
348match classify_sub ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
349[ sub_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Osub ??) e1 e2)
350(* XXX could optimise cast as above *)
351| sub_case_pi n ty sz sg ⇒
352    λe1,e2. typ_should_eq ??? (Op2 ??? (Osubpi I16) (fix_ptr_type … e1) (Op2 ??? (Omul I16 Signed) (Op1 ?? (Ocastint sz sg I16 Signed) e2) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty))))))
353(* XXX check in detail? *)
354| sub_case_pp n1 n2 ty1 ty2 ⇒
355    λe1,e2. match ty' return λty'. res (CMexpr (typ_of_type ty')) with
356    [ Tint sz sg ⇒ OK ? (Op1 ?? (Ocastint I16 Signed sz sg) (Op2 ??? (Odiv I16) (Op2 ??? (Osubpp I16) (fix_ptr_type … e1) (fix_ptr_type ?? e2)) (Cst ? (Ointconst I16 Signed (repr ? (sizeof ty2))))))
357    | _ ⇒ Error ? (msg TypeMismatch)
358    ]
359| sub_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
360].
361
362definition translate_mul ≝
363λty1,ty2,ty'.
364let ty1' ≝ typ_of_type ty1 in
365let ty2' ≝ typ_of_type ty2 in
366match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
367[ aop_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omul …) e1 e2)
368(* | aop_case_ff sz ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omulf …) e1 e2) *)
369| aop_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
370].
371
372definition translate_div ≝
373λty1,ty2,ty'.
374let ty1' ≝ typ_of_type ty1 in
375let ty2' ≝ typ_of_type ty2 in
376match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
377[ aop_case_ii sz sg ⇒
378    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
379    [ Unsigned ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odivu …) e1 e2)
380    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odiv …) e1 e2)
381    ]
382(* | aop_case_ff sz ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Odivf …) e1 e2) *)
383| aop_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
384].
385
386definition translate_mod ≝
387λty1,ty2,ty'.
388let ty1' ≝ typ_of_type ty1 in
389let ty2' ≝ typ_of_type ty2 in
390match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
391[ aop_case_ii sz sg ⇒
392    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
393    [ Unsigned ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omodu …) e1 e2)
394    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omod …) e1 e2)
395    ]
396(* no float case *)
397| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
398].
399
400definition translate_shr ≝
401λty1,ty2,ty'.
402let ty1' ≝ typ_of_type ty1 in
403let ty2' ≝ typ_of_type ty2 in
404match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
405[ aop_case_ii sz sg ⇒
406    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
407    [ Unsigned ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omodu …) e1 e2)
408    | Signed ⇒ λe1,e2. typ_should_eq ??? (Op2 ??? (Omod …) e1 e2)
409    ]
410(* no float case *)
411| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
412].
413
414definition complete_cmp : ∀ty'. CMexpr (ASTint I8 Unsigned) → res (CMexpr (typ_of_type ty')) ≝
415λty',e.
416match ty' return λty'. res (CMexpr (typ_of_type ty')) with
417[ Tint sz sg ⇒ OK ? (Op1 ?? (Ocastint I8 Unsigned sz sg) e)
418| _ ⇒ Error ? (msg TypeMismatch)
419].
420
421definition translate_cmp ≝
422λc,ty1,ty2,ty'.
423let ty1' ≝ typ_of_type ty1 in
424let ty2' ≝ typ_of_type ty2 in
425match classify_cmp ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
426[ cmp_case_ii sz sg ⇒
427    match sg return λsg. CMexpr (ASTint sz sg) → CMexpr (ASTint sz sg) → res (CMexpr (typ_of_type ty')) with
428    [ Unsigned ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpu … c) e1 e2)
429    | Signed ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmp … c) e1 e2)
430    ]
431| cmp_case_pp n ty ⇒
432    λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpp … c) (fix_ptr_type … e1) (fix_ptr_type … e2))
433(* | cmp_case_ff sz ⇒ λe1,e2. complete_cmp ty' (Op2 ??? (Ocmpf … c) e1 e2) *)
434| cmp_default _ _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
435].
436
437definition translate_misc_aop ≝
438λty1,ty2,ty',op.
439let ty1' ≝ typ_of_type ty1 in
440let ty2' ≝ typ_of_type ty2 in
441match classify_aop ty1 ty2 return λty1,ty2.λ_. CMexpr (typ_of_type ty1) → CMexpr (typ_of_type ty2) → res (CMexpr (typ_of_type ty')) with
442[ aop_case_ii sz sg ⇒ λe1,e2. typ_should_eq ??? (Op2 ?? (ASTint sz sg) (op sz sg) e1 e2)
443| _ ⇒ λ_.λ_. Error ? (msg TypeMismatch)
444].
445
446definition translate_binop : binary_operation → type → CMexpr ? → type → CMexpr ? → type → res (CMexpr ?) ≝
447λop,ty1,e1,ty2,e2,ty.
448let ty' ≝ typ_of_type ty in
449match op with
450[ Oadd ⇒ translate_add ty1 ty2 ty e1 e2
451| Osub ⇒ translate_sub ty1 ty2 ty e1 e2
452| Omul ⇒ translate_mul ty1 ty2 ty e1 e2
453| Omod ⇒ translate_mod ty1 ty2 ty e1 e2
454| Odiv ⇒ translate_div ty1 ty2 ty e1 e2
455| Oand ⇒ translate_misc_aop ty1 ty2 ty Oand e1 e2
456| Oor  ⇒ translate_misc_aop ty1 ty2 ty Oor e1 e2
457| Oxor ⇒ translate_misc_aop ty1 ty2 ty Oxor e1 e2
458| Oshl ⇒ translate_misc_aop ty1 ty2 ty Oshl e1 e2
459| Oshr ⇒ translate_shr ty1 ty2 ty e1 e2
460| Oeq ⇒ translate_cmp Ceq ty1 ty2 ty e1 e2
461| One ⇒ translate_cmp Cne ty1 ty2 ty e1 e2
462| Olt ⇒ translate_cmp Clt ty1 ty2 ty e1 e2
463| Ogt ⇒ translate_cmp Cgt ty1 ty2 ty e1 e2
464| Ole ⇒ translate_cmp Cle ty1 ty2 ty e1 e2
465| Oge ⇒ translate_cmp Cge ty1 ty2 ty e1 e2
466].
467
468lemma typ_equals : ∀t1,t2. ∀P:∀t. expr t → Prop. ∀v1,v2.
469  typ_should_eq t1 t2 expr v1 = OK ? v2 →
470  P t1 v1 →
471  P t2 v2.
472#t1 #t2 #P #v1 #v2
473whd in ⊢ (??%? → ?); cases (typ_eq t1 t2)
474[ #E destruct #E whd in E:(??%?); destruct //
475| #NE #E normalize in E; destruct
476] qed.
477
478lemma unfix_ptr_type : ∀ty,n,e.∀P:∀t. expr t → Prop.
479  P (typ_of_type (ptr_type ty n)) e →
480  P ASTptr (fix_ptr_type ty n e).
481#ty * [ 2: #n ] #e #P #H @H
482qed.
483
484(* Recall that [expr_vars], defined in Cminor/Syntax.ma, asserts a predicate on
485  all the variables of a program. [translate_binop_vars], given
486  a predicate verified for all variables of subexprs e1 and e2, produces
487  a proof that all variables of [translate_binop op _ e1 _ e2 _] satisfy this
488  predicate. *)
489
490lemma translate_binop_vars : ∀P,op,ty1,e1,ty2,e2,ty,e.
491  expr_vars ? e1 P →
492  expr_vars ? e2 P →
493  translate_binop op ty1 e1 ty2 e2 ty = OK ? e →
494  expr_vars ? e P.
495#P * #ty1 #e1 #ty2 #e2 #ty #e #H1 #H2
496whd in ⊢ (??%? → ?);
497[ inversion (classify_add ty1 ty2) in ⊢ ?;
498  [ #sz #sg #E1 #E2 #E3 destruct >E3 #E4 -E3 change with (typ_should_eq ???? = OK ??) in E4;
499    @(typ_equals … E4) % //
500(*  | #sz #E1 #E2 #E3 destruct >E3 #E4
501    @(typ_equals … E4) % // *)
502  | #n #ty0 #sz #sg #E1 #E2 #E3 destruct >E3 #E4
503    @(typ_equals … E4) -E4 -E3 % [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)| % // ]
504  | #n #sz #sg #ty0 #E1 #E2 #E3 destruct >E3 #E4
505    @(typ_equals … E4) % [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2)| % // ]
506  | #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
507  ]
508 
509| inversion (classify_sub ty1 ty2) in ⊢ ?;
510  [ #sz #sg #E1 #E2 #E3 destruct >E3 #E4
511    @(typ_equals … E4) % //
512(*  | #sz #E1 #E2 #E3 destruct >E3 #E4
513    @(typ_equals … E4) % // *)
514  | #n #ty0 #sz #sg #E1 #E2 #E3 destruct >E3 #E4
515    @(typ_equals … E4) % [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)| % // ]
516  | #n1 #n2 #ty1' #ty2' #E1 #E2 #E3 destruct >E3
517    whd in ⊢ (??%? → ?); cases ty in e ⊢ %;
518    [ 2: #sz #sg #e #E4 | 3: #ty #e #E4 | 4: #ty' #n' #e #E4
519    | *: normalize #X1 #X2 try #X3 try #X4 destruct
520    ] whd in E4:(??%?); destruct % // %
521    [ @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1) | @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2) ]
522  | #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
523  ]
524| 3,4,5,6,7,8,9,10: inversion (classify_aop ty1 ty2) in ⊢ ?;
525  (* Note that some cases require a split on signedness of integer type. *)
526  [ 1,3,5,7,9,11,13,15: #sz * #E1 #E2 #E3 destruct >E3 #E4
527    @(typ_equals … E4) % //
528  | 2,4,6,8,10,12,14,16,18: #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); destruct
529  ]
530| *: inversion (classify_cmp ty1 ty2) in ⊢ ?;
531  [ 1,4,7,10,13,16: #sz * #E1 #E2 #E3 destruct >E3
532  | 2,5,8,11,14,17: #n #ty' #E1 #E2 #E3 destruct >E3
533  | *: #ty1' #ty2' #E1 #E2 #E3 destruct >E3 #E4 whd in E4:(??%?); @⊥ destruct
534  ] whd in ⊢ (??%? → ?); cases ty in e ⊢ %; normalize nodelta
535  try (normalize #X1 #X2 try #X3 try #X4 try #X5 destruct #FAIL)
536  #sz #sg #e #E4
537  whd in E4:(??%?); destruct % try @H1 try @H2
538  try  @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H1)
539  try  @(unfix_ptr_type ??? (λt,e. expr_vars t e P) H2)
540] qed. 
541
542(* We'll need to implement proper translation of pointers if we really do memory
543   spaces.
544(* This function performs leibniz-style subst if r1 = r2, and fails otherwise. *)
545definition check_region : ∀r1:region. ∀r2:region. ∀P:region → Type[0]. P r1 → res (P r2) ≝
546λr1,r2,P.
547  match r1 return λx.P x → res (P r2) with
548  [ Any ⇒   match r2 return λx.P Any → res (P x) with [ Any ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
549  | Data ⇒  match r2 return λx.P Data → res (P x) with [ Data ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
550  | IData ⇒ match r2 return λx.P IData → res (P x) with [ IData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
551  | PData ⇒ match r2 return λx.P PData → res (P x) with [ PData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
552  | XData ⇒ match r2 return λx.P XData → res (P x) with [ XData ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
553  | Code ⇒  match r2 return λx.P Code → res (P x) with [ Code ⇒ OK ? | _ ⇒ λ_.Error ? (msg TypeMismatch) ]
554  ].
555
556(* Simple application of [check_region] to translate between terms. *)
557definition translate_ptr : ∀P,r1,r2. (Σe:CMexpr (ASTptr r1). expr_vars ? e P) → res (Σe':CMexpr (ASTptr r2).expr_vars ? e' P) ≝
558λP,r1,r2,e. check_region r1 r2 (λr.Σe:CMexpr (ASTptr r).expr_vars ? e P) e.
559*)
560axiom FIXME : String.
561
562(* Given a source and target type, translate an expession of type source to type target *)
563definition translate_cast : ∀P. ∀ty1:type.∀ty2:type. (Σe:CMexpr (typ_of_type ty1). expr_vars ? e P) → res (Σe':CMexpr (typ_of_type ty2). expr_vars ? e' P) ≝
564λP,ty1,ty2.
565match ty1 return λx.(Σe:CMexpr (typ_of_type x). expr_vars ? e P) → ? with
566[ Tint sz1 sg1 ⇒ λe.
567    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
568    [ Tint sz2 sg2 ⇒ OK ? (Op1 ?? (Ocastint ? sg1 sz2 ?) e)
569  (*  | Tfloat sz2 ⇒ OK ? (Op1 ?? (match sg1 with [ Unsigned ⇒ Ofloatofintu ?? | _ ⇒ Ofloatofint ??]) e)*)
570    | Tpointer _ ⇒ OK ? (Op1 ?? (Optrofint ??) e)
571    | Tarray _ _ ⇒ OK ? (Op1 ?? (Optrofint ??) e)
572    | _ ⇒ Error ? (msg TypeMismatch)
573    ]
574(* | Tfloat sz1 ⇒ λe.
575    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
576    [ Tint sz2 sg2 ⇒ OK ? «Op1 ?? (match sg2 with [ Unsigned ⇒ Ointuoffloat ? sz2 | _ ⇒ Ointoffloat ? sz2 ]) e, ?»
577    | Tfloat sz2 ⇒ Error ? (msg FIXME) (* OK ? «Op1 ?? (Oid ?) e, ?» (* FIXME *) *)
578    | _ ⇒ Error ? (msg TypeMismatch)
579    ] *)
580| Tpointer _ ⇒ λe. (* will need changed for memory regions *)
581    match ty2 return λx.res (Σe':CMexpr (typ_of_type x). expr_vars ? e' P) with
582    [ Tint sz2 sg2 ⇒ OK ? «Op1 ?? (Ointofptr sz2 ?) e, ?»
583    | Tarray _ _ ⇒ (*translate_ptr ? r1 r2 e*) OK ? e
584    | Tpointer _ ⇒ OK ? e
585    | _ ⇒ Error ? (msg TypeMismatch)
586    ]
587| Tarray _ _ ⇒ λe. (* will need changed for memory regions *)
588    match ty2 return λx.res (Σe':CMexpr (typ_of_type x).expr_vars ? e' P) with
589    [ Tint sz2 sg2 ⇒ OK ? «Op1 ASTptr (ASTint sz2 sg2) (Ointofptr sz2 ?) e, ?»
590    | Tarray _ _ ⇒ OK ? e
591    | Tpointer _ ⇒ OK ? e
592    | _ ⇒ Error ? (msg TypeMismatch)
593    ]
594| _ ⇒ λ_. Error ? (msg TypeMismatch)
595]. whd normalize nodelta @pi2
596qed.
597
598(* Translate Clight exprs into Cminor ones.
599  Arguments :
600  - vars:var_types, an environment mapping each variable to a couple (allocation mode, type)
601  - e:expr, the expression to be converted
602  Result : res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars))
603  that is, either
604  . an error
605  . an expression e', matching the type of e, such that e' respect the property that all variables
606    in it are not global. In effect, [translate_expr] will replace global variables by constant symbols.
607*)
608let rec translate_expr (vars:var_types) (e:expr) on e : res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars)) ≝
609match e return λe. res (Σe':CMexpr (typ_of_type (typeof e)). expr_vars ? e' (local_id vars)) with
610[ Expr ed ty ⇒
611  match ed with
612  [ Econst_int sz i ⇒
613      match ty return λty. res (Σe':CMexpr (typ_of_type ty).  expr_vars ? e' (local_id vars)) with
614      [ Tint sz' sg ⇒ intsize_eq_elim' sz sz' (λsz,sz'. res (Σe':CMexpr (typ_of_type (Tint sz' sg)). expr_vars ? e' (local_id vars)))
615                        (OK ? «Cst ? (Ointconst sz sg i), ?»)
616                        (Error ? (msg TypeMismatch))
617      | _ ⇒ Error ? (msg TypeMismatch)
618      ]
619 (* | Econst_float f ⇒
620      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
621      [ Tfloat sz ⇒ OK ? «Cst ? (Ofloatconst sz f), ?»
622      | _ ⇒ Error ? (msg TypeMismatch)
623      ] *)
624  | Evar id ⇒
625      (* E is an equality proof of the shape "lookup' vars id = Ok <c,t>" *) 
626      do 〈c,t〉 as E ← lookup' vars id;
627      match c return λx. (c = x) → res (Σe':CMexpr ?. ?) with
628      [ Global r ⇒ λHeq_c.
629          (* We are accessing a global variable in an expression. Its Cminor counterpart also depends on
630             its access mode:
631             - By_value q, where q is a memory chunk specification (whitch should match the type of the global)
632             - By_reference, and we only take the adress of the variable
633             - By_nothing : error
634           *)
635          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
636          [ By_value t ⇒ OK ? «Mem t (Cst ? (Oaddrsymbol id 0)), ?» (* Mem is "load" in compcert *)
637          | By_reference ⇒ OK ? «Cst ? (Oaddrsymbol id 0), ?»
638          | By_nothing _ ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id]
639          ]
640      | Stack n ⇒ λHeq_c.
641          (* We have decided that the variable should be allocated on the stack,
642           * because its adress was taken somewhere or becauste it's a structured data. *)
643          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
644          [ By_value t ⇒ OK ? «Mem t (Cst ? (Oaddrstack n)), ?»
645          | By_reference ⇒ (*match r return λr. res (Σe':CMexpr (ASTptr r). ?) with
646                             [ Any ⇒*) OK ? «Cst ? (Oaddrstack n), ?» (*
647                             | _ ⇒ Error  ? [MSG BadlyTypedAccess; CTX ? id]
648                             ]*)
649          | By_nothing _ ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id]
650          ]
651          (* This is a local variable. Keep it as an identifier in the Cminor code, ensuring that the type of the original expr and of ty match. *)
652      | Local ⇒ λHeq_c. type_should_eq t ty (λt.Σe':CMexpr (typ_of_type t).expr_vars (typ_of_type t) e' (local_id vars))  («Id (typ_of_type t) id, ?»)
653      ] (refl ? c)
654  | Ederef e1 ⇒
655      do e1' ← translate_expr vars e1;
656      (* According to the way the data pointed to by e1 is accessed, the generated Cminor code will vary.
657        - if e1 is a kind of int* ptr, then we load ("Mem") the ptr returned by e1
658        - if e1 is a struct* or a function ptr, then we acess by reference, in which case we :
659           1) check the consistency of the regions in the type of e1 and in the access mode of its type
660           2) return directly the converted CMinor expression "as is" (TODO : what is the strange notation with the ceil function and the mapsto ?)
661      *)
662      match typ_of_type (typeof e1) return λx.(Σz:CMexpr x.expr_vars ? z (local_id vars)) → ? with
663      [ ASTptr ⇒ λe1'.
664          match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
665          [ By_value t ⇒ OK ? «Mem t (pi1 … e1'), ?»
666          | By_reference ⇒ OK ? e1'
667          | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
668          ]
669      | _ ⇒ λ_. Error ? (msg TypeMismatch)
670      ] e1'             
671  | Eaddrof e1 ⇒
672      do e1' ← translate_addr vars e1;
673      match typ_of_type ty return λx.res (Σz:CMexpr x.?) with
674      [ ASTptr ⇒ OK ? e1'
675(*          match e1' with
676          [ mk_DPair r1 e1' ⇒ region_should_eq r1 r ? e1'
677          ]*)
678      | _ ⇒ Error ? (msg TypeMismatch)
679      ]
680  | Eunop op e1 ⇒
681     match op
682      return λx. (op = x) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
683      with
684      [ Onotbool ⇒ λHop.
685        match typ_of_type ty
686        return λy. (typ_of_type ty = y) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
687        with
688        [ ASTint sz sg ⇒  λHtyp_of_type.
689          match sz
690          return λz. (sz = z) → res (Σe':CMexpr (typ_of_type ty). expr_vars ? e' (local_id vars))
691          with
692          [ I32 ⇒ λHsz.
693            do op' ← translate_unop (typ_of_type (typeof e1)) (typ_of_type ty) op;
694            do e1' ← translate_expr vars e1;
695            OK ? «Op1 ?? op' e1', ?»
696          | _ ⇒ λHsz.
697            Error ? (msg TypeMismatch)
698          ] (refl ? sz)
699        | _ ⇒ λHtyp_of_type.
700          Error ? (msg TypeMismatch)
701        ] (refl ? (typ_of_type ty))       
702      | _ ⇒ λHop.
703        do op' ← translate_unop (typ_of_type (typeof e1)) (typ_of_type ty) op;
704        do e1' ← translate_expr vars e1;
705        OK ? «Op1 ?? op' e1', ?»
706      ] (refl ? op)
707  | Ebinop op e1 e2 ⇒
708      do e1' ← translate_expr vars e1;
709      do e2' ← translate_expr vars e2;
710      do e' as E ← translate_binop op (typeof e1) e1' (typeof e2) e2' ty;
711      OK ? «e', ?»
712  | Ecast ty1 e1 ⇒
713      do e1' ← translate_expr vars e1;
714      do e' ← translate_cast ? (typeof e1) ty1 e1';
715      do e' ← typ_should_eq (typ_of_type ty1) (typ_of_type ty) ? e';
716      OK ? e'
717  | Econdition e1 e2 e3 ⇒
718      do e1' ← translate_expr vars e1;
719      do e2' ← translate_expr vars e2;
720      do e2' ← type_should_eq ? ty (λx.Σe:CMexpr (typ_of_type x).?) e2';
721      do e3' ← translate_expr vars e3;
722      do e3' ← type_should_eq ? ty (λx.Σe:CMexpr (typ_of_type x).?) e3';
723      match typ_of_type (typeof e1) return λx.(Σe1':CMexpr x. expr_vars ? e1' (local_id vars)) → res ? with
724      [ ASTint _ _ ⇒ λe1'. OK ? «Cond ??? e1' e2' e3', ?»
725      | _ ⇒ λ_.Error ? (msg TypeMismatch)
726      ] e1'
727  | Eandbool e1 e2 ⇒
728      do e1' ← translate_expr vars e1;
729      do e2' ← translate_expr vars e2;
730      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
731      [ Tint sz sg ⇒
732          do e2' ← type_should_eq ? (Tint sz sg) (λx.Σe:CMexpr (typ_of_type x).?) e2';
733          match typ_of_type (typeof e1)
734          return λx.
735            (Σe:CMexpr x. expr_vars ? e (local_id vars)) → (res ?)
736          with
737          [ ASTint sz1 _ ⇒ λe1'.
738            OK ? «Cond ??? e1' e2' (Cst ? (Ointconst sz sg (zero ?))), ?»
739          | _ ⇒ λ_. Error ? (msg TypeMismatch)
740          ] e1'
741      | _ ⇒ Error ? (msg TypeMismatch)
742      ]
743(*  | Eandbool e1 e2 ⇒
744      do e1' ← translate_expr vars e1;
745      do e2' ← translate_expr vars e2;
746      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
747      [ Tint sz sg ⇒
748        match sz
749        return λsz'. (sz = sz') → res (Σe':CMexpr (typ_of_type ?). ?)
750        with
751        [ I32 ⇒ λHsz_eq.
752          do e2' ← type_should_eq ? (Tint I32 sg) (λx.Σe:CMexpr (typ_of_type x).?) e2';
753          match typ_of_type (typeof e1)
754          return λx.
755            (Σe:CMexpr x. expr_vars ? e (local_id vars)) → (res ?)
756          with
757          [ ASTint sz1 _ ⇒ λe1'.
758            OK ? «Cond ??? e1' e2' (Cst ? (Ointconst I32 sg (zero ?))), ?»
759          | _ ⇒ λ_. Error ? (msg TypeMismatch)
760          ] e1'
761        | _ ⇒ λ_. Error ? (msg TypeMismatch)
762        ] (refl ? sz)
763      | _ ⇒ Error ? (msg TypeMismatch)
764      ]*)
765  | Eorbool e1 e2 ⇒
766      do e1' ← translate_expr vars e1;
767      do e2' ← translate_expr vars e2;
768      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
769      [ Tint sz sg ⇒
770        do e2' ← type_should_eq ? (Tint sz sg) (λx.Σe:CMexpr (typ_of_type x).?) e2';
771        match typ_of_type (typeof e1)
772        return λx.(Σe:CMexpr x. expr_vars ? e (local_id vars)) → res ? with
773        [ ASTint _ _ ⇒ λe1'. OK ? «Cond ??? e1' (Cst ? (Ointconst sz sg (repr ? 1))) e2', ?»
774        | _ ⇒ λ_. Error ? (msg TypeMismatch)
775        ] e1'
776      | _ ⇒ Error ? (msg TypeMismatch)
777      ]     
778  | Esizeof ty1 ⇒
779      match ty return λty. res (Σe':CMexpr (typ_of_type ty). ?) with
780      [ Tint sz sg ⇒ OK ? «Cst ? (Ointconst sz sg (repr ? (sizeof ty1))), ?»
781      | _ ⇒ Error ? (msg TypeMismatch)
782      ]     
783  | Efield e1 id ⇒
784      match typeof e1 with
785      [ Tstruct _ fl ⇒
786          do e1' ← translate_addr vars e1;
787(*          match e1' with
788          [ mk_DPair r e1' ⇒*)
789            do off ← field_offset id fl;
790            match access_mode ty return λt.λ_. res (Σe':CMexpr t. expr_vars ? e' (local_id vars)) with
791            [ By_value t ⇒
792                OK ? «Mem t (Op2 ? (ASTint I16 Signed (* XXX efficiency? *)) ?
793                                   (Oaddp …) e1' (Cst ? (Ointconst I16 Signed (repr ? off)))),?»
794            | By_reference ⇒
795(*                do e1' ← region_should_eq r r' ? e1';*)
796                OK ? «Op2 ASTptr (ASTint I16 Signed (* XXX efficiency? *)) ASTptr
797                        (Oaddp …) e1' (Cst ? (Ointconst I16 Signed (repr ? off))),?»
798            | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
799            ]
800      | Tunion _ _ ⇒
801          do e1' ← translate_addr vars e1;
802            match access_mode ty return λt.λ_. res (Σz:CMexpr t.?) with
803            [ By_value t ⇒ OK ? «Mem t e1', ?»
804            | By_reference ⇒ OK ? e1'
805            | By_nothing _ ⇒ Error ? (msg BadlyTypedAccess)
806            ]
807      | _ ⇒ Error ? (msg BadlyTypedAccess)
808      ]           
809  | Ecost l e1 ⇒
810      do e1' ← translate_expr vars e1;
811      do e' ← OK ? «Ecost ? l e1',?»;
812      typ_should_eq (typ_of_type (typeof e1)) (typ_of_type ty) (λx.Σe:CMexpr x.?) e'     
813  ]
814]
815
816(* Translate addr takes an expression e1, and returns a Cminor code computing the address of the result of [e1].   *)
817and translate_addr (vars:var_types) (e:expr) on e : res ((*𝚺r.*) Σe':CMexpr ASTptr. expr_vars ? e' (local_id vars)) ≝
818match e with
819[ Expr ed _ ⇒
820  match ed with
821  [ Evar id ⇒
822      do 〈c,t〉 ← lookup' vars id;
823      match c return λ_. res (Σz:CMexpr ASTptr.?) with
824      [ Global r ⇒ OK ? «Cst ? (Oaddrsymbol id 0), ?»
825      | Stack n ⇒ OK ? «Cst ? (Oaddrstack n), ?»
826      | Local ⇒ Error ? [MSG BadlyTypedAccess; CTX ? id] (* TODO: could rule out? *)
827      ]
828  | Ederef e1 ⇒
829      do e1' ← translate_expr vars e1;
830      match typ_of_type (typeof e1) return λx. (Σz:CMexpr x.expr_vars ? z (local_id vars)) → res (Σz:CMexpr ASTptr. expr_vars ? z (local_id vars)) with
831      [ ASTptr ⇒ λe1'.OK ? e1'
832      | _ ⇒ λ_.Error ? (msg BadlyTypedAccess)
833      ] e1'
834  | Efield e1 id ⇒
835      match typeof e1 with
836      [ Tstruct _ fl ⇒
837          do e1' ← translate_addr vars e1;
838          do off ← field_offset id fl;
839(*          match e1' with
840          [ mk_DPair r e1'' ⇒ OK (𝚺r:region.Σe:CMexpr (ASTptr r).?)*)
841             OK ? «Op2 ASTptr (ASTint I16 Signed (* FIXME inefficient?*)) ASTptr
842                   (Oaddp I16) e1' (Cst ? (Ointconst I16 Signed (repr ? off))), ?»
843      | Tunion _ _ ⇒ translate_addr vars e1
844      | _ ⇒ Error ? (msg BadlyTypedAccess)
845      ]
846  | _ ⇒ Error ? (msg BadLvalue)
847  ]
848].
849whd try @I
850[ >E whd >Heq_c @refl
851| 2,3: @pi2
852| cases e1' //
853| cases e1' //
854| @(translate_binop_vars … E) @pi2
855| % [ % ] @pi2
856| % [ % @pi2 ] whd @I
857| % [ % [ @pi2 | @I ] | @pi2 ]
858| % [ @pi2 | @I ]
859| % [ @pi2 | @I ]
860| @pi2
861| @pi2
862| % [ @pi2 | @I ]
863] qed.
864
865(* We provide a function to work out how to do an assignment to an lvalue
866   expression.  It is used for both Clight assignments and Clight function call
867   destinations, but doesn't take the value to be assigned so that we can use
868   it to form a single St_store when possible (and avoid introducing an
869   unnecessary temporary variable and assignment).
870   *)
871inductive destination (vars:var_types) : Type[0] ≝
872| IdDest : ∀id,ty. local_id vars id (typ_of_type ty) → destination vars
873| MemDest : (Σe:CMexpr ASTptr.expr_vars ? e (local_id vars)) → destination vars.
874
875(* Let a source Clight expression be assign(e1, e2). First of all, observe that [e1] is a
876  /Clight/ expression, not converted by translate_expr. We thus have to do part of the work
877  of [translate_expr] in this function. [translate_dest] will convert e1
878   into a proper destination for an assignement operation. We proceed by case analysis on e1.
879   - if e1 is a variable [id], then we proceed by case analysis on its allocation mode:
880      - if [id] is allocated locally (in a register), then id becomes directly
881        the target for the assignement, as (IdDest vars id t H), where t is the type
882        of id, and H asserts that id is indeed a local variable.
883      - if [id] is a global variable stored in region [r], then we perform [translate_expr]'s
884        job and return an adress, given as a constant symbol corresponding to [id], with
885        region r and memory chunk specified by the access mode of the rhs type ty2 of [e2].
886      - same thing for stack-allocated variables, except that we don't specify any region.
887   - if e1 is not a variable, we use [translate_addr] to generate a Cminor expression computing
888    the adres of e1
889*)
890definition translate_dest ≝
891λvars,e1.
892  match e1 with
893  [ Expr ed1 ty1 ⇒
894      match ed1 with
895      [ Evar id ⇒
896          do 〈c,t〉 as E ← lookup' vars id;
897          match c return λx.? → ? with
898          [ Local ⇒ λE. OK ? (IdDest vars id t ?)
899          | Global r ⇒ λE. OK ? (MemDest ? (Cst ? (Oaddrsymbol id 0)))
900          | Stack n ⇒ λE. OK ? (MemDest ? (Cst ? (Oaddrstack n)))
901          ] E
902      | _ ⇒
903          do e1' ← translate_addr vars e1;
904          OK ? (MemDest ? e1')
905      ]
906  ].
907whd // >E @refl
908qed.
909
910(* [lenv] is the type of maps from Clight labels to Cminor labels. *)
911definition lenv ≝ identifier_map SymbolTag (identifier Label).
912
913axiom MissingLabel : String.
914
915(* Find the Cminor label corresponding to [l] or fail. *)
916definition lookup_label ≝
917λlbls:lenv.λl. opt_to_res … [MSG MissingLabel; CTX ? l] (lookup ?? lbls l).
918
919(* True iff the Cminor label [l] is in the codomain of [lbls] *)
920definition lpresent ≝ λlbls:lenv. λl. ∃l'. lookup_label lbls l' = OK ? l.
921
922(* True iff The Clight label [l] is in the domain of [lbls] *)
923definition label_in_domain ≝ λlbls:lenv. λl. present ?? lbls l.
924
925let rec fresh_list_for_univ (l:list (identifier Label)) (u:universe Label) ≝
926match l with
927[ nil ⇒ True
928| cons elt tl ⇒ fresh_for_univ ? elt u ∧ fresh_list_for_univ tl u].
929
930record labgen : Type[0] ≝ {
931  labuniverse   : universe Label;
932  label_genlist    : list (identifier Label);
933  genlist_is_fresh : fresh_list_for_univ label_genlist labuniverse
934}.
935
936lemma fresh_list_stays_fresh : ∀l,tmp,u,u'. fresh_list_for_univ l u → 〈tmp,u'〉=fresh Label u → fresh_list_for_univ l u'.
937#l elim l
938[ 1: normalize //
939| 2: #hd #tl #Hind #tmp #u #u' #HA #HB
940  whd
941  @conj
942  [ 1: whd in HA ⊢ ?;
943    elim HA #HAleft #HAright
944    @(fresh_remains_fresh ? hd tmp u u') assumption
945  | 2: whd in HA ⊢ ?;
946    elim HA #HAleft #HAright   
947    @Hind //
948  ]
949]
950qed.
951
952definition In ≝ λelttype.λelt.λl.Exists elttype (λx.x=elt) l.   
953
954definition generate_fresh_label :
955 ∀ul. Σlul:(identifier Label × labgen).
956               (And (∀lab. In ? lab (label_genlist ul) → In ? lab (label_genlist (snd … lul)))
957                   (In ? (fst … lul) (label_genlist (snd … lul)))) ≝
958λul.
959let 〈tmp,u〉 as E ≝ fresh ? (labuniverse ul) in
960 «〈tmp, mk_labgen u (tmp::(label_genlist ul)) ?〉, ?».
961[ 1: normalize @conj
962  [ 1: @(fresh_is_fresh ? tmp u (labuniverse ul) ?) assumption
963  | 2: @fresh_list_stays_fresh // ]
964| @conj /2/
965]
966qed.
967
968let rec labels_defined (s:statement) : list ident ≝
969match s with
970[ Ssequence s1 s2 ⇒ labels_defined s1 @ labels_defined s2
971| Sifthenelse _ s1 s2 ⇒ labels_defined s1 @ labels_defined s2
972| Swhile _ s ⇒ labels_defined s
973| Sdowhile _ s ⇒ labels_defined s
974| Sfor s1 _ s2 s3 ⇒ labels_defined s1 @ labels_defined s2 @ labels_defined s3
975| Sswitch _ ls ⇒ labels_defined_switch ls
976| Slabel l s ⇒ l::(labels_defined s)
977| Scost _ s ⇒ labels_defined s
978| _ ⇒ [ ]
979]
980and labels_defined_switch (ls:labeled_statements) : list ident ≝
981match ls with
982[ LSdefault s ⇒ labels_defined s
983| LScase _ _ s ls ⇒ labels_defined s @ labels_defined_switch ls
984].
985
986definition ldefined ≝ λs.λl.Exists ? (λl'.l' = l) (labels_of s).
987
988(* For each label l in s, there exists a matching label l' = lenv(l) defined in s' *)
989definition labels_translated : lenv → statement → stmt → Prop ≝
990λlbls,s,s'.  ∀l.
991  (Exists ? (λl'.l' = l) (labels_defined s)) →
992  ∃l'. lookup_label lbls l = (OK ? l') ∧ ldefined s' l'.
993
994
995(* Invariant on statements, holds during conversion to Cminor *)
996definition stmt_inv ≝  λvars. stmt_P (stmt_vars (local_id vars)).
997
998(* I (Ilias) decided to inline the following definition, to make explicit the data constructed.
999 * This was needed to prove some stuff in translate_statement at some point, but it might be
1000 * useless now. If needed, I can revert this change.  *)
1001definition translate_assign : ∀vars:var_types. expr → expr → res (Σs:stmt. stmt_inv vars s) ≝
1002λvars,e1,e2.
1003do e2' ← translate_expr vars e2;
1004do dest ← translate_dest vars e1;
1005match dest with
1006[ IdDest id ty p ⇒
1007    do e2' ← type_should_eq (typeof e2) ty ? e2';
1008    OK ? «St_assign ? id e2', ?»
1009| MemDest e1' ⇒ OK ? «St_store ? e1' e2', ?»
1010].
1011% try (//) elim e2' /2/ elim e1' /2/
1012qed.
1013
1014definition m_option_map : ∀A,B:Type[0]. (A → res B) → option A → res (option B) ≝
1015λA,B,f,oa.
1016match oa with
1017[ None ⇒ OK ? (None ?)
1018| Some a ⇒ do b ← f a; OK ? (Some ? b)
1019].
1020
1021definition translate_expr_sigma : ∀vars:var_types. expr → res (Σe:(𝚺t:typ.CMexpr t). match e with [ mk_DPair t e ⇒ expr_vars t e (local_id vars) ]) ≝
1022λv,e.
1023  do e' ← translate_expr v e;
1024  OK (Σe:(𝚺t:typ.CMexpr t).?) «❬?, e'❭, ?».
1025whd @pi2
1026qed.
1027
1028(* Add the list of typed variables tmpenv to the environment [var_types] with
1029   the allocation mode Local. *)
1030definition add_tmps : var_types → list (ident × type) → var_types ≝
1031λvs,tmpenv.
1032  foldr ?? (λidty,vs. add ?? vs (\fst idty) 〈Local, \snd idty〉) vs tmpenv.
1033
1034record tmpgen (vars:var_types) : Type[0] ≝ {
1035  tmp_universe : universe SymbolTag;
1036  tmp_env : list (ident × type);
1037  tmp_ok : fresh_map_for_univ … (add_tmps vars tmp_env) tmp_universe;
1038  tmp_preserved :
1039    ∀id,ty. local_id vars id ty → local_id (add_tmps vars tmp_env) id ty
1040}.
1041
1042definition alloc_tmp : ∀vars. type → tmpgen vars → ident × (tmpgen vars) ≝
1043λvars,ty,g.
1044  let 〈tmp,u〉 as E ≝ fresh ? (tmp_universe ? g) in
1045  〈tmp, mk_tmpgen ? u (〈tmp, ty〉::(tmp_env ? g)) ??〉.
1046[ #id #ty'
1047  whd in ⊢ (? → ?%??);
1048  whd in ⊢ (% → %);
1049  whd in ⊢ (? → match % with [_ ⇒ ? | _ ⇒ ?]); #H
1050  >lookup_add_miss
1051  [ @(tmp_preserved … g) @H
1052  | @(fresh_distinct … E) @(tmp_ok … g)
1053    lapply (tmp_preserved … g id ty' H)
1054    whd in ⊢ (% → %);
1055    whd in ⊢ (match % with [_ ⇒ ? | _ ⇒ ?] → ?);
1056    cases (lookup ??? id)
1057    [ * | #x #_ % #E destruct ]
1058  ]
1059| @fresh_map_add
1060  [ @(fresh_map_preserved … E) @(tmp_ok … g)
1061  | @(fresh_is_fresh … E)
1062  ]
1063] qed.
1064
1065
1066lemma lookup_label_hit : ∀lbls,l,l'.
1067  lookup_label lbls l = OK ? l' →
1068  lpresent lbls l'.
1069#lbls #l #l' #E whd %{l} @E
1070qed.
1071
1072(* TODO: is this really needed now? *)
1073
1074definition tmps_preserved : ∀vars:var_types. tmpgen vars → tmpgen vars → Prop ≝
1075λvars,u1,u2.
1076  ∀id,ty. local_id (add_tmps vars (tmp_env … u1)) id ty → local_id (add_tmps vars (tmp_env … u2)) id ty.
1077
1078lemma alloc_tmp_preserves : ∀vars,tmp,u,u',q.
1079  〈tmp,u'〉 = alloc_tmp ? q u → tmps_preserved vars u u'.
1080#vars #tmp * #u1 #e1 #F1 #P1 * #u2 #e2 #F2 #P2 #q
1081whd in ⊢ (???% → ?); generalize in ⊢ (???(?%) → ?);
1082cases (fresh SymbolTag u1) in ⊢ (??%? → ???(match % with [ _ ⇒ ? ]?) → ?);
1083#tmp' #u' #E1 #E2 whd in E2:(???%); destruct
1084#id #ty #H whd in ⊢ (?%??); whd in H ⊢ %;
1085whd in ⊢ match % with [ _ ⇒ ? | _ ⇒ ? ];
1086>lookup_add_miss // @(fresh_distinct … E1) @F1
1087whd in H:(match % with [_ ⇒ ?|_ ⇒ ?]) ⊢ %;
1088cases (lookup ??? id) in H ⊢ %;
1089[ * | #x #_ % #E destruct ]
1090qed.
1091
1092lemma add_tmps_oblivious : ∀vars,s,u.
1093  stmt_inv vars s → stmt_inv (add_tmps vars (tmp_env vars u)) s.
1094#vars #s #u #H
1095@(stmt_P_mp … H)
1096#s' #H1 @(stmt_vars_mp … H1) #id #t #H @(tmp_preserved ? u ?? H)
1097qed.
1098
1099lemma local_id_fresh_tmp : ∀vars,tmp,u,ty,u0.
1100  〈tmp,u〉 = alloc_tmp vars ty u0 → local_id (add_tmps vars (tmp_env … u)) tmp (typ_of_type ty).
1101#vars #tmp #u #ty #u0
1102whd in ⊢ (???% → ?); generalize in ⊢ (???(?%) → ?);
1103cases (fresh SymbolTag (tmp_universe vars u0)) in ⊢ (??%? → ???(match % with [_⇒?]?) → ?);
1104* #tmp' #u' #e #E whd in E:(???%);
1105destruct
1106whd in ⊢ (?%??); whd whd in ⊢ match % with [ _ ⇒ ? | _ ⇒ ? ]; >lookup_add_hit
1107@refl
1108qed.
1109
1110
1111let rec mklabels (ul:labgen) : (identifier Label) × (identifier Label) × labgen ≝
1112  match generate_fresh_label ul with
1113  [ mk_Sig res1 H1 ⇒
1114     let 〈entry_label, ul1〉 as E1 ≝ res1 in
1115     match generate_fresh_label ul1 with
1116     [ mk_Sig res2 H2 ⇒
1117        let 〈exit_label, ul2〉 as E2 ≝ res2 in
1118        〈entry_label, exit_label, ul2〉
1119     ]
1120  ].
1121
1122(* When converting loops into gotos, and in order to eliminate blocks, we have
1123 * to convert continues and breaks into goto's, too. We add some "flags" in
1124 * in argument to [translate_statement], meaning that the next encountered break
1125 * or continue has to be converted into a goto to some contained label.
1126 * ConvertTo l1 l2 means "convert continue to goto l1 and convert break to goto l2".
1127 *)
1128inductive convert_flag : Type[0] ≝
1129| DoNotConvert : convert_flag
1130| ConvertTo    : identifier Label → identifier Label → convert_flag. (* continue, break *)
1131
1132let rec labels_of_flag (flag : convert_flag) : list (identifier Label) ≝
1133match flag with
1134[ DoNotConvert ⇒ [ ]
1135| ConvertTo continue break ⇒ continue :: break :: [ ]
1136].
1137
1138(* For a top-level expression, [label-wf] collapses to "all labels are properly declared" *)
1139definition label_wf ≝
1140λ (s : statement) .λ (s' : stmt) .λ (lbls : lenv). λ (flag : convert_flag).
1141    stmt_P (λs1. stmt_labels (λl.ldefined s' l ∨ lpresent lbls l ∨ In ? l (labels_of_flag flag)) s1) s'.
1142
1143definition return_ok : option typ → stmt → Prop ≝
1144λot.
1145stmt_P (λs.
1146  match s with [ St_return oe ⇒
1147    match oe with [ Some e ⇒ Some ? (dpi1 … e) = ot | None ⇒ None ? = ot ]
1148  | _ ⇒ True ]).
1149
1150(* trans_inv is the invariant which is enforced during the translation from Clight to Cminor.
1151  The involved arguments are the following:
1152  . vars:var_types, an environment mapping variables to their types and allocation modes
1153  . lbls:lenv, a mapping from old (Clight) to fresh and new (Cminor) labels,
1154  . s:statement, a Clight statement,
1155  . uv, a fresh variable generator (containing itself some invariants)
1156  . flag, wich maps "break" and "continue" to "gotos"
1157  . su', a couple of a Cminor statement and fresh variable generator.
1158*)
1159definition trans_inv : ∀vars:var_types . ∀lbls:lenv . statement → tmpgen vars → convert_flag → option typ → ((tmpgen vars) × labgen × stmt) → Prop ≝
1160λvars,lbls,s,uv,flag,rettyp,su'.
1161  let 〈uv', ul', s'〉 ≝ su' in
1162  stmt_inv (add_tmps vars (tmp_env … uv')) s' ∧   (* remaining variables in s' are local*)
1163  labels_translated lbls s s' ∧                   (* all the labels in s are transformed in label of s' using [lbls] as a map *)
1164  tmps_preserved vars uv uv' ∧                    (* the variables generated are local and grows in a monotonic fashion *)
1165  return_ok rettyp s' ∧                           (* return statements have correct typ *)
1166  label_wf s s' lbls flag.                        (* labels are "properly" declared, as defined in [ŀabel_wf].*)
1167
1168axiom ReturnMismatch : String.
1169
1170let rec translate_statement (vars:var_types) (uv:tmpgen vars) (ul:labgen) (lbls:lenv) (flag:convert_flag) (rettyp:option typ) (s:statement) on s
1171  : res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls s uv flag rettyp su) ≝
1172match s return λs.res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls s uv flag rettyp su) with
1173[ Sskip ⇒ OK ? «〈uv, ul, St_skip〉, ?»
1174| Sassign e1 e2 ⇒
1175    do e2' ← translate_expr vars e2;  (* rhs *)
1176    do dest ← translate_dest vars e1; (* e1 *)
1177    match dest with
1178    [ IdDest id ty p ⇒
1179       do e2' ← type_should_eq (typeof e2) ty ? e2';
1180       OK ? «〈uv, ul, St_assign ? id e2'〉, ?»
1181    | MemDest e1' ⇒
1182       OK ? «〈uv, ul, St_store ? e1' e2'〉, ?»
1183    ]
1184| Scall ret ef args ⇒
1185    do ef' ← translate_expr vars ef;
1186    do ef' ← typ_should_eq (typ_of_type (typeof ef)) ASTptr ? ef';
1187    do args' ← mmap_sigma ??? (translate_expr_sigma vars) args;
1188    match ret with
1189    [ None ⇒ OK ? «〈uv, ul, St_call (None ?) ef' args'〉, ?»
1190    | Some e1 ⇒
1191        do dest ← translate_dest vars e1;
1192        match dest with
1193        [ IdDest id ty p ⇒ OK ? «〈uv, ul, St_call (Some ? 〈id,typ_of_type ty〉) ef' args'〉, ?»
1194        | MemDest e1' ⇒
1195            let 〈tmp, uv1〉 as Etmp ≝ alloc_tmp ? (typeof e1) uv in
1196            OK ? «〈uv1, ul, St_seq (St_call (Some ? 〈tmp,typ_of_type (typeof e1)〉) ef' args') (St_store (typ_of_type (typeof e1)) e1' (Id ? tmp))〉, ?»
1197        ]
1198    ]
1199| Ssequence s1 s2 ⇒
1200    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1201    do «fgens2, s2', H2» ← translate_statement vars (fst … fgens1) (snd … fgens1) lbls flag rettyp s2;
1202    OK ? «〈fgens2, St_seq s1' s2'〉, ?»
1203| Sifthenelse e1 s1 s2 ⇒
1204    do e1' ← translate_expr vars e1;
1205    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x.expr_vars ? e ?) → res ? with
1206    [ ASTint _ _ ⇒ λe1'.
1207         do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1208         do «fgens2, s2', H2» ← translate_statement vars (fst … fgens1) (snd … fgens1) lbls flag rettyp s2;
1209        OK ? «〈fgens2, St_ifthenelse ?? e1' s1' s2'〉, ?»
1210    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1211    ] e1'
1212(* Performing loop conversions while keeping good cost labelling properties is
1213   a little tricky.  In principle we should have a cost label in each branch,
1214   but the behaviour of the next stage means that we can put in Cminor skips and
1215   goto labels before the cost label. *)
1216| Swhile e1 s1 ⇒
1217    do e1' ← translate_expr vars e1;
1218    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x.expr_vars ? e ?) → res ? with
1219    [ ASTint _ _ ⇒ λe1'.         
1220        let 〈labels, ul1〉 as E1 ≝ mklabels ul in
1221        let 〈entry, exit〉 as E2 ≝ labels in
1222        do «fgens2, s1',H1» ← translate_statement vars uv ul1 lbls (ConvertTo entry exit) rettyp s1;
1223        let converted_loop ≝
1224          St_label entry
1225          (St_seq
1226            (St_ifthenelse ?? e1' (St_seq s1' (St_goto entry)) St_skip)
1227            (St_label exit St_skip))
1228        in         
1229          OK ? «〈fgens2, converted_loop〉, ?»
1230    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1231    ] e1'
1232| Sdowhile e1 s1 ⇒
1233    do e1' ← translate_expr vars e1;
1234    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x. expr_vars ? e ?) → res ? with
1235    [ ASTint _ _ ⇒ λe1'.
1236        let 〈labels, ul1〉 as E1 ≝ mklabels ul in
1237        let 〈condexpr, exit〉 as E2 ≝ labels in
1238        let 〈body, ul2〉 ≝ generate_fresh_label … ul1 in
1239        do «fgens2, s1', H1» ← translate_statement vars uv ul2 lbls (ConvertTo condexpr exit) rettyp s1;
1240        (* This is particularly carefully implemented, we need to reach the
1241           cost label in s1' or the cost label after the loop (if they are
1242           present) after the ifthenelse, and we're only allowed skips and
1243           goto labels in between.  So we structure it like a while with a goto
1244           into the middle (the CFG will be essentially the same, anyway.) *)
1245        let converted_loop ≝
1246        St_seq
1247          (St_seq
1248            (St_goto body)
1249            (St_label condexpr
1250              (St_ifthenelse ?? e1'
1251                (St_label body
1252                  (St_seq
1253                    s1'
1254                    (St_goto condexpr)))
1255                St_skip)))
1256          (St_label exit St_skip)
1257        in
1258        OK ? «〈fgens2, converted_loop〉, ?»
1259    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1260    ] e1'
1261| Sfor s1 e1 s2 s3 ⇒
1262    do e1' ← translate_expr vars e1;
1263    match typ_of_type (typeof e1) return λx.(Σe:CMexpr x. expr_vars ? e ?) → res ? with
1264    [ ASTint _ _ ⇒ λe1'.
1265        let 〈labels, ul1〉 as E ≝ mklabels ul in
1266        let 〈continue, exit〉 as E2 ≝ labels in
1267        let 〈entry, ul2〉 ≝ generate_fresh_label … ul1 in
1268        do «fgens2, s1', H1» ← translate_statement vars uv ul2 lbls flag rettyp s1;
1269        (* The choice of flag is arbitrary - Clight's semantics give no meaning
1270           to continue or break in s2 because in C it must be an expression. *)
1271        do «fgens3, s2', H2» ← translate_statement vars (fst … fgens2) (snd … fgens2) lbls flag rettyp s2;
1272        do «fgens4, s3', H3» ← translate_statement vars (fst … fgens3) (snd … fgens3) lbls (ConvertTo continue exit) rettyp s3;
1273        let converted_loop ≝
1274          St_seq
1275            s1'
1276            (St_label entry
1277              (St_seq
1278                (St_ifthenelse ?? e1' (St_seq s3' (St_label continue (St_seq s2' (St_goto entry)))) St_skip)
1279                (St_label exit St_skip)
1280            ))
1281        in
1282          OK ? «〈fgens4, converted_loop〉, ?»
1283    | _ ⇒ λ_.Error ? (msg TypeMismatch)
1284    ] e1'
1285| Sbreak ⇒
1286   match flag return λf.flag = f → ? with
1287   [ DoNotConvert ⇒ λEflag.
1288     Error ? (msg FIXME)
1289   | ConvertTo continue_label break_label ⇒ λEflag.
1290     OK ? «〈uv, ul, St_goto break_label〉, ?»
1291   ] (refl ? flag)
1292| Scontinue ⇒
1293  match flag return λf.flag = f → ? with
1294  [ DoNotConvert ⇒ λEflag.
1295    Error ? (msg FIXME)
1296  | ConvertTo continue_label break_label ⇒ λEflag.
1297    OK ? «〈uv, ul, St_goto continue_label〉, ?»
1298  ] (refl ? flag)
1299| Sreturn ret ⇒
1300    match ret with
1301    [ None ⇒
1302        match rettyp return λx.res (Σy.trans_inv … x y) with
1303        [ None ⇒ OK ? «〈uv, ul, St_return (None ?)〉, ?»
1304        | _ ⇒ Error ? (msg ReturnMismatch)
1305        ]
1306    | Some e1 ⇒
1307        match rettyp return λx.res (Σy.trans_inv … x y) with
1308        [ Some rty ⇒
1309            do e1' ← translate_expr vars e1;
1310            do e1' ← typ_should_eq (typ_of_type (typeof e1)) rty ? e1';
1311            OK ? «〈uv, ul, St_return (Some ? (mk_DPair … e1'))〉, ?»
1312        | _ ⇒ Error ? (msg ReturnMismatch)
1313        ]
1314    ]
1315| Sswitch e1 ls ⇒ Error ? (msg FIXME)
1316| Slabel l s1 ⇒
1317    do l' as E ← lookup_label lbls l;
1318    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1319    OK ? «〈fgens1, St_label l' s1'〉, ?»
1320| Sgoto l ⇒
1321    do l' as E ← lookup_label lbls l;
1322    OK ? «〈uv, ul, St_goto l'〉, ?»
1323| Scost l s1 ⇒
1324    do «fgens1, s1', H1» ← translate_statement vars uv ul lbls flag rettyp s1;
1325    OK ? «〈fgens1, St_cost l s1'〉, ?»
1326].
1327try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj
1328try (@I)
1329try (#l #H elim H)
1330try (#size #sign #H assumption)
1331try (#H1 try #H2 assumption)
1332[ 1,5: @(tmp_preserved … p) ]
1333[ 1,3: elim e2' | 2,9,23: elim e1' | 4,7,13: elim ef' ]
1334[ 1,2,3,4,5,6,7,8 : #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal) ]
1335[ 1: @All_mp [ 1: @(λe.match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars) ])
1336             | 2: * #t #e #Hev whd in Hev ⊢ %; @(expr_vars_mp … Hev) #i #t #Hp @(tmp_preserved … Hp)
1337             | 3: elim args' // ]
1338| 7: (* we should be able to merge this case with the previous ... *)
1339     @All_mp [ 1: @(λe.match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars) ])
1340             | 2: * #t #e #Hev whd in Hev ⊢ %; @(expr_vars_mp … Hev) #i #t #Hp @(tmp_preserved … Hp)
1341             | 3: elim args' // ]
1342| 2: @(local_id_fresh_tmp vars tmp uv1 (typeof e1) uv Etmp)
1343| 3:  @(All_mp (𝚺 t:typ.expr t) (λe. match e with [ mk_DPair t e0 ⇒ expr_vars t e0 (local_id vars)]))
1344       [ 1: #a #Ha elim a in Ha ⊢ ?; #ta #a #Ha whd @(expr_vars_mp ?? (local_id vars))
1345       [ 1: #i0 #t0 #H0 @(tmp_preserved vars uv1 i0 t0 H0)
1346       | 2: assumption ]
1347       | 2: elim args' // ]
1348| 4: @(local_id_fresh_tmp vars tmp uv1 (typeof e1) uv Etmp) ]
1349[ 1: #size #sign | 2: ]
1350[ 1,2: #H @(alloc_tmp_preserves vars tmp uv uv1 … Etmp) @H ]
1351try @refl (* Does (at least) the return_ok cases *)
1352try @(match fgens1 return λx.x=fgens1 → ? with
1353     [ mk_Prod uv1 ul1 ⇒ λHfgens1.? ] (refl ? fgens1))
1354try @(match fgens2 return λx.x=fgens2 → ? with
1355     [ mk_Prod uv2 ul2 ⇒ λHfgens2.? ] (refl ? fgens2))
1356try @(match fgens3 return λx.x=fgens3 → ? with
1357     [ mk_Prod uv3 ul3 ⇒ λHfgens3.? ] (refl ? fgens3))
1358try @(match fgens4 return λx.x=fgens4 → ? with
1359     [ mk_Prod uv4 ul4 ⇒ λHfgens4.? ] (refl ? fgens4))
1360whd in H1 H2 H3 ⊢ ?; destruct whd nodelta in H1 H2 H3;
1361try (elim H1 -H1 * * * #Hstmt_inv1 #Hlabels_tr1 #Htmps_pres1 #Hret1)
1362try (elim H2 -H2 * * * #Hstmt_inv2 #Hlabels_tr2 #Htmps_pres2 #Hret2)
1363try (elim H3 -H3 * * * #Hstmt_inv3 #Hlabels_tr3 #Htmps_pres3 #Hret3)
1364[ 1,2: #Hind1 #Hind2 | 3,4,8,10: #Hind | 5: #Hind1 #Hind2 #Hind3 ]
1365try @conj try @conj try @conj try @conj try @conj try @conj try (whd @I) try assumption
1366[ 1,7: @(stmt_P_mp … Hstmt_inv1) #e #Hvars @(stmt_vars_mp … Hvars) #i #t #Hlocal @(Htmps_pres2 … Hlocal)
1367| 2: #l #H cases (Exists_append ???? H) #Hcase
1368         [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1369           [ 1: @(proj1 ?? Hlabel)
1370           | 2: normalize @Exists_append_l @(proj2 … Hlabel) ]
1371         | 2: elim (Hlabels_tr2 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1372           [ 1: @(proj1 ?? Hlabel)
1373           | 2: normalize @Exists_append_r @(proj2 … Hlabel) ]
1374         ]
1375| 3,9: #id #ty #H @(Htmps_pres2 … (Htmps_pres1 id ty H)) ]
1376[ 1: @(stmt_P_mp … Hind2) | 2: @(stmt_P_mp … Hind1) ]
1377[ 1,2: #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1378     #l * try * [ 1,4: #H %1 %1 normalize in H ⊢ %; try (@Exists_append_l @H); try (@Exists_append_r @H)
1379                | 2,5: #H %1 %2 assumption
1380                | 3,6: #H %2 assumption ]
1381(* if/then/else *)
1382| 3: whd elim e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1383| 4: whd #l #H
1384       cases (Exists_append ???? H) #Hcase
1385         [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1386           [ 1: @(proj1 ?? Hlabel)
1387           | 2: normalize @Exists_append_l @(proj2 … Hlabel) ]
1388         | 2: elim (Hlabels_tr2 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1389           [ 1: @(proj1 ?? Hlabel)
1390           | 2: normalize @Exists_append_r @(proj2 … Hlabel) ]
1391         ]
1392]                 
1393[ 1: 1: @(stmt_P_mp … Hind2) | 2: @(stmt_P_mp … Hind1) ]
1394[ 1,2: #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1395     #l * try * [ 1,4: #H %1 %1 normalize in H ⊢ %; try (@Exists_append_l @H); try (@Exists_append_r @H)
1396                | 2,5: #H %1 %2 assumption
1397                | 3,6: #H %2 assumption ] ]
1398try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @I try assumption
1399[ 1,7,19: whd elim e1' #e #Hvars @(expr_vars_mp … Hvars) #i #t #Hlocal @(tmp_preserved … Hlocal)
1400| 2,8: whd #l #H normalize in H;
1401       elim (Hlabels_tr1 … H) #label #Hlabel @(ex_intro … label)
1402       @conj
1403       [ 1,3: @(proj1 … Hlabel)
1404       | 2,4: whd @or_intror normalize in ⊢ (???%);
1405              [ @Exists_append_l @Exists_append_l @Exists_append_l | %2 @Exists_append_l @Exists_append_l @Exists_append_l ]
1406              @(proj2 … Hlabel) ]
1407| whd %1 %1 normalize /2/
1408| 4,12: @(stmt_P_mp … Hind) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1409   #l * try * [ 1,5: #H %1 %1 normalize %2 [ 2: %2 ] @Exists_append_l @Exists_append_l try @Exists_append_l @H
1410              | 2,6: #H %1 %2 assumption
1411              | 3,7: #H <H %1 %1 normalize /2/
1412              | 4,8: #H normalize in H; elim H [ 1,3: #E <E %1 %1 normalize %2 [2: %2]
1413                                                 @Exists_append_r normalize /2/
1414                                               | 2,4: * ]
1415              ]
1416| normalize %1 %1 %1 //
1417| 6,11: normalize %1 %1 %2 [ @Exists_append_r normalize /2/ | %1 % ]
1418| whd %1 %1 normalize %2 %1 %
1419| 10,13: normalize %1 %1 %1 %
1420| normalize %1 %1 %2 %2 /2/
1421| whd #label * [ 1: #Eq @(ex_intro … l') @conj [ 1: destruct // | whd /2/ ]
1422               | 2: #H elim (Hlabels_tr1 label H)
1423                    #lab * #Hlookup #Hdef @(ex_intro … lab) @conj
1424                    [ 1: // | 2: whd %2 assumption ]
1425               ]
1426| normalize %1 %1 %1 %
1427| @(stmt_P_mp … Hind) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1428  #l * try * [ 1: #H %1 %1 normalize %2 @H
1429             | 2: #H %1 %2 assumption
1430             | 3: #H %2 assumption ]
1431| @(stmt_P_mp … Hstmt_inv1) #s0 #Hstmt_vars @(stmt_vars_mp … Hstmt_vars) #i #t
1432  #H @(Htmps_pres3 … (Htmps_pres2 … H))
1433| @(stmt_P_mp … Hstmt_inv2) #s0 #Hstmt_vars @(stmt_vars_mp … Hstmt_vars) #i #t
1434  #H @(Htmps_pres3 … H)
1435| % //
1436| whd #l #H normalize in H;
1437  cases (Exists_append … H) #Hcase
1438  [ 1: elim (Hlabels_tr1 l Hcase) #label #Hlabel @(ex_intro … label) @conj
1439    [ 1: @(proj1 … Hlabel)
1440    | 2: normalize @Exists_append_l @(proj2 … Hlabel)
1441    ]
1442  | 2: cases (Exists_append … Hcase) #Hcase2
1443    [ 1: elim (Hlabels_tr2 l Hcase2) #label #Hlabel @(ex_intro … label) @conj
1444      [ 1: @(proj1 … Hlabel)
1445      | 2: normalize >append_nil >append_nil >append_cons
1446           @Exists_append_r @Exists_append_l @Exists_append_r %2
1447           @(proj2 … Hlabel)
1448      ]
1449    | 2: elim (Hlabels_tr3 l Hcase2) #label #Hlabel @(ex_intro … label) @conj
1450      [ 1: @(proj1 … Hlabel)
1451      | 2: normalize >append_nil >append_nil >append_cons
1452         @Exists_append_r @Exists_append_l @Exists_append_l
1453         @(proj2 … Hlabel)
1454      ]
1455    ]
1456  ]
1457| #id #ty #H @(Htmps_pres3 … (Htmps_pres2 … (Htmps_pres1 … H)))
1458| @(stmt_P_mp … Hind3) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1459   #l * try * [ 1: #H %1 %1 normalize @Exists_append_l @H
1460              | 2: #H %1 %2 assumption
1461              | 3: #H %2 assumption ]
1462| whd %1 %1 normalize /2/
1463| @(stmt_P_mp … Hind1) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1464   #l * try * [ 1: #H %1 %1 normalize @Exists_append_r @(Exists_add ?? (nil ?))
1465                   @Exists_append_r @Exists_append_l @Exists_append_l
1466                   @Exists_append_l assumption
1467              | 2: #H %1 %2 assumption
1468              | 3: #H <H %1 %1 normalize
1469                   @Exists_append_r %2 @Exists_append_l @Exists_append_l
1470                   @Exists_append_r %1 %
1471              | 4: * [ 1: #Eq <Eq %1 %1 whd normalize
1472                       @Exists_append_r @(Exists_add ?? (nil ?)) @Exists_append_r
1473                       @Exists_append_r whd %1 //
1474                     | 2: * ]
1475              ]
1476| % %1 normalize @Exists_append_r %2 @Exists_append_l @Exists_append_l
1477  @Exists_append_r % %
1478| @(stmt_P_mp … Hind2) #s0 #Hstmt_labels @(stmt_labels_mp … Hstmt_labels)
1479   #l * try * [ 1: #H %1 %1 normalize @Exists_append_r @(Exists_add ?? (nil ?))
1480                   @Exists_append_r @Exists_append_l @Exists_append_l                   
1481                   @Exists_append_r %2 @Exists_append_l assumption
1482              | 2: #H %1 %2 assumption
1483              | 3: /2/
1484              ]
1485| whd %1 %1 normalize /2/
1486| whd %1 %1 normalize
1487  @Exists_append_r @(Exists_add ?? (nil ?)) @Exists_append_r @Exists_append_r
1488  whd %1 //
1489| normalize %2 /3/
1490| normalize /4/
1491| whd %1 %2 whd @(ex_intro … l) @E
1492] qed.
1493
1494axiom ParamGlobalMixup : String.
1495
1496(* params and statement aren't real parameters, they're just there for giving the invariant. *)
1497definition alloc_params :
1498 ∀vars:var_types.∀lbls,statement,uv,flag,rettyp. list (ident×type) → (Σsu:(tmpgen vars)×labgen×stmt. trans_inv vars lbls statement uv flag rettyp su)
1499   → res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls statement uv flag rettyp su) ≝   
1500λvars,lbls,statement,uv,ul,rettyp,params,s. foldl ?? (λsu,it.
1501  let 〈id,ty〉 ≝ it in
1502  do «result,Is» ← su;
1503  let 〈fgens1, s〉 as Eresult ≝ result in
1504  do 〈t,ty'〉 as E ← lookup' vars id;
1505  match t return λx.? → res (Σsu:(tmpgen vars)×labgen×stmt.trans_inv vars lbls statement uv ul rettyp su) with
1506  [ Local ⇒ λE. OK (Σs:(tmpgen vars)×labgen×stmt.?) «result,Is»
1507  | Stack n ⇒ λE.
1508      OK ? «〈fgens1, St_seq (St_store ? (Cst ? (Oaddrstack n)) (Id (typ_of_type ty') id)) s〉, ?»
1509  | Global _ ⇒ λE. Error ? [MSG ParamGlobalMixup; CTX ? id]
1510  ] E) (OK ? s) params.
1511whd
1512@(match fgens1 return λx.x=fgens1 → ? with
1513  [ mk_Prod uv1 ul1 ⇒ λHfgens1.? ] (refl ? fgens1))
1514whd in Is ⊢ %; destruct whd in Is;
1515try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @conj try @I
1516elim Is * * * #Hincl #Hstmt_inv #Hlab_tr #Hret #Htmp_pr try assumption
1517@(expr_vars_mp … (tmp_preserved … uv1)) whd >E @refl
1518qed.
1519
1520axiom DuplicateLabel : String.
1521
1522definition lenv_list_inv : lenv → lenv → list ident → Prop ≝
1523λlbls0,lbls,ls.
1524 ∀l,l'. lookup_label lbls l = OK ? l' →
1525 Exists ? (λl'. l' = l) ls ∨ lookup_label lbls0 l = OK ? l'.
1526
1527lemma lookup_label_add : ∀lbls,l,l'.
1528  lookup_label (add … lbls l l') l = OK ? l'.
1529#lbls #l #l' whd in ⊢ (??%?); >lookup_add_hit @refl
1530qed.
1531
1532lemma lookup_label_miss : ∀lbls,l,l',l0.
1533  l0 ≠ l →
1534  lookup_label (add … lbls l l') l0 = lookup_label lbls l0.
1535#lbls #l #l' #l0 #NE
1536whd in ⊢ (??%%);
1537>lookup_add_miss
1538[ @refl | @NE ]
1539qed.
1540
1541let rec populate_lenv (ls:list ident) (ul:labgen) (lbls:lenv): res ((Σlbls':lenv. lenv_list_inv lbls lbls' ls) × labgen) ≝
1542match ls return λls.res ((Σlbls':lenv. lenv_list_inv lbls lbls' ls) × labgen) with
1543[ nil ⇒ OK ? 〈«lbls, ?», ul〉
1544| cons l t ⇒
1545  match lookup_label lbls l return λlook. lookup_label lbls l = look → ? with
1546  [ OK _    ⇒ λ_.Error ? (msg DuplicateLabel)
1547  | Error _ ⇒ λLOOK.
1548    match generate_fresh_label … ul with
1549    [ mk_Sig ret H ⇒
1550       do 〈packed_lbls, ul1〉 ← populate_lenv t (snd ?? ret) (add … lbls l (fst ?? ret));
1551       match packed_lbls with
1552       [ mk_Sig lbls' Hinv ⇒ OK ? 〈«lbls', ?», ul1〉 ]
1553    ]
1554  ] (refl ? (lookup_label lbls l))
1555].
1556[ 1: whd #l #l' #Hlookup %2 assumption
1557| 2: whd in Hinv; whd #cl_lab #cm_lab #Hlookup
1558     @(eq_identifier_elim … l cl_lab)
1559     [ 1: #Heq %1 >Heq whd %1 //
1560     | 2: #Hneq cases (Hinv cl_lab cm_lab Hlookup)
1561           [ 1: #H %1 %2 @H
1562           | 2: #LOOK' %2 >lookup_label_miss in LOOK'; /2/ #H @H ]
1563     ]
1564]
1565qed.
1566
1567definition build_label_env :
1568   ∀body:statement. res ((Σlbls:lenv. ∀l,l'.lookup_label lbls l = OK ? l' → Exists ? (λl'.l' = l) (labels_defined body)) × labgen) ≝
1569λbody.
1570  let initial_labgen ≝ mk_labgen (new_universe ?) (nil ?) ?  in
1571  do 〈label_map, u〉 ← populate_lenv (labels_defined body) initial_labgen (empty_map ??);
1572  let lbls ≝ pi1 ?? label_map in
1573  let H    ≝ pi2 ?? label_map in
1574  OK ? 〈«lbls, ?», u〉.
1575[ 1: #l #l' #E cases (H l l' E) //
1576     whd in ⊢ (??%? → ?); #H destruct
1577| 2: whd @I ]
1578qed.
1579
1580lemma local_id_split : ∀vars,tmpgen,i,t.
1581  local_id (add_tmps vars (tmp_env vars tmpgen)) i t →
1582  local_id vars i t ∨ Exists ? (λx. \fst x = i ∧ typ_of_type (\snd x) = t) (tmp_env … tmpgen).
1583#vars #tmpgen #i #t
1584whd in ⊢ (?%?? → ?);
1585elim (tmp_env vars tmpgen)
1586[ #H %1 @H
1587| * #id #ty #tl #IH
1588  cases (identifier_eq ? i id)
1589  [ #E >E #H %2 whd %1 % [ @refl | whd in H; whd in H:(match % with [_⇒?|_⇒?]); >lookup_add_hit in H; #E1 >E1 @refl ]
1590  | #NE #H cases (IH ?)
1591    [ #H' %1 @H'
1592    | #H' %2 %2 @H'
1593    | whd in H; whd in H:(match % with [ _ ⇒ ? | _ ⇒ ? ]);
1594      >lookup_add_miss in H; [ #H @H | @NE ]
1595    ]
1596  ]
1597] qed.
1598
1599lemma Exists_squeeze : ∀A,P,l1,l2,l3.
1600  Exists A P (l1@l3) → Exists A P (l1@l2@l3).
1601#A #P #l1 #l2 #l3 #EX
1602cases (Exists_append … EX)
1603[ #EX1 @Exists_append_l @EX1
1604| #EX3 @Exists_append_r @Exists_append_r @EX3
1605] qed.
1606
1607(* This lemma allows to merge two stmt_P in one. Used in the following parts to merge an invariant on variables
1608   and an invariant on labels. *)
1609lemma stmt_P_conj : ∀ (P1:stmt → Prop). ∀ (P2:stmt → Prop). ∀ s. stmt_P P1 s → stmt_P P2 s → stmt_P (λs.P1 s ∧ P2 s) s.
1610#P1 #P2 #s elim s
1611normalize /6 by proj1, proj2, conj/
1612qed.
1613
1614definition translate_function :
1615  ∀tmpuniverse:universe SymbolTag.
1616  ∀globals:list (ident×region×type).
1617  ∀f:function.
1618    globals_fresh_for_univ ? globals tmpuniverse →
1619    fn_fresh_for_univ f tmpuniverse →
1620  res internal_function ≝
1621λtmpuniverse, globals, f, Fglobals, Ffn.
1622  do 〈env_pack, ul〉 ← build_label_env (fn_body f);
1623    match env_pack with
1624    [ mk_Sig lbls Ilbls ⇒
1625      let 〈vartypes, stacksize〉 as E ≝ characterise_vars globals f in
1626      let uv ≝ mk_tmpgen vartypes tmpuniverse [ ] ?? in
1627      do s0 ← translate_statement vartypes uv ul lbls DoNotConvert (opttyp_of_type (fn_return f)) (fn_body f);
1628      do «fgens, s1, Is» ← alloc_params vartypes lbls ? uv DoNotConvert (opttyp_of_type (fn_return f)) (fn_params f) s0;
1629      let params ≝ map ?? (λv.〈\fst v, typ_of_type (\snd v)〉) (fn_params f) in
1630      let vars ≝ map ?? (λv.〈\fst v, typ_of_type (\snd v)〉) (tmp_env ? (fst ?? fgens) @ fn_vars f) in
1631      do D ← check_distinct_env ?? (params @ vars);
1632      OK ? (mk_internal_function
1633        (opttyp_of_type (fn_return f))
1634        params
1635        vars
1636        D
1637        stacksize
1638        s1 ?)
1639  ].
1640[ 1: #i #t #Hloc whd @Hloc
1641| 2: whd #id #Hpresent normalize in Hpresent:(???%?); whd in Hpresent;
1642      @(characterise_vars_fresh … (sym_eq … E)) //
1643| 3: @(match fgens return λx.x=fgens → ? with
1644     [ mk_Prod uv' ul' ⇒ λHfgens.? ] (refl ? fgens))
1645     whd in Is; <Hfgens in Is; #Is whd in Is ⊢ %;
1646     elim Is * * * #Hstmt_inv #Hlab_trans #Htmps_pres #Hreturn #Hlabel_wf
1647     (* merge Hlabel_wf with Hstmt_inv and eliminate right away *)
1648     @(stmt_P_mp … (stmt_P_conj … (stmt_P_conj … Hstmt_inv Hlabel_wf) Hreturn))
1649     #s * * #Hstmt_vars #Hstmt_labels #Hstmt_return %
1650     [ 1: (* prove that variables are either parameters or locals *)
1651        @(stmt_vars_mp … Hstmt_vars) #i #t #H
1652        (* Case analysis: (i, t) is either in vartypes, or in (tmp_env vartypes uv) *)
1653        cases (local_id_split … H)
1654        [ 1: #H' >map_append
1655          @Exists_map [ 1: #x @(And (\fst x = i) (typ_of_type (\snd x) = t))  (* * #id #ty @(〈id, typ_of_type ty〉=〈i, t〉)*)
1656                      | 2: whd @Exists_squeeze @(characterise_vars_all globals f ?? (sym_eq ??? E) i t H')
1657                      | 3: * #id #ty * #E1 #E2 <E1 <E2 @refl
1658                      ]
1659        | 2: #EX @Exists_append_r whd in ⊢ (???%); <map_append @Exists_append_l
1660          @Exists_map [ 1: #x @(And (\fst x = i) (typ_of_type (\snd x) = t))
1661                      | 2: <Hfgens @EX
1662                      | 3: * #id #ty * #E1 #E2 <E1 <E2 % @refl
1663                      ]
1664        ]
1665     | 2: (* prove that labels are properly declared. *)
1666          @(stmt_labels_mp … Hstmt_labels) #l * *
1667          [ 1: #H assumption
1668          | 2: * #cl_label #Hlookup lapply (Ilbls cl_label l Hlookup) #Hdefined
1669                cases (Hlab_trans … Hdefined) #lx * #LOOKUPx >LOOKUPx in Hlookup; #Ex destruct (Ex)
1670                #H @H
1671          ]
1672     | cases s in Hstmt_return; // * normalize [2: * #t #e ]
1673       cases (fn_return f) normalize #A try #B try #C try #D try #E destruct //
1674    ]
1675] qed.   
1676
1677definition translate_fundef :
1678  ∀tmpuniverse:universe SymbolTag.
1679  ∀globals:list (ident×region×type).
1680    globals_fresh_for_univ ? globals tmpuniverse →
1681  ∀f:clight_fundef.
1682    fd_fresh_for_univ f tmpuniverse →
1683  res (fundef internal_function) ≝
1684λtmpuniverse,globals,Fglobals,f.
1685match f return λf. fd_fresh_for_univ f ? → ? with
1686[ CL_Internal fn ⇒ λFf. do fn' ← translate_function tmpuniverse globals fn Fglobals Ff; OK ? (Internal ? fn')
1687| CL_External fn argtys retty ⇒ λ_. OK ? (External ? (mk_external_function fn (signature_of_type argtys retty)))
1688].
1689
1690let rec map_partial_All (A,B:Type[0]) (P:A → Prop) (f:∀a:A. P a → res B)
1691  (l:list A) (H:All A P l) on l : res (list B) ≝
1692match l return λl. All A P l → ? with
1693[ nil ⇒ λ_. OK (list B) (nil B)
1694| cons hd tl ⇒ λH.
1695    do b_hd ← f hd (proj1 … H);
1696    do b_tl ← map_partial_All A B P f tl (proj2 … H);
1697      OK (list B) (cons B b_hd b_tl)
1698] H.
1699
1700definition clight_to_cminor : clight_program → res Cminor_program ≝
1701λp.
1702  let tmpuniverse ≝ universe_for_program p in
1703  let fun_globals ≝ map ?? (λidf. 〈\fst idf,Code,type_of_fundef (\snd idf)〉) (prog_funct ?? p) in
1704  let var_globals ≝ map ?? (λv. 〈\fst (\fst v), \snd (\fst v), \snd (\snd v)〉) (prog_vars ?? p) in
1705  let globals ≝ fun_globals @ var_globals in
1706  do fns ← map_partial_All ??? (λx,H. do f ← translate_fundef tmpuniverse globals ? (\snd x) H; OK ? 〈\fst x, f〉) (prog_funct ?? p) ?;
1707    OK ? (mk_program ??
1708      (map ?? (λv. 〈\fst v, \fst (\snd v)〉) (prog_vars ?? p))
1709      fns
1710      (prog_main ?? p)).
1711cases (prog_fresh p) * #H1 #H2 #H3
1712[ @(All_mp … H1) #x * //
1713| @All_append
1714  [ elim (prog_funct ?? p) in H1 ⊢ %; // * #id #fd #tl #IH * * #Hhd1 #Hhd2 #Htl % // @IH @Htl
1715  | whd in H3; elim (prog_vars ?? p) in H3 ⊢ %; // #hd #tl #IH * #Hhd #Htl % /2/
1716  ]
1717] qed.
1718
1719(* It'd be nice to go back to some generic thing like
1720
1721 transform_partial_program2 … p (translate_fundef tmpuniverse globals) (λi. OK ? (\fst i)).
1722
1723   rather than the messier definition above.
1724*)
Note: See TracBrowser for help on using the repository browser.