Debian Codegraph @

src/Stringification/IR.v

raw
1 From Coq Require Import ZArith.
2 From Coq Require Import MSetPositive.
3 From Coq Require Import FMapPositive.
4 From Coq Require Import String.
5 From Coq Require Import Ascii.
6 From Coq Require Import Bool.
7 From Coq Require Import HexString.
8 Require Import Crypto.Util.ListUtil Coq.Lists.List.
9 Require Crypto.Util.Strings.String.
10 Require Import Crypto.Util.Strings.Decimal.
11 Require Import Crypto.Util.Strings.Show.
12 Require Import Crypto.Util.ZRange.
13 Require Import Crypto.Util.ZRange.Operations.
14 Require Import Crypto.Util.ZRange.Show.
15 Require Import Crypto.Util.Option.
16 Require Import Crypto.Util.OptionList.
17 Require Import Rewriter.Language.Language.
18 Require Import Crypto.Language.API.
19 Require Import Crypto.Stringification.Language.
20 Require Import Crypto.AbstractInterpretation.ZRange.
21 Require Import Crypto.AbstractInterpretation.AbstractInterpretation.
22 Require Import Crypto.Util.Bool.Equality.
23 Require Import Crypto.Util.Notations.
24 Import Coq.Lists.List ListNotations. Local Open Scope zrange_scope. Local Open Scope Z_scope.
25
26 Module Compilers.
27 Local Set Boolean Equality Schemes.
28 Local Set Decidable Equality Schemes.
29 Export Language.Compilers.
30 Export Language.API.Compilers.
31 Export AbstractInterpretation.Compilers.
32 Export AbstractInterpretation.ZRange.Compilers.
33 Export Stringification.Language.Compilers.
34 Import invert_expr.
35 Import Compilers.API.
36
37 Local Notation tZ := (base.type.type_base base.type.Z).
38
39 Module ToString.
40 Import Stringification.Language.Compilers.ToString.
41 Import Stringification.Language.Compilers.ToString.ZRange.
42 Local Open Scope string_scope.
43 Local Open Scope Z_scope.
44
45 Module IR.
46 Module type.
47 Inductive primitive := Z | Zptr.
48 Inductive type := type_primitive (t : primitive) | prod (A B : type) | unit.
49 Module Export Notations.
50 Global Coercion type_primitive : primitive >-> type.
51 Declare Scope Ctype_scope.
52 Delimit Scope Ctype_scope with Ctype.
53
54 Bind Scope Ctype_scope with type.
55 Notation "()" := unit : Ctype_scope.
56 Notation "A * B" := (prod A B) : Ctype_scope.
57 Notation type := type.
58 End Notations.
59 End type.
60 Import type.Notations.
61 Import int.Notations.
62
63 Section ident.
64 Import type.
65 Inductive Z_binop : Set :=
66 | Z_land
67 | Z_lor
68 | Z_lxor
69 | Z_add
70 | Z_mul
71 | Z_sub
72 .
73 Inductive Z_unop : Set :=
74 | Z_shiftr (offset : BinInt.Z)
75 | Z_shiftl (offset : BinInt.Z)
76 (*| Z_opp*)
77 | Z_lnot (ty:int.type)
78 | Z_bneg
79 | Z_value_barrier (ty:int.type)
80 .
81 Inductive ident : type -> type -> Set :=
82 | literal (v : BinInt.Z) : ident unit Z
83 | List_nth (n : Datatypes.nat) : ident Zptr Z
84 | Addr : ident Z Zptr
85 | Dereference : ident Zptr Z
86 | iunop (op : Z_unop) : ident Z Z
87 | ibinop (op : Z_binop) : ident (Z * Z) Z
88 | Z_mul_split (lgs:BinInt.Z) : ident ((Zptr * Zptr) * (Z * Z)) unit
89 | Z_add_with_get_carry (lgs:BinInt.Z) : ident ((Zptr * Zptr) * (Z * Z * Z)) unit
90 | Z_sub_with_get_borrow (lgs:BinInt.Z) : ident ((Zptr * Zptr) * (Z * Z * Z)) unit
91 | Z_zselect (ty:int.type) : ident (Zptr * (Z * Z * Z)) unit
92 | Z_add_modulo : ident (Z * Z * Z) Z
93 | Z_static_cast (ty : int.type) : ident Z Z
94 .
95 End ident.
96
97 Inductive arith_expr : type -> Set :=
98 | AppIdent {s d} (idc : ident s d) (arg : arith_expr s) : arith_expr d
99 | Var (t : type.primitive) (v : string) : arith_expr t
100 | Pair {A B} (a : arith_expr A) (b : arith_expr B) : arith_expr (A * B)
101 | TT : arith_expr type.unit.
102
103 Inductive stmt :=
104 | Call (val : arith_expr type.unit)
105 | Comment (lines : list string) (mentioned_variables : list { t : _ & OfPHOAS.var_data t})
106 | Assign (declare : bool) (t : type.primitive) (sz : option int.type) (name : string) (val : arith_expr t)
107 | AssignZPtr (name : string) (sz : option int.type) (val : arith_expr type.Z)
108 | DeclareVar (t : type.primitive) (sz : option int.type) (name : string)
109 | AssignNth (name : string) (n : nat) (val : arith_expr type.Z).
110 Definition expr := list stmt.
111
112 Module Export Notations.
113 Export int.Notations.
114 Export type.Notations.
115 Declare Scope Cexpr_scope.
116 Delimit Scope Cexpr_scope with Cexpr.
117 Bind Scope Cexpr_scope with expr.
118 Bind Scope Cexpr_scope with stmt.
119 Bind Scope Cexpr_scope with arith_expr.
120 Infix "@@@" := AppIdent : Cexpr_scope.
121 Notation "( x , y , .. , z )" := (Pair .. (Pair x%Cexpr y%Cexpr) .. z%Cexpr) : Cexpr_scope.
122 Notation "( )" := TT : Cexpr_scope.
123
124 Notation "()" := TT : Cexpr_scope.
125 Notation "x ;; y" := (@cons stmt x%Cexpr y%Cexpr) (at level 70, right associativity, format "'[v' x ;; '/' y ']'") : Cexpr_scope.
126 Global Coercion iunop : Z_unop >-> ident.
127 Global Coercion ibinop : Z_binop >-> ident.
128 End Notations.
129
130 Definition invert_literal {t} (e : arith_expr t) : option (BinInt.Z)
131 := match e with
132 | AppIdent s d (literal v) arg => Some v
133 | _ => None
134 end.
135
136 Module ident_infos.
137 Definition collect_infos_of_ident {s d} (idc : ident s d) : ident_infos
138 := match idc with
139 | Z_static_cast ty => ident_info_of_bitwidths_used (IntSet.singleton ty)
140 | Z_mul_split lg2s
141 => ident_info_of_mulx (PositiveSet.add (Z.to_pos lg2s) PositiveSet.empty)
142 | Z_add_with_get_carry lg2s
143 | Z_sub_with_get_borrow lg2s
144 => ident_info_of_addcarryx (PositiveSet.add (Z.to_pos lg2s) PositiveSet.empty)
145 | Z_zselect ty
146 => ident_info_of_cmovznz (IntSet.singleton ty)
147 | iunop (Z_value_barrier ty)
148 =>ident_info_of_value_barrier (IntSet.singleton ty)
149 | literal _
150 | List_nth _
151 | Addr
152 | Dereference
153 | ibinop _
154 | iunop _
155 | Z_add_modulo
156 => ident_info_empty
157 end.
158 Fixpoint collect_infos_of_arith_expr {t} (e : arith_expr t) : ident_infos
159 := match e with
160 | AppIdent s d idc arg => ident_info_union (collect_infos_of_ident idc) (@collect_infos_of_arith_expr _ arg)
161 | Var t v => ident_info_empty
162 | Pair A B a b => ident_info_union (@collect_infos_of_arith_expr _ a) (@collect_infos_of_arith_expr _ b)
163 | TT => ident_info_empty
164 end.
165
166 Definition collect_infos_of_stmt (e : stmt) : ident_infos
167 := match e with
168 | Assign _ _ (Some sz) _ val
169 | AssignZPtr _ (Some sz) val
170 => ident_info_union (ident_info_of_bitwidths_used (IntSet.singleton sz)) (collect_infos_of_arith_expr val)
171 | Call val
172 | Assign _ _ None _ val
173 | AssignZPtr _ None val
174 | AssignNth _ _ val
175 => collect_infos_of_arith_expr val
176 | DeclareVar _ (Some sz) _
177 => ident_info_of_bitwidths_used (IntSet.singleton sz)
178 | DeclareVar _ None _
179 | Comment _ _
180 => ident_info_empty
181 end.
182
183 Fixpoint collect_infos_of_base_typedef_data {t} : OfPHOAS.base_var_typedef_data t -> ident_infos
184 := match t return OfPHOAS.base_var_typedef_data t -> ident_infos with
185 | tZ
186 => fun n => match n with
187 | Some n => ident_info_of_typedefs [n]
188 | None => ident_info_empty
189 end
190 | base.type.prod A B
191 => fun '(tda, tdb)
192 => ident_info_union (@collect_infos_of_base_typedef_data A tda)
193 (@collect_infos_of_base_typedef_data B tdb)
194 | base.type.list tZ
195 => fun n => match n with
196 | Some n => ident_info_of_typedefs [n]
197 | None => ident_info_empty
198 end
199 | base.type.list _
200 | base.type.option _
201 | base.type.type_base _
202 | base.type.unit
203 => fun _ => ident_info_empty
204 end.
205
206 Definition collect_infos_of_typedef_data {t} : OfPHOAS.var_typedef_data t -> ident_infos
207 := match t return OfPHOAS.var_typedef_data t -> ident_infos with
208 | type.base t => collect_infos_of_base_typedef_data
209 | type.arrow _ _ => fun 'tt => ident_info_empty
210 end.
211
212 Fixpoint collect_infos_of_arg_typedef_data {t} : type.for_each_lhs_of_arrow OfPHOAS.var_typedef_data t -> ident_infos
213 := match t with
214 | type.base _ => fun 'tt => ident_info_empty
215 | type.arrow s d
216 => fun '(td, tds)
217 => ident_info_union (collect_infos_of_typedef_data td)
218 (@collect_infos_of_arg_typedef_data d tds)
219 end.
220
221 Definition collect_infos (e : expr) : ident_infos
222 := fold_right
223 ident_info_union
224 ident_info_empty
225 (List.map
226 collect_infos_of_stmt
227 e).
228
229 Definition collect_all_infos {skip_typedefs : skip_typedefs_opt}
230 (e : expr)
231 {t}
232 (intypedefs : type.for_each_lhs_of_arrow OfPHOAS.var_typedef_data t)
233 (outtypedefs : OfPHOAS.base_var_typedef_data (type.final_codomain t))
234 := ident_info_union
235 (collect_infos e)
236 (if skip_typedefs
237 then ident_info_empty
238 else ident_info_union
239 (ident_infos.collect_infos_of_arg_typedef_data intypedefs)
240 (ident_infos.collect_infos_of_typedef_data (t:=type.base _) outtypedefs)).
241 End ident_infos.
242
243 Module name_infos.
244 Notation t := (list string) (only parsing).
245 Definition mem (v : string) (m : t) : bool := existsb (fun s => v =? s)%string m.
246 Definition add (v : string) (m : t) : t
247 := if mem v m then m else v :: m.
248 Definition union (m1 m2 : t) : t
249 := let '(l1, l2) := (List.length m1, List.length m2) in
250 let '(m1, m2) := if (l1 <=? l2)%nat then (m1, m2) else (m2, m1) in
251 (* now m1 is shorter, so we recurse over m1 *)
252 List.fold_right add m2 m1.
253 Definition empty : t := nil.
254 Definition singleton (v : string) : t := add v empty.
255 Definition of_list (v : list string) : t := v.
256
257 Section __.
258 Context (consider_retargs_live : forall s d, ident s d -> bool).
259
260 Let consider_addr_dead s d (idc : ident s d) : bool
261 := match idc with
262 | Addr => false
263 | _ => true
264 end.
265
266 Fixpoint collect_live_of_arith_expr
267 (consider_args_live : forall s d, ident s d -> bool)
268 {t'} (e : arith_expr t') : t
269 := match e with
270 | AppIdent s d idc arg
271 => if consider_args_live s d idc
272 then @collect_live_of_arith_expr
273 (if consider_retargs_live s d idc
274 then consider_args_live
275 else consider_addr_dead)
276 _ arg
277 else empty
278 | Var t v => singleton v
279 | Pair A B a b => union (@collect_live_of_arith_expr consider_args_live _ a) (@collect_live_of_arith_expr consider_args_live _ b)
280 | TT => empty
281 end.
282
283 Definition collect_live_of_stmt (e : stmt) : t
284 := match e with
285 | Assign _ _ _ _ val
286 | AssignZPtr _ _ val
287 | Call val
288 | AssignNth _ _ val
289 => collect_live_of_arith_expr (fun _ _ _ => true) val
290 | Comment _ live_vars
291 => of_list (List.flat_map (fun v => OfPHOAS.names_list_of_var_data (projT2 v)) live_vars)
292 | DeclareVar _ _ _ => empty
293 end.
294
295 Definition collect_live (e : expr) : t
296 := fold_right
297 union
298 empty
299 (List.map
300 collect_live_of_stmt
301 e).
302
303 Section adjust_dead.
304 Context (rename_dead : string -> string)
305 (live : t).
306
307 Definition rename_if_dead (v : string) : string
308 := if mem v live then v else rename_dead v.
309
310 Fixpoint adjust_dead_of_arith_expr {t'} (e : arith_expr t') : arith_expr t'
311 := match e with
312 | AppIdent s d idc arg => AppIdent idc (@adjust_dead_of_arith_expr _ arg)
313 | Var t v => Var t (rename_if_dead v)
314 | Pair A B a b => Pair (@adjust_dead_of_arith_expr _ a) (@adjust_dead_of_arith_expr _ b)
315 | TT => TT
316 end.
317
318 Definition adjust_dead_of_stmt (e : stmt) : list stmt
319 := match e with
320 | Call val
321 => [Call (adjust_dead_of_arith_expr val)]
322 | Assign declare t sz name val
323 => [Assign declare t sz name (adjust_dead_of_arith_expr val)]
324 | AssignZPtr name sz val
325 => [AssignZPtr name sz (adjust_dead_of_arith_expr val)]
326 | AssignNth name n val
327 => [AssignNth name n (adjust_dead_of_arith_expr val)]
328 | DeclareVar t sz name
329 => if mem name live
330 then [DeclareVar t sz name]
331 else []
332 | Comment _ _ as e
333 => [e]
334 end.
335
336 Definition adjust_dead_of_expr (e : expr) : expr
337 := flat_map adjust_dead_of_stmt e.
338 End adjust_dead.
339
340 Definition adjust_dead (rename_dead : string -> string) (e : expr) : expr
341 := adjust_dead_of_expr rename_dead (collect_live e) e.
342 End __.
343 End name_infos.
344
345 Module LiftDeclare.
346 Local Open Scope list_scope.
347
348 Definition split_declare (e : stmt) : list stmt (* decls *) * list stmt (* non-decls *)
349 := match e with
350 | Assign true t sz name val
351 => ([DeclareVar t sz name], [Assign false t sz name val])
352 | DeclareVar _ _ _ as e
353 => ([e], [])
354 | e => ([], [e])
355 end.
356
357 Definition split_declarations (e : expr) : expr (* decls *) * expr (* non-decls *)
358 := let ls := List.map split_declare e in
359 (List.flat_map (@fst _ _) ls,
360 List.flat_map (@snd _ _) ls).
361
362 Definition lift_declarations (e : expr) : expr
363 := let '(decls, rest) := split_declarations e in
364 decls ++ rest.
365 End LiftDeclare.
366
367 Module OfPHOAS.
368 Export Stringification.Language.Compilers.ToString.OfPHOAS.
369
370 Fixpoint arith_expr_for_base (t : base.type) : Type
371 := match t with
372 | tZ
373 => arith_expr type.Z * option int.type
374 | base.type.prod A B
375 => arith_expr_for_base A * arith_expr_for_base B
376 | base.type.list A => list (arith_expr_for_base A)
377 | base.type.option A => option (arith_expr_for_base A)
378 | base.type.unit as t
379 | base.type.type_base _ as t
380 => base.interp t
381 end.
382 Definition arith_expr_for (t : Compilers.type.type base.type) : Type
383 := match t with
384 | type.base t => arith_expr_for_base t
385 | type.arrow s d => Empty_set
386 end.
387
388 (* Parametrizes the PHOAS -> IR translation over language specific
389 numeric conversions *)
390 Class LanguageCasts :=
391 {
392 (* [bin_op_natural_output] takes in a binary operation and
393 the known types that the input fits into, and returns
394 the type that the output will land in if no casts are
395 present. *)
396 bin_op_natural_output
397 : Z_binop -> int.type * int.type -> int.type;
398 (* [bin_op_casts] takes in a binary operation, the known
399 type that the output fits in, and the pair of known
400 types that the inputs fit in. It returns the triple of
401 (output, (input1, intput2)) of casts that are necessary
402 for running the operation. No-op casts on the inputs
403 will later be discarded; the cast on the output, if
404 given, will always be used. *)
405 bin_op_casts
406 : Z_binop -> option int.type -> int.type * int.type -> option int.type * (option int.type * option int.type);
407 (* [un_op_casts] takes in a unary operation, the known
408 type that the output fits in, and the known types that
409 the input fits in. It returns the tuple of (output,
410 input) of casts that are necessary for running the
411 operation. No-op casts on the inputs will later be
412 discarded; the cast on the output, if given, will
413 always be used. *)
414 un_op_casts
415 : Z_unop -> option int.type -> int.type -> option int.type * option int.type;
416 (* Are upcasts necessary on assignments? *)
417 upcast_on_assignment : bool;
418 (* Are upcasts necessary for arguments to function calls? *)
419 upcast_on_funcall : bool;
420
421 (* Should we declare pointer variables explicitly (rather than declaring non-pointer variables and taking references to them *)
422 explicit_pointer_variables : bool;
423 }.
424
425 Class consider_retargs_live_opt := consider_retargs_live : forall {s d}, ident s d -> bool.
426 Class rename_dead_opt := rename_dead : string -> string.
427 Class lift_declarations_opt := lift_declarations : bool.
428
429 Section __.
430 Context {lang_casts : LanguageCasts}
431 {relax_zrange : relax_zrange_opt}
432 {consider_retargs_live : consider_retargs_live_opt}
433 {rename_dead : rename_dead_opt}
434 {lift_declarations : lift_declarations_opt}
435 {language_specific_cast_adjustment : language_specific_cast_adjustment_opt}.
436
437 (* None means unconstrained *)
438 Definition bin_op_natural_output_opt
439 : Z_binop -> option int.type * option int.type -> option int.type
440 := fun idc '(t1, t2)
441 => match t1, t2 with
442 | Some t1, Some t2 => Some (bin_op_natural_output idc (t1, t2))
443 | _, _ => None
444 end.
445 Definition bin_op_casts_opt
446 : Z_binop -> option int.type -> option int.type * option int.type -> option int.type * (option int.type * option int.type)
447 := fun idc tout '(t1, t2)
448 => match t1, t2 with
449 | Some t1, Some t2
450 => bin_op_casts idc tout (t1, t2)
451 | _, _ => (tout, (None, None))
452 end.
453 Definition un_op_casts_opt
454 : Z_unop -> option int.type -> option int.type -> option int.type * option int.type
455 := fun idc tout t1
456 => match t1 with
457 | Some t1
458 => un_op_casts idc tout t1
459 | None => (tout, None)
460 end.
461
462 Definition Zcast {always : bool}
463 : option int.type -> arith_expr_for_base tZ -> arith_expr_for_base tZ
464 := fun desired_type '(e, known_type)
465 => let eq_known_type_desired_type
466 := (known_type <- known_type;
467 desired_type <- desired_type;
468 Some (int.type_beq known_type desired_type))%option in
469 match always, language_specific_cast_adjustment, desired_type, eq_known_type_desired_type with
470 | true, _, Some desired_type, _ (* if we always insert the cast, and there's a cast, then insert it *)
471 | _, true, Some desired_type, Some false (* if we are doing language-specific casts and we know the desired type and it's not the same as the known type, insert it *)
472 | _, true, Some desired_type, None (* if we are doing language-specific casts and we know the desired type and there was no known type, insert it *)
473 => (Z_static_cast desired_type @@@ e, Some desired_type)
474 | false, false, _, _ (* if we're not doing cast insertion (neither by forcing nor by language-specific casts), don't insert a cast *)
475 | _, true, Some _, Some true (* if we're doing language-specific casts but the new type is the same as the known type, we don't need to insert a cast *)
476 | _, _, None, _ (* if we don't know the type to insert, we can't insert a cast *)
477 => (e, known_type)
478 end%core%Cexpr%bool.
479
480 Definition get_Zcast_down_if_needed
481 : option int.type -> option int.type -> option int.type
482 := fun desired_type known_type
483 => match desired_type, known_type with
484 | None, _ => None
485 | Some desired_type, Some known_type
486 => if int.is_tighter_than known_type desired_type
487 then None
488 else Some desired_type
489 | Some desired_type, None
490 => Some desired_type
491 end%core%Cexpr.
492
493 Definition Zcast_down_if_needed
494 : option int.type -> arith_expr_for_base tZ -> arith_expr_for_base tZ
495 := fun desired_type '(e, known_type)
496 => Zcast (always:=false) (get_Zcast_down_if_needed desired_type known_type) (e, known_type).
497
498 Fixpoint cast_down_if_needed {t}
499 : int.option.interp t -> arith_expr_for_base t -> arith_expr_for_base t
500 := match t with
501 | tZ => Zcast_down_if_needed
502 | base.type.type_base _
503 | base.type.unit
504 => fun _ x => x
505 | base.type.prod A B
506 => fun '(r1, r2) '(e1, e2) => (@cast_down_if_needed A r1 e1,
507 @cast_down_if_needed B r2 e2)
508 | base.type.list A
509 => fun r1 ls
510 => match r1 with
511 | Some r1 => List.map (fun '(r, e) => @cast_down_if_needed A r e)
512 (List.combine r1 ls)
513 | None => ls
514 end
515 | base.type.option A
516 => fun r1 ls
517 => match r1 with
518 | Some r1 => Option.map (fun '(r, e) => @cast_down_if_needed A r e)
519 (Option.combine r1 ls)
520 | None => ls
521 end
522 end.
523
524 Definition get_Zcast_up_if_needed
525 : option int.type -> option int.type -> option int.type
526 := fun desired_type known_type
527 => match desired_type, known_type with
528 | None, _ | _, None => None
529 | Some desired_type, Some known_type
530 => if int.is_tighter_than desired_type known_type
531 then None
532 else Some desired_type
533 end.
534
535 Definition Zcast_up_if_needed
536 : option int.type -> arith_expr_for_base tZ -> arith_expr_for_base tZ
537 := fun desired_type '(e, known_type)
538 => Zcast (always:=false) (get_Zcast_up_if_needed desired_type known_type) (e, known_type).
539
540 Fixpoint cast_up_if_needed {t}
541 : int.option.interp t -> arith_expr_for_base t -> arith_expr_for_base t
542 := match t with
543 | tZ => Zcast_up_if_needed
544 | base.type.type_base _
545 | base.type.unit
546 => fun _ x => x
547 | base.type.prod A B
548 => fun '(r1, r2) '(e1, e2) => (@cast_up_if_needed A r1 e1,
549 @cast_up_if_needed B r2 e2)
550 | base.type.list A
551 => fun r1 ls
552 => match r1 with
553 | Some r1 => List.map (fun '(r, e) => @cast_up_if_needed A r e)
554 (List.combine r1 ls)
555 | None => ls
556 end
557 | base.type.option A
558 => fun r1 ls
559 => match r1 with
560 | Some r1 => Option.map (fun '(r, e) => @cast_up_if_needed A r e)
561 (Option.combine r1 ls)
562 | None => ls
563 end
564 end.
565
566 Fixpoint cast {always:bool} {t}
567 : int.option.interp t -> arith_expr_for_base t -> arith_expr_for_base t
568 := match t with
569 | tZ => Zcast (always:=always)
570 | base.type.type_base _
571 | base.type.unit
572 => fun _ x => x
573 | base.type.prod A B
574 => fun '(r1, r2) '(e1, e2) => (@cast always A r1 e1,
575 @cast always B r2 e2)
576 | base.type.list A
577 => fun r1 ls
578 => match r1 with
579 | Some r1 => List.map (fun '(r, e) => @cast always A r e)
580 (List.combine r1 ls)
581 | None => ls
582 end
583 | base.type.option A
584 => fun r1 ls
585 => match r1 with
586 | Some r1 => Option.map (fun '(r, e) => @cast always A r e)
587 (Option.combine r1 ls)
588 | None => ls
589 end
590 end.
591
592 Definition arith_bin_arith_expr_of_PHOAS_ident
593 (s:=(tZ * tZ)%etype)
594 (d:=tZ)
595 (idc : Z_binop)
596 : option int.type -> arith_expr_for (type.base s) -> arith_expr_for (type.base d)
597 := fun desired_type '((e1, t1), (e2, t2)) =>
598 let '(cstout, (cst1, cst2)) := bin_op_casts_opt idc desired_type (t1, t2) in
599 let typ := bin_op_natural_output_opt idc (Option.or_else cst1 t1, Option.or_else cst2 t2) in
600 let '((e1, t1), (e2, t2)) := (Zcast (always:=false) cst1 (e1, t1), Zcast (always:=false) cst2 (e2, t2)) in
601 Zcast (always:=false) cstout ((idc @@@ (e1, e2))%Cexpr, typ).
602
603 Definition arith_un_arith_expr_of_PHOAS_ident
604 (s:=tZ)
605 (d:=tZ)
606 (idc : Z_unop)
607 : option int.type -> arith_expr_for (type.base s) -> arith_expr_for (type.base d)
608 := fun desired_type '(e, t) =>
609 let '(cstout, cst) := un_op_casts_opt idc desired_type t in
610 let typ := (*un_op_natural_output_opt idc*) Option.or_else cst t in
611 let '(e, t) := Zcast (always:=false) cst (e, t) in
612 Zcast (always:=false) cstout ((idc @@@ e)%Cexpr, typ).
613
614 Local Definition fakeprod (A B : Compilers.type.type base.type) : Compilers.type.type base.type
615 := match A, B with
616 | type.base A, type.base B => type.base (base.type.prod A B)
617 | type.arrow _ _, _
618 | _, type.arrow _ _
619 => type.base base.type.unit
620 end.
621 Definition arith_expr_for_uncurried_domain (t : Compilers.type.type base.type)
622 := match t return Type with
623 | type.base t => unit
624 | type.arrow s d => arith_expr_for (type.uncurried_domain fakeprod s d)
625 end.
626
627 Section with_bind.
628 (* N.B. If we make the [bind*_err] notations, then Coq can't
629 infer types correctly; if we make them [Local
630 Definition]s or [Let]s, then [ocamlopt] fails with
631 "Error: The type of this module, [...], contains type
632 variables that cannot be generalized". We need to run
633 [cbv] below to actually unfold them. >.< *)
634 Local Notation ErrT T := (T + list string)%type.
635 Local Notation ret v := (@inl _ (list string) v) (only parsing).
636 Local Notation "x <- v ; f" := (match v with
637 | inl x => f
638 | inr err => inr err
639 end).
640 Declare Scope err_scope.
641 (*Local*) Delimit Scope err_scope with err.
642 Local Notation "x <- v ; f" := (match v with
643 | inl x => f
644 | inr err => inr err
645 end) : err_scope.
646 Reserved Notation "A1 ,, A2 <- X ; B" (at level 70, A2 at next level, right associativity, format "'[v' A1 ,, A2 <- X ; '/' B ']'").
647 Reserved Notation "A1 ,, A2 <- X1 , X2 ; B" (at level 70, A2 at next level, right associativity, format "'[v' A1 ,, A2 <- X1 , X2 ; '/' B ']'").
648 Reserved Notation "A1 ,, A2 ,, A3 <- X ; B" (at level 70, A2 at next level, A3 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 <- X ; '/' B ']'").
649 Reserved Notation "A1 ,, A2 ,, A3 <- X1 , X2 , X3 ; B" (at level 70, A2 at next level, A3 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 <- X1 , X2 , X3 ; '/' B ']'").
650 Reserved Notation "A1 ,, A2 ,, A3 ,, A4 <- X ; B" (at level 70, A2 at next level, A3 at next level, A4 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 ,, A4 <- X ; '/' B ']'").
651 Reserved Notation "A1 ,, A2 ,, A3 ,, A4 <- X1 , X2 , X3 , X4 ; B" (at level 70, A2 at next level, A3 at next level, A4 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 ,, A4 <- X1 , X2 , X3 , X4 ; '/' B ']'").
652 Reserved Notation "A1 ,, A2 ,, A3 ,, A4 ,, A5 <- X ; B" (at level 70, A2 at next level, A3 at next level, A4 at next level, A5 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 ,, A4 ,, A5 <- X ; '/' B ']'").
653 Reserved Notation "A1 ,, A2 ,, A3 ,, A4 ,, A5 <- X1 , X2 , X3 , X4 , X5 ; B" (at level 70, A2 at next level, A3 at next level, A4 at next level, A5 at next level, right associativity, format "'[v' A1 ,, A2 ,, A3 ,, A4 ,, A5 <- X1 , X2 , X3 , X4 , X5 ; '/' B ']'").
654 Let bind2_err {A B C} (v1 : ErrT A) (v2 : ErrT B) (f : A -> B -> ErrT C) : ErrT C
655 := match v1, v2 with
656 | inl x1, inl x2 => f x1 x2
657 | inr err, inl _ | inl _, inr err => inr err
658 | inr err1, inr err2 => inr (List.app err1 err2)
659 end.
660 Local Notation "x1 ,, x2 <- v1 , v2 ; f"
661 := (bind2_err v1 v2 (fun x1 x2 => f)).
662 Local Notation "x1 ,, x2 <- v ; f"
663 := (x1 ,, x2 <- fst v , snd v; f).
664 Let bind3_err {A B C R} (v1 : ErrT A) (v2 : ErrT B) (v3 : ErrT C) (f : A -> B -> C -> ErrT R) : ErrT R
665 := (x12 ,, x3 <- (x1 ,, x2 <- v1, v2; inl (x1, x2)), v3;
666 let '(x1, x2) := x12 in
667 f x1 x2 x3).
668 Local Notation "x1 ,, x2 ,, x3 <- v1 , v2 , v3 ; f"
669 := (bind3_err v1 v2 v3 (fun x1 x2 x3 => f)).
670 Local Notation "x1 ,, x2 ,, x3 <- v ; f"
671 := (let '(v1, v2, v3) := v in x1 ,, x2 ,, x3 <- v1 , v2 , v3; f).
672 Let bind4_err {A B C D R} (v1 : ErrT A) (v2 : ErrT B) (v3 : ErrT C) (v4 : ErrT D) (f : A -> B -> C -> D -> ErrT R) : ErrT R
673 := (x12 ,, x34 <- (x1 ,, x2 <- v1, v2; inl (x1, x2)), (x3 ,, x4 <- v3, v4; inl (x3, x4));
674 let '((x1, x2), (x3, x4)) := (x12, x34) in
675 f x1 x2 x3 x4).
676 Local Notation "x1 ,, x2 ,, x3 ,, x4 <- v1 , v2 , v3 , v4 ; f"
677 := (bind4_err v1 v2 v3 v4 (fun x1 x2 x3 x4 => f)).
678 Local Notation "x1 ,, x2 ,, x3 ,, x4 <- v ; f"
679 := (let '(v1, v2, v3, v4) := v in x1 ,, x2 ,, x3 ,, x4 <- v1 , v2 , v3 , v4; f).
680 Let bind5_err {A B C D E R} (v1 : ErrT A) (v2 : ErrT B) (v3 : ErrT C) (v4 : ErrT D) (v5 : ErrT E) (f : A -> B -> C -> D -> E -> ErrT R) : ErrT R
681 := (x12 ,, x345 <- (x1 ,, x2 <- v1, v2; inl (x1, x2)), (x3 ,, x4 ,, x5 <- v3, v4, v5; inl (x3, x4, x5));
682 let '((x1, x2), (x3, x4, x5)) := (x12, x345) in
683 f x1 x2 x3 x4 x5).
684 Local Notation "x1 ,, x2 ,, x3 ,, x4 ,, x5 <- v1 , v2 , v3 , v4 , v5 ; f"
685 := (bind5_err v1 v2 v3 v4 v5 (fun x1 x2 x3 x4 x5 => f)).
686 Local Notation "x1 ,, x2 ,, x3 ,, x4 ,, x5 <- v ; f"
687 := (let '(v1, v2, v3, v4, v5) := v in x1 ,, x2 ,, x3 ,, x4 ,, x5 <- v1 , v2 , v3 , v4 , v5; f).
688
689 Definition maybe_log2 (s : Z) : option Z
690 := if 2^Z.log2 s =? s then Some (Z.log2 s) else None.
691 Definition maybe_loglog2 (s : Z) : option nat
692 := (v <- maybe_log2 s;
693 v <- maybe_log2 v;
694 if Z.leb 0 v
695 then Some (Z.to_nat v)
696 else None).
697
698
699 Definition arith_expr_of_PHOAS_literal_Z
700 (t:=tZ)
701 v
702 : int.option.interp (type.final_codomain t) -> arith_expr_for_base t
703 := fun r
704 => cast_down_if_needed
705 r
706 (literal v @@@ TT, Some (int.of_zrange_relaxed (relax_zrange r[v~>v])))%core%Cexpr%option%zrange.
707
708 Definition arith_expr_of_PHOAS_ident
709 {t}
710 (idc : ident.ident t)
711 : int.option.interp (type.final_codomain t) -> type.interpM_final (fun T => ErrT T) arith_expr_for_base t
712 := match idc in ident.ident t return int.option.interp (type.final_codomain t) -> type.interpM_final (fun T => ErrT T) arith_expr_for_base t with
713 | ident.Literal base.type.Z v
714 => fun r => ret (arith_expr_of_PHOAS_literal_Z v r)
715 | ident.tt => fun _ => ret tt
716 | ident.nil t
717 => fun _ => ret nil
718 | ident.cons t
719 => fun r x xs => ret (cast_down_if_needed r (cons x xs))
720 | ident.fst A B => fun r xy => ret (cast_down_if_needed r (@fst _ _ xy))
721 | ident.snd A B => fun r xy => ret (cast_down_if_needed r (@snd _ _ xy))
722 | ident.List_nth_default tZ
723 => fun r d ls n
724 => List.nth_default (inr ["Invalid list index " ++ show n]%string)
725 (List.map (fun x => ret (cast_down_if_needed r x)) ls) n
726 | ident.Z_shiftr
727 => fun r e '(offset, roffset)
728 => match invert_literal offset with
729 | Some offset
730 => ret (arith_un_arith_expr_of_PHOAS_ident (Z_shiftr offset) r e)
731 | None => inr ["Invalid right-shift by a non-literal"]%string
732 end
733 | ident.Z_shiftl
734 => fun r e '(offset, roffset)
735 => match invert_literal offset with
736 | Some offset
737 => ret (arith_un_arith_expr_of_PHOAS_ident (Z_shiftl offset) r e)
738 | None => inr ["Invalid left-shift by a non-literal"]%string
739 end
740 | ident.Z_truncating_shiftl
741 => fun r '(bitwidth, rbitwidth) e '(offset, roffset)
742 => match invert_literal bitwidth, invert_literal offset with
743 | Some bitwidth, Some offset
744 => let rpre_out := Some (int.of_zrange_relaxed r[0 ~> Z.max (2^offset) (2^bitwidth-1)]%zrange) in
745 let shifted := arith_un_arith_expr_of_PHOAS_ident (Z_shiftl offset) rpre_out e in
746 let truncated := arith_bin_arith_expr_of_PHOAS_ident Z_land r (shifted, arith_expr_of_PHOAS_literal_Z (2^bitwidth-1) (Some (int.of_zrange_relaxed r[0~>2^bitwidth - 1]))) in
747 ret truncated
748 | _, None => inr ["Invalid (truncating) left-shift by a non-literal"]%string
749 | None, _ => inr ["Invalid left-shift truncated to a non-literal bitwidth"]%string
750 end
751 | ident.value_barrier
752 => fun r '(x, rx)
753 => match rx with
754 | Some ty
755 => ret (cast_down_if_needed r (Z_value_barrier ty @@@ x, Some ty))
756 | None => inr ["Invalid unknown integer size for value_barrier"]%string
757 end
758 | ident.Z_bneg => fun r x => ret (arith_un_arith_expr_of_PHOAS_ident Z_bneg r x)
759 | ident.Z_land => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_land r (x, y))
760 | ident.Z_lor => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_lor r (x, y))
761 | ident.Z_lxor => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_lxor r (x, y))
762 | ident.Z_add => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_add r (x, y))
763 | ident.Z_mul => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_mul r (x, y))
764 | ident.Z_sub => fun r x y => ret (arith_bin_arith_expr_of_PHOAS_ident Z_sub r (x, y))
765 | ident.Z_lnot_modulo
766 => fun rout '(e, r) '(modulus, _)
767 => match invert_literal modulus with
768 | Some modulus
769 => match maybe_loglog2 modulus with
770 | Some lgbitwidth
771 => let ty := int.unsigned lgbitwidth in
772 let rin' := Some ty in
773 let '(e, _) := Zcast (always:=false) rin' (e, r) in
774 ret (cast_down_if_needed rout (cast_up_if_needed rout (Z_lnot ty @@@ e, rin')))
775 | None => inr ["Invalid modulus for Z.lnot (not 2^(2^_)): " ++ show modulus]%string
776 end
777 | None => inr ["Invalid non-literal modulus for Z.lnot"]%string
778 end
779 | ident.pair A B
780 => fun _ _ _ => inr ["Invalid identifier in arithmetic expression " ++ show idc]%string
781 | ident.Z_opp (* we pretend this is [0 - _] *)
782 => fun r x =>
783 let zero := (literal 0 @@@ TT, Some (int.of_zrange_relaxed (relax_zrange r[0~>0]))) in
784 ret (arith_bin_arith_expr_of_PHOAS_ident Z_sub r (zero, x))
785 | ident.Literal _ v
786 => fun _ => ret v
787 | ident.comment _
788 | ident.comment_no_keep _
789 | ident.Nat_succ
790 | ident.Nat_pred
791 | ident.Nat_max
792 | ident.Nat_mul
793 | ident.Nat_add
794 | ident.Nat_sub
795 | ident.Nat_eqb
796 | ident.Pos_add
797 | ident.Pos_mul
798 | ident.prod_rect _ _ _
799 | ident.bool_rect _
800 | ident.bool_rect_nodep _
801 | ident.nat_rect _
802 | ident.eager_nat_rect _
803 | ident.nat_rect_arrow _ _
804 | ident.eager_nat_rect_arrow _ _
805 | ident.Some _
806 | ident.None _
807 | ident.option_rect _ _
808 | ident.list_rect _ _
809 | ident.eager_list_rect _ _
810 | ident.list_rect_arrow _ _ _
811 | ident.eager_list_rect_arrow _ _ _
812 | ident.nat_rect_fbb_b _ _ _
813 | ident.nat_rect_fbb_b_b _ _ _ _
814 | ident.list_rect_fbb_b _ _ _ _
815 | ident.list_rect_fbb_b_b _ _ _ _ _
816 | ident.list_rect_fbb_b_b_b _ _ _ _ _ _
817 | ident.list_rect_fbb_b_b_b_b _ _ _ _ _ _ _
818 | ident.list_rect_fbb_b_b_b_b_b _ _ _ _ _ _ _ _
819 | ident.list_case _ _
820 | ident.List_length _
821 | ident.List_seq
822 | ident.List_repeat _
823 | ident.List_firstn _
824 | ident.List_skipn _
825 | ident.List_combine _ _
826 | ident.List_map _ _
827 | ident.List_app _
828 | ident.List_rev _
829 | ident.List_flat_map _ _
830 | ident.List_partition _
831 | ident.List_filter _
832 | ident.List_fold_right _ _
833 | ident.List_update_nth _
834 | ident.List_nth_default _
835 | ident.eager_List_nth_default _
836 | ident.Z_pow
837 | ident.Z_div
838 | ident.Z_modulo
839 | ident.Z_eqb
840 | ident.Z_leb
841 | ident.Z_ltb
842 | ident.Z_geb
843 | ident.Z_gtb
844 | ident.Z_min
845 | ident.Z_max
846 | ident.Z_abs
847 | ident.Z_log2
848 | ident.Z_log2_up
849 | ident.Z_of_nat
850 | ident.Z_to_nat
851 | ident.Z_pos
852 | ident.Z_to_pos
853 | ident.Z_ltz
854 | ident.Z_zselect
855 | ident.Z_mul_split
856 | ident.Z_mul_high
857 | ident.Z_add_get_carry
858 | ident.Z_add_with_carry
859 | ident.Z_add_with_get_carry
860 | ident.Z_sub_get_borrow
861 | ident.Z_sub_with_get_borrow
862 | ident.Z_add_modulo
863 | ident.Z_rshi
864 | ident.Z_cc_m
865 | ident.Z_combine_at_bitwidth
866 | ident.Z_cast
867 | ident.Z_cast2
868 | ident.Build_zrange
869 | ident.zrange_rect _
870 | ident.fancy_add
871 | ident.fancy_addc
872 | ident.fancy_sub
873 | ident.fancy_subb
874 | ident.fancy_mulll
875 | ident.fancy_mullh
876 | ident.fancy_mulhl
877 | ident.fancy_mulhh
878 | ident.fancy_rshi
879 | ident.fancy_selc
880 | ident.fancy_selm
881 | ident.fancy_sell
882 | ident.fancy_addm
883 => fun _ => type.interpM_return _ _ _ (inr ["Invalid identifier in arithmetic expression " ++ show idc]%string)
884 end%core%Cexpr%option%zrange.
885
886 Fixpoint collect_args_and_apply_unknown_casts {t}
887 : (int.option.interp (type.final_codomain t) -> type.interpM_final (fun T => ErrT T) arith_expr_for_base t)
888 -> type.interpM_final
889 (fun T => ErrT T)
890 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
891 t
892 := match t
893 return ((int.option.interp (type.final_codomain t) -> type.interpM_final (fun T => ErrT T) arith_expr_for_base t)
894 -> type.interpM_final
895 (fun T => ErrT T)
896 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
897 t)
898 with
899 | type.base t => fun v => ret v
900 | type.arrow (type.base s) d
901 => fun f
902 (x : (int.option.interp s -> ErrT (arith_expr_for_base s)))
903 => match x int.option.None return _ with
904 | inl x'
905 => @collect_args_and_apply_unknown_casts
906 d
907 (fun rout => f rout x')
908 | inr errs => type.interpM_return _ _ _ (inr errs)
909 end
910 | type.arrow (type.arrow _ _) _
911 => fun _ => type.interpM_return _ _ _ (inr ["Invalid higher-order function"])
912 end.
913
914 Definition collect_args_and_apply_known_casts {t}
915 (idc : ident.ident t)
916 : ErrT (type.interpM_final
917 (fun T => ErrT T)
918 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
919 t)
920 := match idc in ident.ident t
921 return ErrT
922 (type.interpM_final
923 (fun T => ErrT T)
924 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
925 t)
926 with
927 | ident.Z_cast
928 => inl
929 (fun r arg
930 => r <- r tt;
931 let r := Some (int.of_zrange_relaxed r) in
932 inl (fun r'
933 => if language_specific_cast_adjustment
934 then
935 arg <- arg r; ret (Zcast_down_if_needed r' arg)
936 else
937 arg <- arg None; ret (Zcast (always:=true) r arg)))
938 | ident.Z_cast2
939 => inl
940 (fun r arg
941 => r <- r (tt, tt);
942 let r := (Some (int.of_zrange_relaxed (fst r)), Some (int.of_zrange_relaxed (snd r))) in
943 inl (fun r'
944 => if language_specific_cast_adjustment
945 then
946 (arg <- arg r; ret (cast_down_if_needed (t:=tZ*tZ) r' arg))
947 else
948 (arg <- arg (None, None); ret (cast (always:=true) (t:=tZ*tZ) r arg))))
949 | ident.pair A B
950 => inl (fun ea eb
951 => inl
952 (fun '(ra, rb)
953 => ea' ,, eb' <- ea ra, eb rb;
954 inl (ea', eb')))
955 | ident.nil _
956 => inl (inl (fun _ => inl nil))
957 | ident.cons t
958 => inl
959 (fun x xs
960 => inl
961 (fun rls
962 => let mkcons (r : int.option.interp t)
963 (rs : int.option.interp (base.type.list t))
964 := x ,, xs <- x r, xs rs;
965 inl (cons x xs) in
966 match rls with
967 | Some (cons r rs) => mkcons r (Some rs)
968 | Some nil
969 | None
970 => mkcons int.option.None int.option.None
971 end))
972 | _ => inr ["Invalid identifier where cast or constructor was expected: " ++ show idc]%string
973 end.
974
975 Definition collect_args_and_apply_casts {t} (idc : ident.ident t)
976 (convert_no_cast : int.option.interp (type.final_codomain t) -> type.interpM_final (fun T => ErrT T) arith_expr_for_base t)
977 : type.interpM_final
978 (fun T => ErrT T)
979 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
980 t
981 := match collect_args_and_apply_known_casts idc with
982 | inl res => res
983 | inr errs => collect_args_and_apply_unknown_casts convert_no_cast
984 end.
985
986 Fixpoint arith_expr_of_base_PHOAS_Var
987 {t}
988 : base_var_data t -> int.option.interp t -> ErrT (arith_expr_for_base t)
989 := match t with
990 | tZ
991 => fun '(n, is_ptr, r, td) r'
992 => let v := if is_ptr
993 then (Dereference @@@ Var type.Zptr n)%Cexpr
994 else Var type.Z n in
995 ret (cast_down_if_needed r' (v, r))
996 | base.type.prod A B
997 => fun '(da, db) '(ra, rb)
998 => (ea,, eb <- @arith_expr_of_base_PHOAS_Var A da ra, @arith_expr_of_base_PHOAS_Var B db rb;
999 inl (ea, eb))
1000 | base.type.list tZ
1001 => fun '(n, r, len, td) r'
1002 => ret (List.map
1003 (fun i => (List_nth i @@@ Var type.Zptr n, r))%core%Cexpr
1004 (List.seq 0 len))
1005 | base.type.list _
1006 | base.type.option _
1007 | base.type.type_base _
1008 | base.type.unit
1009 => fun _ _ => inr ["Invalid type " ++ show t]%string
1010 end.
1011
1012 Fixpoint arith_expr_of_PHOAS
1013 {t}
1014 (e : @API.expr var_data t)
1015 : type.interpM_final
1016 (fun T => ErrT T)
1017 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
1018 t
1019 := match e in expr.expr t
1020 return type.interpM_final
1021 (fun T => ErrT T)
1022 (fun t => int.option.interp t -> ErrT (arith_expr_for_base t))
1023 t
1024 with
1025 | expr.Var (type.base _) v
1026 => ret (arith_expr_of_base_PHOAS_Var v)
1027 | expr.Ident t idc
1028 => collect_args_and_apply_casts idc (arith_expr_of_PHOAS_ident idc)
1029 | expr.App (type.base s) d f x
1030 => let x' := @arith_expr_of_PHOAS (type.base s) x in
1031 match x' with
1032 | inl x' => @arith_expr_of_PHOAS _ f x'
1033 | inr errs => type.interpM_return _ _ _ (inr errs)
1034 end
1035 | expr.Var (type.arrow _ _) _
1036 => type.interpM_return _ _ _ (inr ["Invalid non-arithmetic let-bound Var of type " ++ show t]%string)
1037 | expr.App (type.arrow _ _) _ _ _
1038 => type.interpM_return _ _ _ (inr ["Invalid non-arithmetic let-bound App of type " ++ show t]%string)
1039 | expr.LetIn _ _ _ _
1040 => type.interpM_return _ _ _ (inr ["Invalid non-arithmetic let-bound LetIn of type " ++ show t]%string)
1041 | expr.Abs _ _ _
1042 => type.interpM_return _ _ _ (inr ["Invalid non-arithmetic let-bound Abs of type: " ++ show t]%string)
1043 end.
1044
1045 Definition arith_expr_of_base_PHOAS
1046 {t:base.type}
1047 (e : @API.expr var_data (type.base t))
1048 (rout : int.option.interp t)
1049 : ErrT (arith_expr_for_base t)
1050 := (e' <- arith_expr_of_PHOAS e; e' rout).
1051
1052 Definition result_upcast {t}
1053 : int.option.interp t -> arith_expr_for_base t -> arith_expr_for_base t
1054 := if upcast_on_assignment
1055 then cast (always:=false)
1056 else fun _ e => e.
1057
1058 Definition funcall_upcast {t}
1059 : int.option.interp t -> arith_expr_for_base t -> arith_expr_for_base t
1060 := if upcast_on_funcall
1061 then cast (always:=false)
1062 else fun _ e => e.
1063
1064 Fixpoint make_return_assignment_of_base_arith {t}
1065 : base_var_data t
1066 -> @API.expr var_data (type.base t)
1067 -> ErrT expr
1068 := match t return base_var_data t -> expr.expr (type.base t) -> ErrT expr with
1069 | tZ
1070 => fun '(n, is_ptr, r, td) e
1071 => (rhs <- arith_expr_of_base_PHOAS e r;
1072 let '(e, r) := result_upcast (t:=tZ) r rhs in
1073 ret (if is_ptr
1074 then [AssignZPtr n r e]
1075 else [Assign false type.Z r n e]))
1076 | base.type.type_base _
1077 | base.type.unit
1078 => fun _ _ => inr ["Invalid type " ++ show t]%string
1079 | base.type.prod A B
1080 => fun '(rva, rvb) e
1081 => match invert_pair e with
1082 | Some (ea, eb)
1083 => ea',, eb' <- @make_return_assignment_of_base_arith A rva ea, @make_return_assignment_of_base_arith B rvb eb;
1084 ret (ea' ++ eb')
1085 | None => inr ["Invalid non-pair expr of type " ++ show t]%string
1086 end
1087 | base.type.list tZ
1088 => fun '(n, r, len, td) e
1089 => (ls <- arith_expr_of_base_PHOAS e (Some (repeat r len));
1090 ret (List.map
1091 (fun '(i, rhs) =>
1092 let '(e, _) := result_upcast (t:=tZ) r rhs in
1093 AssignNth n i e)
1094 (List.combine (List.seq 0 len) ls)))
1095 | base.type.list _
1096 | base.type.option _
1097 => fun _ _ => inr ["Invalid type of expr: " ++ show t]%string
1098 end%list.
1099 Definition make_return_assignment_of_arith {t}
1100 : var_data t
1101 -> @API.expr var_data t
1102 -> ErrT expr
1103 := match t with
1104 | type.base t => make_return_assignment_of_base_arith
1105 | type.arrow s d => fun _ _ => inr ["Invalid type of expr: " ++ show t]%string
1106 end.
1107
1108 Definition report_type_mismatch (expected : API.type) (given : API.type) : string
1109 := ("Type mismatch; expected " ++ show expected ++ " but given " ++ show given ++ ".")%string.
1110
1111 Fixpoint arith_expr_of_PHOAS_args
1112 {t}
1113 : type.for_each_lhs_of_arrow (@API.expr var_data) t
1114 -> ErrT (type.for_each_lhs_of_arrow (fun t => @API.expr var_data t * (arith_expr type.Z * option int.type)) t)
1115 := match t with
1116 | type.base t => fun 'tt => inl tt
1117 | type.arrow (type.base tZ) d
1118 => fun '(arg, args)
1119 => arg' ,, args' <- arith_expr_of_base_PHOAS arg int.option.None , @arith_expr_of_PHOAS_args d args;
1120 inl ((arg, arg'), args')
1121 | type.arrow s d
1122 => fun '(arg, args)
1123 => arg' ,, args' <- @inr unit _ ["Invalid argument of non-ℤ type " ++ show s]%string , @arith_expr_of_PHOAS_args d args;
1124 inr ["Impossible! (type error got lost somewhere)"]
1125 end.
1126
1127 Fixpoint base_var_names_of_string_opt {t} (n : string) : option (base_var_names t)
1128 := match t return option (base_var_names t) with
1129 | tZ
1130 | base.type.list _
1131 => Some n
1132 | base.type.prod A B
1133 => (a <- @base_var_names_of_string_opt A (n ++ "₁");
1134 b <- @base_var_names_of_string_opt B (n ++ "₂");
1135 Some (a, b))%option
1136 | base.type.unit => Some tt
1137 | base.type.option _
1138 | base.type.type_base _
1139 => None
1140 end.
1141
1142 Fixpoint string_of_base_var_names {t} : base_var_names t -> string
1143 := match t return base_var_names t -> string with
1144 | tZ
1145 | base.type.list _
1146 => fun n => n
1147 | base.type.prod A B
1148 => fun x : base_var_names A * base_var_names B
1149 => let a := @string_of_base_var_names A (fst x) in
1150 let b := @string_of_base_var_names B (snd x) in
1151 let len_a := String.length a in
1152 let len_b := String.length b in
1153 let '(a, a_tl) := (String.substring 0 (len_a - 1) a, String.substring (len_a - 1) 1 a) in
1154 let '(b, b_tl) := (String.substring 0 (len_b - 1) b, String.substring (len_b - 1) 1 b) in
1155 if ((len_a =? len_b)%nat && (a =? b) && (a_tl =? "₁") && (b_tl =? "₂"))
1156 then a
1157 else "(" ++ a ++ "," ++ b ++ ")"
1158 | base.type.unit => fun 'tt => "()"
1159 | base.type.option _
1160 | base.type.type_base _
1161 => fun absurd : Empty_set => match absurd with end
1162 end%string%bool.
1163
1164 Definition var_names_of_string_opt {t} (n : string) : option (var_names t)
1165 := match t with
1166 | type.base _ => @base_var_names_of_string_opt _ n
1167 | type.arrow _ _ => None
1168 end.
1169
1170 Definition string_of_var_names {t} : var_names t -> string
1171 := match t with
1172 | type.base _ => @string_of_base_var_names _
1173 | type.arrow _ _ => fun absurd : Empty_set => match absurd with end
1174 end.
1175
1176 Definition base_var_data_of_string_opt {t} (n : string) : option (base_var_data t)
1177 := option_map base_var_data_of_names (base_var_names_of_string_opt n).
1178 Definition var_data_of_string_opt {t} (n : string) : option (var_data t)
1179 := option_map var_data_of_names (var_names_of_string_opt n).
1180
1181 Definition string_of_base_var_data {t} (v : base_var_data t) : string
1182 := string_of_base_var_names (names_of_base_var_data v).
1183 Definition string_of_var_data {t} (v : var_data t) : string
1184 := string_of_var_names (names_of_var_data v).
1185
1186 Fixpoint extract_var_data_list {t} (e : @API.expr var_data t) : list { t : _ & var_data t }
1187 := match e with
1188 | expr.Ident t idc => []
1189 | expr.Var t v => [existT _ _ v]
1190 | expr.Abs s d f
1191 => match var_data_of_string_opt "(FAKE_extract_var_data_list)" with
1192 | Some d => extract_var_data_list (f d)
1193 | None => []
1194 end
1195 | expr.App s d f x
1196 => extract_var_data_list f ++ extract_var_data_list x
1197 | expr.LetIn A B x f
1198 => (extract_var_data_list x)
1199 ++ match var_data_of_string_opt "(FAKE_extract_var_data_list)" with
1200 | Some d => extract_var_data_list (f d)
1201 | None => []
1202 end
1203 end.
1204
1205 Let make_comment
1206 {t}
1207 (e : @API.expr var_data t)
1208 : ErrT (expr * var_data t)
1209 := let _ := @PHOAS.expr.partially_show_expr in
1210 let ret_err := inr ["Not a comment " ++ show e]%string in
1211 match invert_AppIdent e, var_data_of_string_opt "()" with
1212 | Some (existT t (idc, arg)), Some retdata
1213 => let should_keep_live := match idc return option bool with
1214 | ident.comment _ => Some true
1215 | ident.comment_no_keep _ => Some false
1216 | _ => None
1217 end in
1218 match should_keep_live with
1219 | Some should_keep_live
1220 => inl ([Comment
1221 (PHOAS.expr.show_lines_expr_gen (@string_of_var_data) (@var_data_of_string_opt) arg) (* comment lines *)
1222 (if should_keep_live then extract_var_data_list arg else []) (* live variables *)],
1223 retdata)
1224 | None => ret_err
1225 end
1226 | None, _ | _, None => ret_err
1227 end.
1228
1229 Definition bounds_check (do_bounds_check : bool) (descr : string) {t} (idc : ident.ident t) (s : BinInt.Z) {t'} (ev : @API.expr var_data t') (found : option int.type)
1230 : ErrT unit
1231 := if negb do_bounds_check
1232 then ret tt
1233 else
1234 let _ := @PHOAS.expr.partially_show_expr in
1235 match found with
1236 | None => inr ["Missing range on " ++ descr ++ " " ++ show idc ++ ": " ++ show ev]%string
1237 | Some ty
1238 => if int.is_tighter_than ty (int.of_zrange_relaxed (relax_zrange r[0~>2^s-1]))
1239 then ret tt
1240 else inr ["Final bounds check failed on " ++ descr ++ " " ++ show idc ++ "; expected an unsigned " ++ Decimal.Z.to_string s ++ "-bit number (relaxed to " ++ show (int.of_zrange_relaxed (relax_zrange r[0~>2^s-1])) ++ "), but found a " ++ show ty ++ "."]%string
1241 end.
1242
1243 Let recognize_1ref_ident
1244 (do_bounds_check : bool)
1245 {t}
1246 (idc : ident.ident t)
1247 : option (forall (rout : option int.type),
1248 type.for_each_lhs_of_arrow (fun t => @API.expr var_data t * (arith_expr type.Z * option int.type))%type t
1249 -> ErrT (arith_expr type.Zptr -> expr))
1250 := let _ := @PHOAS.expr.partially_show_expr in
1251 match idc in ident.ident t
1252 return option (forall (rout : option int.type),
1253 type.for_each_lhs_of_arrow (fun t => @API.expr var_data t * (arith_expr type.Z * option int.type))%type t
1254 -> ErrT (arith_expr type.Zptr -> expr))
1255 with
1256 | ident.Z_zselect
1257 => Some
1258 (fun rout '((econdv, (econd, rcond)), ((e1v, (e1, r1)), ((e2v, (e2, r2)), tt)))
1259 => (*let err := inr ["Invalid argument to Z.zselect not known to be 0 or 1: " ++ show econdv]%string in*)
1260 _ <- bounds_check do_bounds_check "first argument to" idc 1 econdv rcond;
1261 let '((e1, r1), (e2, r2)) :=
1262 funcall_upcast (t:=tZ*tZ) (rout, rout) ((e1, r1), (e2, r2)) in
1263 ty <- match rout with
1264 | Some rout
1265 => inl rout
1266 | None => inr ["Missing cast annotation on return of Z.zselect"]
1267 end;
1268 ret (fun retptr => [Call (Z_zselect ty @@@ (retptr, (econd, e1, e2)))]%Cexpr))
1269 | _ => None (* fun _ => inr ["Unrecognized identifier (expecting a 1-pointer-returning function): " ++ show idc]%string *)
1270 end.
1271
1272 Let round_up_to_split_type (lgs : Z) (t : option int.type) : option int.type
1273 := option_map (int.union (int.of_zrange_relaxed (relax_zrange r[0~>2^lgs-1]))) t.
1274
1275 Let check_literal_rangeZ (r : option zrange) (v : Z) (nth : string) {t'} (idc : ident.ident t') : ErrT unit
1276 := match r with
1277 | None => inl tt
1278 | Some r
1279 => if ZRange.type.is_bounded_by (t:=tZ) r v
1280 then inl tt
1281 else inr ["Literal value " ++ show v ++ " is not within the casted range " ++ show r ++ " (when trying to parse the " ++ nth ++ " argument of " ++ show idc ++ ")"]%string
1282 end.
1283
1284 Let recognize_3arg_2ref_ident
1285 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1286 (do_bounds_check : bool)
1287 (t:=(tZ -> tZ -> tZ -> tZ * tZ)%etype)
1288 (idc : ident.ident t)
1289 (rout : option int.type * option int.type)
1290 (args : type.for_each_lhs_of_arrow (fun t => @API.expr var_data t *
1291 (arith_expr type.Z * option int.type))%type t)
1292 : ErrT ((option int.type * option int.type) * (arith_expr (type.Zptr * type.Zptr) -> expr))
1293 := let _ := @PHOAS.expr.partially_show_expr in
1294 let '((s, _), ((e1v, (e1, r1)), ((e2v, (e2, r2)), tt))) := args in
1295 match (rs <- invert_Literal_through_cast s; lg2s <- maybe_log2 (snd rs); Some (fst rs, lg2s))%option, idc return ErrT ((option int.type * option int.type) * (arith_expr (type.Zptr * type.Zptr) -> expr))
1296 with
1297 | Some (r, s), ident.Z_mul_split
1298 => (_ <- check_literal_rangeZ r (2^s) "first" idc;
1299 _ ,, _ ,, _ ,, _
1300 <- bounds_check do_bounds_check "first argument to" idc s e1v r1,
1301 bounds_check do_bounds_check "second argument to" idc s e2v r2,
1302 bounds_check do_bounds_check "first return value of" idc s e2v (fst rout),
1303 bounds_check do_bounds_check "second return value of" idc s e2v (snd rout);
1304 inl ((round_up_to_split_type s (fst rout), round_up_to_split_type s (snd rout)),
1305 fun retptr => [Call (Z_mul_split s @@@ (retptr, (e1, e2)))%Cexpr]))
1306 | Some (r, s), ident.Z_add_get_carry as idc
1307 | Some (r, s), ident.Z_sub_get_borrow as idc
1308 => let idc' : ident _ _ := Option.invert_Some
1309 match idc with
1310 | ident.Z_add_get_carry => Some (Z_add_with_get_carry s)
1311 | ident.Z_sub_get_borrow => Some (Z_sub_with_get_borrow s)
1312 | _ => None
1313 end in
1314 (_ <- check_literal_rangeZ r (2^s) "first" idc;
1315 let '(return_carry_borrow_width, round_up_return_carry)
1316 := if List.existsb (Z.eqb s) relax_adc_sbb_return_carry_to_bitwidth
1317 then (s, round_up_to_split_type s)
1318 else (1 (* boolean carry/borrow *), fun x => x) in
1319 _ ,, _ ,, _ ,, _
1320 <- bounds_check do_bounds_check "first argument to" idc s e1v r1,
1321 bounds_check do_bounds_check "second argument to" idc s e2v r2,
1322 bounds_check do_bounds_check "first return value of" idc s e2v (fst rout),
1323 bounds_check do_bounds_check "second return value of" idc return_carry_borrow_width e2v (snd rout);
1324 let '(e1, _) := result_upcast (t:=tZ) (Some (int.of_zrange_relaxed r[0 ~> 2 ^ s - 1])) (e1, r1) in
1325 let '(e2, _) := result_upcast (t:=tZ) (Some (int.of_zrange_relaxed r[0 ~> 2 ^ s - 1])) (e2, r2) in
1326 inl ((round_up_to_split_type s (fst rout), round_up_return_carry (snd rout)),
1327 fun retptr => [Call (idc' @@@ (retptr, (literal 0 @@@ TT, e1, e2)))%Cexpr]))
1328 | Some _, _ => inr ["Unrecognized identifier when attempting to construct an assignment with 2 arguments: " ++ show idc]%string
1329 | None, _ => inr ["Expression is not a literal power of two of type ℤ: " ++ show s ++ " (when trying to parse the first argument of " ++ show idc ++ ")"]%string
1330 end.
1331
1332 Let recognize_4arg_2ref_ident
1333 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1334 (do_bounds_check : bool)
1335 (t:=(tZ -> tZ -> tZ -> tZ -> tZ * tZ)%etype)
1336 (idc : ident.ident t)
1337 (rout : option int.type * option int.type)
1338 (args : type.for_each_lhs_of_arrow (fun t => @API.expr var_data t * (arith_expr type.Z * option int.type))%type t)
1339 : ErrT ((option int.type * option int.type) * (arith_expr (type.Zptr * type.Zptr) -> expr))
1340 := let _ := @PHOAS.expr.partially_show_expr in
1341 let '((s, _), ((e1v, (e1, r1)), ((e2v, (e2, r2)), ((e3v, (e3, r3)), tt)))) := args in
1342 match (rs <- invert_Literal_through_cast s; lg2s <- maybe_log2 (snd rs); Some (fst rs, lg2s))%option, idc return ErrT ((option int.type * option int.type) * (arith_expr (type.Zptr * type.Zptr) -> expr))
1343 with
1344 | Some (r, s), ident.Z_add_with_get_carry as idc
1345 | Some (r, s), ident.Z_sub_with_get_borrow as idc
1346 => let idc' : ident _ _ := Option.invert_Some
1347 match idc with
1348 | ident.Z_add_with_get_carry => Some (Z_add_with_get_carry s)
1349 | ident.Z_sub_with_get_borrow => Some (Z_sub_with_get_borrow s)
1350 | _ => None
1351 end in
1352 (_ <- check_literal_rangeZ r (2^s) "first" idc;
1353 let '(return_carry_borrow_width, round_up_return_carry)
1354 := if List.existsb (Z.eqb s) relax_adc_sbb_return_carry_to_bitwidth
1355 then (s, round_up_to_split_type s)
1356 else (1 (* boolean carry/borrow *), fun x => x) in
1357 _ ,, _ ,, _ ,, _ ,, _
1358 <- (bounds_check do_bounds_check "first (carry) argument to" idc 1 e1v r1,
1359 bounds_check do_bounds_check "second argument to" idc s e2v r2,
1360 bounds_check do_bounds_check "third argument to" idc s e2v r2,
1361 bounds_check do_bounds_check "first return value of" idc s e2v (fst rout),
1362 bounds_check do_bounds_check "second (carry) return value of" idc return_carry_borrow_width e2v (snd rout));
1363 let '(e1, _) := result_upcast (t:=tZ) (Some (int.of_zrange_relaxed (relax_zrange r[0 ~> 2 ^ 1 - 1]))) (e1, r1) in
1364 let '(e2, _) := result_upcast (t:=tZ) (Some (int.of_zrange_relaxed (relax_zrange r[0 ~> 2 ^ s - 1]))) (e2, r2) in
1365 let '(e3, _) := result_upcast (t:=tZ) (Some (int.of_zrange_relaxed (relax_zrange r[0 ~> 2 ^ s - 1]))) (e3, r3) in
1366 inl ((round_up_to_split_type s (fst rout), round_up_return_carry (snd rout)),
1367 fun retptr => [Call (idc' @@@ (retptr, (e1, e2, e3)))%Cexpr]))
1368 | Some _, _ => inr ["Unrecognized identifier when attempting to construct an assignment with 2 arguments: " ++ show idc]%string
1369 | None, _ => inr ["Expression is not a literal power of two of type ℤ: " ++ show s ++ " (when trying to parse the first argument of " ++ show idc ++ ")"]%string
1370 end.
1371
1372 Let recognize_2ref_ident
1373 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1374 {t}
1375 : forall (do_bounds_check : bool)
1376 (idc : ident.ident t)
1377 (rout : option int.type * option int.type)
1378 (args : type.for_each_lhs_of_arrow (fun t => @API.expr var_data t * (arith_expr type.Z * option int.type))%type t),
1379 ErrT ((option int.type * option int.type) * (arith_expr (type.Zptr * type.Zptr) -> expr))
1380 := match t with
1381 | (type.base tZ -> type.base tZ -> type.base tZ -> type.base (tZ * tZ))%etype
1382 => recognize_3arg_2ref_ident
1383 | (type.base tZ -> type.base tZ -> type.base tZ -> type.base tZ -> type.base (tZ * tZ))%etype
1384 => recognize_4arg_2ref_ident
1385 | _ => fun do_bounds_check idc rout args => inr ["Unrecognized type for function call: " ++ show t ++ " (when trying to handle the identifer " ++ show idc ++ ")"]%string
1386 end.
1387
1388 Definition declare_name
1389 (descr : string)
1390 (count : positive)
1391 (make_name : positive -> option string)
1392 (r : option int.type)
1393 : ErrT (expr * string * bool (* is pointer *) * arith_expr type.Zptr)
1394 := (n ,, r <- (match make_name count with
1395 | Some n => ret n
1396 | None => inr ["Variable naming-function does not support the index " ++ show count]%string
1397 end,
1398 match r with
1399 | Some r => ret r
1400 | None => inr ["Missing return type annotation for " ++ descr]%string
1401 end);
1402 ret (if explicit_pointer_variables
1403 then ([DeclareVar type.Zptr (Some r) n], n, true, (Var type.Zptr n)%Cexpr)
1404 else ([DeclareVar type.Z (Some r) n], n, false, (Addr @@@ Var type.Z n)%Cexpr))).
1405
1406 Let make_assign_arg_1ref_opt
1407 (do_bounds_check : bool)
1408 (e : @API.expr var_data tZ)
1409 (count : positive)
1410 (make_name : positive -> option string)
1411 : ErrT (expr * var_data tZ)
1412 := let _ := @PHOAS.expr.partially_show_expr in
1413 let e1 := e in
1414 let '(rout, e) := match invert_App_Z_cast e with
1415 | Some (r, e) => (Some (int.of_zrange_relaxed r), e)
1416 | None => (None, e)
1417 end%core in
1418 let res_ref
1419 := (idc_args <- invert_AppIdent_curried e;
1420 let '(existT _ (idc, args)) := idc_args in
1421 recognize <- recognize_1ref_ident do_bounds_check idc;
1422 Some
1423 (args <- arith_expr_of_PHOAS_args args;
1424 idce <- recognize rout args;
1425 v <- declare_name (show idc) count make_name rout;
1426 let '(decls, n, is_ptr, retv) := v in
1427 ret ((decls ++ (idce retv))%list, (n, is_ptr, rout, None)))%err)%option in
1428 match res_ref with
1429 | Some (inl res) => ret res
1430 | Some (inr err) => inr err
1431 | None
1432 => e1 <- arith_expr_of_base_PHOAS e1 None;
1433 let '(e1, r1) := e1 in
1434 match make_name count with
1435 | Some n1
1436 => ret ([Assign true type.Z r1 n1 e1], (n1, false, r1, None))
1437 | None => inr ["Variable naming-function does not support the index " ++ show count]%string
1438 end
1439 end.
1440
1441 Let make_assign_arg_2ref
1442 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1443 (do_bounds_check : bool)
1444 (e : @API.expr var_data (tZ * tZ))
1445 (count : positive)
1446 (make_name : positive -> option string)
1447 : ErrT (expr * var_data (tZ * tZ))
1448 := let _ := @PHOAS.expr.partially_show_expr in
1449 let '((rout1, rout2), e)
1450 := match invert_App_Z_cast2 e with
1451 | Some ((r1, r2), e) => ((Some (int.of_zrange_relaxed r1), Some (int.of_zrange_relaxed r2)), e)
1452 | None => ((None, None), e)
1453 end%core in
1454 match invert_AppIdent_curried e with
1455 | Some (existT t (idc, args))
1456 => args <- arith_expr_of_PHOAS_args args;
1457 idce <- recognize_2ref_ident do_bounds_check idc (rout1, rout2) args;
1458 let '((rout1, rout2), idce) := idce in
1459 v1,, v2 <- (declare_name (show idc) count make_name rout1,
1460 declare_name (show idc) (Pos.succ count) make_name rout2);
1461 let '(decls1, n1, is_ptr1, retv1) := v1 in
1462 let '(decls2, n2, is_ptr2, retv2) := v2 in
1463 ret (decls1 ++ decls2 ++ (idce (retv1, retv2)%Cexpr), ((n1, is_ptr1, rout1, None), (n2, is_ptr2, rout2, None)))%list
1464 | None => inr ["Invalid assignment of non-identifier-application: " ++ show e]%string
1465 end.
1466
1467 Let make_assign_arg_ref
1468 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1469 (do_bounds_check : bool)
1470 {t}
1471 : forall (e : @API.expr var_data t)
1472 (count : positive)
1473 (make_name : positive -> option string),
1474 ErrT (expr * var_data t)
1475 := let _ := @PHOAS.expr.partially_show_expr in
1476 match t with
1477 | type.base tZ => make_assign_arg_1ref_opt do_bounds_check
1478 | type.base (tZ * tZ)%etype => make_assign_arg_2ref do_bounds_check
1479 | type.base base.type.unit => fun e _ _ => make_comment e
1480 | _ => fun e _ _ => inr ["Invalid type of assignment expression: " ++ show t ++ " (with expression " ++ show e ++ ")"]
1481 end.
1482
1483 Fixpoint size_of_type (t : base.type) : positive
1484 := match t with
1485 | base.type.type_base _
1486 | base.type.unit
1487 => 1
1488 | base.type.prod A B => size_of_type A + size_of_type B
1489 | base.type.list A => 1
1490 | base.type.option A => 1
1491 end%positive.
1492
1493 Let make_uniform_assign_expr_of_PHOAS
1494 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1495 (do_bounds_check : bool)
1496 {s} (e1 : @API.expr var_data s)
1497 {d} (e2 : var_data s -> var_data d -> ErrT expr)
1498 (count : positive)
1499 (make_name : positive -> option string)
1500 (vd : var_data d)
1501 : ErrT expr
1502 := let _ := @PHOAS.expr.partially_show_expr in (* for TC resolution *)
1503 e1_vs <- make_assign_arg_ref do_bounds_check e1 count make_name;
1504 let '(e1, vs) := e1_vs in
1505 e2 <- e2 vs vd;
1506 ret (e1 ++ e2)%list.
1507
1508 (* See above comment about extraction issues *)
1509 Definition make_assign_expr_of_PHOAS
1510 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1511 (do_bounds_check : bool)
1512 {s} (e1 : @API.expr var_data s)
1513 {s' d} (e2 : var_data s' -> var_data d -> ErrT expr)
1514 (count : positive)
1515 (make_name : positive -> option string)
1516 (v : var_data d)
1517 : ErrT expr
1518 := Eval cbv beta iota delta [bind2_err bind3_err bind4_err bind5_err recognize_1ref_ident recognize_3arg_2ref_ident recognize_4arg_2ref_ident recognize_2ref_ident make_assign_arg_1ref_opt make_assign_arg_2ref make_assign_arg_ref make_uniform_assign_expr_of_PHOAS make_uniform_assign_expr_of_PHOAS round_up_to_split_type make_comment check_literal_rangeZ] in
1519 match type.try_transport _ _ s' e1 with
1520 | Some e1 => make_uniform_assign_expr_of_PHOAS do_bounds_check e1 e2 count make_name v
1521 | None => inr [report_type_mismatch s' s]
1522 end.
1523
1524 Fixpoint expr_of_base_PHOAS
1525 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1526 (do_bounds_check : bool)
1527 {t}
1528 (e : @API.expr var_data t)
1529 (count : positive)
1530 (make_name : positive -> option string)
1531 {struct e}
1532 : forall (ret_val : var_data t), ErrT expr
1533 := match e in expr.expr t return var_data t -> ErrT expr with
1534 | expr.LetIn (type.base s) d e1 e2
1535 => make_assign_expr_of_PHOAS
1536 do_bounds_check
1537 e1
1538 (fun vs vd => expr_of_base_PHOAS do_bounds_check (t:=d) (e2 vs) (size_of_type s + count)%positive make_name vd)
1539 count make_name
1540 | expr.LetIn (type.arrow _ _) _ _ _ as e
1541 | expr.Var _ _ as e
1542 | expr.Ident _ _ as e
1543 | expr.App _ _ _ _ as e
1544 | expr.Abs _ _ _ as e
1545 => fun v => make_return_assignment_of_arith v e
1546 end%expr_pat%option.
1547
1548 Fixpoint base_var_data_of_bounds_and_typedefs {t}
1549 (is_ptr : bool)
1550 (count : positive)
1551 (make_name : positive -> option string)
1552 {struct t}
1553 : ZRange.type.base.option.interp t -> base_var_typedef_data t -> option (positive * var_data (type.base t))
1554 := match t return ZRange.type.base.option.interp t -> base_var_typedef_data t -> option (positive * var_data (type.base t)) with
1555 | tZ as t
1556 => fun r typedefs
1557 => (n <- make_name count;
1558 Some (Pos.succ count, (n, is_ptr, int.option.interp.of_zrange_relaxed (t:=t) (option_map relax_zrange r), typedefs)))
1559 | base.type.prod A B
1560 => fun '(ra, rb) '(typedefsa, typedefsb)
1561 => (va <- @base_var_data_of_bounds_and_typedefs A is_ptr count make_name ra typedefsa;
1562 let '(count, va) := va in
1563 vb <- @base_var_data_of_bounds_and_typedefs B is_ptr count make_name rb typedefsb;
1564 let '(count, vb) := vb in
1565 Some (count, (va, vb)))
1566 | base.type.list tZ as t
1567 => fun r typedefs
1568 => (ls <- r;
1569 n <- make_name count;
1570 Some (Pos.succ count,
1571 (n,
1572 int.option.interp.to_union
1573 (int.option.interp.of_zrange_relaxed
1574 (t:=t) (Some (List.map (option_map relax_zrange) ls))),
1575 length ls,
1576 typedefs)))
1577 | base.type.unit
1578 => fun _ _ => Some (count, tt)
1579 | base.type.list _
1580 | base.type.option _
1581 | base.type.type_base _
1582 => fun _ _ => None
1583 end%option.
1584
1585 Definition var_data_of_bounds_and_typedefs {t}
1586 (is_ptr : bool)
1587 (count : positive)
1588 (make_name : positive -> option string)
1589 : ZRange.type.option.interp t -> var_typedef_data t -> option (positive * var_data t)
1590 := match t with
1591 | type.base t => base_var_data_of_bounds_and_typedefs is_ptr count make_name
1592 | type.arrow s d => fun _ _ => None
1593 end.
1594
1595 Fixpoint expr_of_PHOAS'_cps
1596 {t}
1597 (e : @API.expr var_data t)
1598 (make_in_name : positive -> option string)
1599 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1600 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1601 (count : positive)
1602 {T}
1603 {struct t}
1604 : (positive * (type.for_each_lhs_of_arrow var_data t * @API.expr var_data (type.final_codomain t)) -> ErrT T) -> ErrT T
1605 := let _ := @PHOAS.expr.partially_show_expr in (* for TC resolution *)
1606 match t return @API.expr var_data t -> type.for_each_lhs_of_arrow ZRange.type.option.interp t -> type.for_each_lhs_of_arrow var_typedef_data t -> (positive * (type.for_each_lhs_of_arrow var_data t * @API.expr var_data (type.final_codomain t)) -> ErrT T) -> ErrT T with
1607 | type.base t
1608 => fun e 'tt 'tt k => k (count, (tt, e))
1609 | type.arrow s d
1610 => fun e '(inbound, inbounds) '(intypedef, intypedefs) k
1611 => match var_data_of_bounds_and_typedefs false count make_in_name inbound intypedef, invert_Abs e with
1612 | Some (count, vs), Some f
1613 => @expr_of_PHOAS'_cps
1614 d (f vs) make_in_name inbounds intypedefs count _
1615 (fun '(count, (vss, rv))
1616 => k (count, ((vs, vss), rv)))
1617 | None, _ => inr ["Unable to bind names for all arguments and bounds at type " ++ show s]%string%list
1618 | _, None => inr ["Invalid non-λ expression of arrow type (" ++ show t ++ "): " ++ show e]%string%list
1619 end
1620 end%core%expr e inbounds intypedefs.
1621
1622 Definition expr_of_PHOAS'_cont
1623 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1624 (do_bounds_check : bool)
1625 {t}
1626 (make_name : positive -> option string)
1627 (out_data : var_data (type.base (type.final_codomain t)))
1628 (in_to_body_count : positive -> positive)
1629 : positive * (type.for_each_lhs_of_arrow var_data t * @API.expr var_data (type.final_codomain t))
1630 -> ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * expr)
1631 := let _ := @PHOAS.expr.partially_show_expr in (* for TC resolution *)
1632 fun '(count, (d, e))
1633 => (rv <- expr_of_base_PHOAS do_bounds_check e (in_to_body_count count) make_name out_data;
1634 let rv := name_infos.adjust_dead consider_retargs_live rename_dead rv in
1635 let rv := if lift_declarations then LiftDeclare.lift_declarations rv else rv in
1636 ret (d, out_data, rv)).
1637
1638 Definition expr_of_PHOAS'
1639 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1640 (do_bounds_check : bool)
1641 {t}
1642 (e : @API.expr var_data t)
1643 (make_in_name : positive -> option string)
1644 (make_name : positive -> option string)
1645 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1646 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1647 (out_data : var_data (type.base (type.final_codomain t)))
1648 (count : positive)
1649 (in_to_body_count : positive -> positive)
1650 : ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * expr)
1651 := @expr_of_PHOAS'_cps
1652 _ e make_in_name inbounds intypedefs count _
1653 (expr_of_PHOAS'_cont do_bounds_check (t:=t) make_name out_data in_to_body_count).
1654
1655 Definition expr_of_PHOAS_cont
1656 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1657 (do_bounds_check : bool)
1658 {t}
1659 (make_name : positive -> option string)
1660 (in_to_body_count : positive -> positive)
1661 : positive * (type.for_each_lhs_of_arrow var_data t * var_data (type.final_codomain t) * @API.expr var_data (type.final_codomain t))
1662 -> ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.final_codomain t) * expr)
1663 := fun '(count, (din, dout, e))
1664 => expr_of_PHOAS'_cont do_bounds_check (t:=t) make_name dout in_to_body_count (count, (din, e)).
1665
1666 Definition expr_of_PHOAS_cps
1667 {t}
1668 (e : @API.expr var_data t)
1669 (make_in_name : positive -> option string)
1670 (make_out_name : positive -> option string)
1671 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1672 (outbounds : ZRange.type.option.interp (type.base (type.final_codomain t)))
1673 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1674 (outtypedefs : var_typedef_data (type.base (type.final_codomain t)))
1675 (count : positive)
1676 (out_to_in_count : positive -> positive)
1677 {T}
1678 (k : positive * (type.for_each_lhs_of_arrow var_data t * var_data (type.final_codomain t) * @API.expr var_data (type.final_codomain t)) -> ErrT T)
1679 : ErrT T
1680 := match var_data_of_bounds_and_typedefs true count make_out_name outbounds outtypedefs with
1681 | Some vd
1682 => let '(count, dout) := vd in
1683 let count := out_to_in_count count in
1684 @expr_of_PHOAS'_cps
1685 t e make_in_name inbounds intypedefs count _
1686 (fun '(count, (din, e)) => k (count, (din, dout, e)))
1687 | None => inr ["Unable to bind names for all return arguments and bounds at type " ++ show (type.final_codomain t)]%string
1688 end.
1689
1690 Definition expr_of_PHOAS
1691 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1692 (do_bounds_check : bool)
1693 {t}
1694 (e : @API.expr var_data t)
1695 (make_in_name : positive -> option string)
1696 (make_out_name : positive -> option string)
1697 (make_name : positive -> option string)
1698 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1699 (outbounds : ZRange.type.option.interp (type.base (type.final_codomain t)))
1700 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1701 (outtypedefs : var_typedef_data (type.base (type.final_codomain t)))
1702 (count : positive)
1703 (in_to_body_count out_to_in_count : positive -> positive)
1704 : ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.final_codomain t) * expr)
1705 := @expr_of_PHOAS_cps
1706 _ e make_in_name make_out_name inbounds outbounds intypedefs outtypedefs count out_to_in_count _
1707 (expr_of_PHOAS_cont do_bounds_check (t:=t) make_name in_to_body_count).
1708
1709 Let make_name_gen (name_list : option (list string))
1710 := fun prefix
1711 => match name_list with
1712 | None => fun p => Some (prefix ++ Decimal.Z.to_string (Zpos p))
1713 | Some ls => fun p => List.nth_error ls (pred (Pos.to_nat p))
1714 end.
1715
1716 Let make_in_name name_list := make_name_gen name_list "arg".
1717 Let make_out_name name_list := make_name_gen name_list "out".
1718 Let make_name name_list := make_name_gen name_list "x".
1719 Let reset_if_names_given (name_list : option (list string))
1720 := match name_list with
1721 | Some _ => fun p : positive => p
1722 | None => fun _ : positive => 1%positive
1723 end.
1724
1725 Definition ExprOfPHOAS_cont
1726 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1727 (do_bounds_check : bool)
1728 {t}
1729 (name_list : option (list string))
1730 : positive * (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * @API.expr var_data (type.final_codomain t))
1731 -> ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * expr)
1732 := expr_of_PHOAS_cont
1733 do_bounds_check (t:=t)
1734 (make_name name_list) (reset_if_names_given name_list).
1735
1736 Definition ExprOfPHOAS_with_opt_outbounds_cps
1737 {absint_opts : AbstractInterpretation.Options}
1738 {t}
1739 (e : @API.Expr t)
1740 (name_list : option (list string))
1741 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1742 (outbounds : option (ZRange.type.base.option.interp (type.final_codomain t)))
1743 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1744 (outtypedefs : base_var_typedef_data (type.final_codomain t))
1745 {T}
1746 (k : positive * (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * @API.expr var_data (type.final_codomain t)) -> ErrT T)
1747 : ErrT T
1748 := let outbounds := Option.value outbounds (partial.Extract true (* assume the output has casts around it *) e inbounds) in
1749 expr_of_PHOAS_cps
1750 (e _) (make_in_name name_list) (make_out_name name_list) inbounds outbounds intypedefs outtypedefs 1 (reset_if_names_given name_list) k.
1751
1752 Definition ExprOfPHOAS_cps
1753 {absint_opts : AbstractInterpretation.Options}
1754 {t}
1755 (e : @API.Expr t)
1756 (name_list : option (list string))
1757 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1758 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1759 (outtypedefs : base_var_typedef_data (type.final_codomain t))
1760 {T}
1761 (k : positive * (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * @API.expr var_data (type.final_codomain t)) -> ErrT T)
1762 : ErrT T
1763 := ExprOfPHOAS_with_opt_outbounds_cps e name_list inbounds None intypedefs outtypedefs k.
1764
1765 Definition var_data_of_PHOAS
1766 {absint_opts : AbstractInterpretation.Options}
1767 {t}
1768 (e : @API.Expr t)
1769 (name_list : option (list string))
1770 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1771 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1772 (outtypedefs : base_var_typedef_data (type.final_codomain t))
1773 : ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)))
1774 := ExprOfPHOAS_with_opt_outbounds_cps
1775 e name_list inbounds None intypedefs outtypedefs
1776 (fun '(count, (din, dout, e)) => ret (din, dout)).
1777
1778 Definition var_data_of_PHOAS_bounds
1779 {absint_opts : AbstractInterpretation.Options}
1780 {t}
1781 (e : @API.Expr t)
1782 (name_list : option (list string))
1783 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1784 (outbounds : ZRange.type.base.option.interp (type.final_codomain t))
1785 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1786 (outtypedefs : base_var_typedef_data (type.final_codomain t))
1787 : ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)))
1788 := ExprOfPHOAS_with_opt_outbounds_cps
1789 e name_list inbounds (Some outbounds) intypedefs outtypedefs
1790 (fun '(count, (din, dout, e)) => ret (din, dout)).
1791
1792 Definition ExprOfPHOAS
1793 {absint_opts : AbstractInterpretation.Options}
1794 {relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt}
1795 (do_bounds_check : bool)
1796 {t}
1797 (e : @API.Expr t)
1798 (name_list : option (list string))
1799 (inbounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1800 (intypedefs : type.for_each_lhs_of_arrow var_typedef_data t)
1801 (outtypedefs : base_var_typedef_data (type.final_codomain t))
1802 : ErrT (type.for_each_lhs_of_arrow var_data t * var_data (type.base (type.final_codomain t)) * expr)
1803 := ExprOfPHOAS_cps
1804 e name_list inbounds intypedefs outtypedefs
1805 (ExprOfPHOAS_cont do_bounds_check name_list).
1806 End with_bind.
1807 End __.
1808 End OfPHOAS.
1809 End IR.
1810 End ToString.
1811 End Compilers.