Debian Codegraph @

src/BoundsPipeline.v

raw
1 (** * BoundsPipeline *)
2 (** This file assembles the various compiler stages together into a
3 composed pipeline. It is the final interface for the compiler,
4 right before integration with Arithmetic. *)
5 From Coq Require Import ZArith.
6 From Coq Require Import QArith_base.
7 From Coq Require Import List.
8 From Coq Require Import String.
9 Require Import Crypto.Util.ZUtil.Log2.
10 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
11 Require Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos.
12 Require Import Crypto.Util.ErrorT.
13 Require Import Crypto.Util.LetIn.
14 Require Import Crypto.Util.Option.
15 Require Import Crypto.Util.Strings.Show.
16 Require Import Crypto.Util.ZRange.
17 Require Import Crypto.Util.ZRange.BasicLemmas.
18 Require Import Crypto.Util.ZRange.Show.
19 Require Import Crypto.Util.Sum.
20 Require Import Crypto.Util.ErrorT.Show.
21 Require Import Crypto.Util.DynList.
22 Require Import Crypto.Util.Tactics.ConstrFail.
23 Require Import Crypto.Util.Tactics.BreakMatch.
24 Require Import Crypto.Util.Tactics.SetoidSubst.
25 Require Import Crypto.Util.Tactics.DestructHead.
26 Require Import Crypto.Util.Tactics.HasBody.
27 Require Import Crypto.Util.Tactics.Head.
28 Require Import Crypto.Util.Tactics.SpecializeBy.
29 Require Import Crypto.Util.Tactics.SplitInContext.
30 Require Import Crypto.Util.Tactics.UniquePose.
31 Require Import Crypto.Util.Tactics.AllInstances.
32 Require Import Crypto.Util.Tactics.PrintContext.
33 Require Import Crypto.Util.Tactics.PrintGoal.
34 Require Import Crypto.Util.DebugMonad.
35 Require Rewriter.Language.Language.
36 Require Crypto.Language.API.
37 Require Rewriter.Language.UnderLets.
38 Require Crypto.AbstractInterpretation.AbstractInterpretation.
39 Require Crypto.AbstractInterpretation.ZRange.
40 Require Rewriter.Rewriter.Rewriter.
41 Require Crypto.MiscCompilerPasses.
42 Require Crypto.Stringification.Language.
43 Require Rewriter.Language.Wf.
44 Require Crypto.Language.WfExtra.
45 Require Rewriter.Language.UnderLetsProofs.
46 Require Crypto.Language.UnderLetsProofsExtra.
47 Require Crypto.MiscCompilerPassesProofs.
48 Require Crypto.MiscCompilerPassesProofsExtra.
49 Require Crypto.Rewriter.All.
50 Require Crypto.AbstractInterpretation.Wf.
51 Require Crypto.AbstractInterpretation.WfExtra.
52 Require Crypto.AbstractInterpretation.Proofs.
53 Require Crypto.Assembly.Parse.
54 Require Crypto.Assembly.Equivalence.
55 Require Import Crypto.Util.Notations.
56 Import Coq.Lists.List. Import ListNotations. Local Open Scope Z_scope.
57 Local Open Scope string_scope.
58 Local Open Scope list_scope.
59
60 Local Set Implicit Arguments.
61 Local Set Primitive Projections.
62 Local Set Keyed Unification.
63
64 Import
65 Rewriter.Language.Wf
66 Crypto.Language.WfExtra
67 Rewriter.Language.UnderLetsProofs
68 Crypto.Language.UnderLetsProofsExtra
69 Crypto.MiscCompilerPassesProofs
70 Crypto.MiscCompilerPassesProofsExtra
71 Crypto.Rewriter.All
72 Crypto.AbstractInterpretation.Wf
73 Crypto.AbstractInterpretation.WfExtra
74 Crypto.AbstractInterpretation.Proofs
75 Rewriter.Language.Language
76 Crypto.Language.API
77 Rewriter.Language.UnderLets
78 Crypto.AbstractInterpretation.AbstractInterpretation
79 AbstractInterpretation.ZRange
80 Rewriter.Rewriter.Rewriter
81 Crypto.MiscCompilerPasses
82 Crypto.Stringification.Language.
83
84 Import
85 Language.Wf.Compilers
86 Language.WfExtra.Compilers
87 UnderLetsProofs.Compilers
88 UnderLetsProofsExtra.Compilers
89 MiscCompilerPassesProofs.Compilers
90 MiscCompilerPassesProofsExtra.Compilers
91 Rewriter.All.Compilers
92 AbstractInterpretation.Wf.Compilers
93 AbstractInterpretation.WfExtra.Compilers
94 AbstractInterpretation.Proofs.Compilers
95 Language.Compilers
96 Language.API.Compilers
97 UnderLets.Compilers
98 AbstractInterpretation.ZRange.Compilers
99 AbstractInterpretation.Compilers
100 Rewriter.Compilers
101 MiscCompilerPasses.Compilers
102 Stringification.Language.Compilers.
103
104 Import
105 ProofsCommon.Compilers.RewriteRules.GoalType
106 ProofsCommon.Compilers.RewriteRules.GoalType.DefaultOptionType.
107
108 Export Stringification.Language.Compilers.Options.
109
110 Import Compilers.API.
111
112 Definition relax_zrange_gen_ranges (possible_ranges : list zrange)
113 : zrange -> option zrange
114 := fun r
115 => List.fold_right
116 (fun r' default
117 => if (r <=? r')%zrange then Some r' else default)
118 None
119 possible_ranges.
120
121 Inductive kind_of_range := signed | unsigned.
122
123 Definition ranges_of_bitwidths (bws : list (Z * kind_of_range))
124 : list zrange
125 := List.map (fun '(bw, k)
126 => match k with
127 | unsigned => r[0~>2^bw-1]
128 | signed => r[-2^(bw-1) ~> 2^(bw-1)-1]
129 end%zrange)
130 bws.
131
132 Definition relax_zrange_gen (only_signed : bool) (possible_values : list Z)
133 : zrange -> option zrange
134 := relax_zrange_gen_ranges
135 (ranges_of_bitwidths
136 (List.flat_map
137 (fun k => List.map (fun bw => (bw, k)) possible_values)
138 (if only_signed
139 then [signed]
140 else [unsigned; signed] (* put [unsigned] first so we prefer unsigned ranges to signed ranges *)))).
141
142 Lemma relax_zrange_gen_ranges_good
143 (possible_ranges : list zrange)
144 : forall r r' z : zrange,
145 is_true (z <=? r)%zrange -> relax_zrange_gen_ranges possible_ranges r = Some r' -> is_true (z <=? r')%zrange.
146 Proof.
147 intros r r' z Hzr.
148 cbv [relax_zrange_gen_ranges].
149 induction possible_ranges as [|R Rs IHRs]; cbn [List.fold_right]; [ congruence | ].
150 intros; break_innermost_match_hyps; inversion_option; subst.
151 { etransitivity; eassumption. }
152 { eauto. }
153 Qed.
154
155 Lemma relax_zrange_gen_good
156 (only_signed : bool)
157 (possible_values : list Z)
158 : forall r r' z : zrange,
159 (z <=? r)%zrange = true -> relax_zrange_gen only_signed possible_values r = Some r' -> (z <=? r')%zrange = true.
160 Proof. apply relax_zrange_gen_ranges_good. Qed.
161
162 (** Instantiate this class with typedefs for various bounds *)
163 Module typedef.
164 Class typedef {t} (bounds : ZRange.type.base.option.interp t) := { name : string ; description : string -> string }.
165 Global Arguments name {_ _ _}.
166 Global Arguments description {_ _ _} _.
167 End typedef.
168 Notation typedef := typedef.typedef (only parsing).
169 Export ZRange.Settings.
170 (** Which of the rewriter methods do we use? *)
171 (** Note that we don't currently generate a precomputed naive method, because it eats too much RAM to do so. *)
172 Inductive low_level_rewriter_method_opt :=
173 precomputed_decision_tree | unreduced_decision_tree | unreduced_naive.
174 Existing Class low_level_rewriter_method_opt.
175 (** We make this an instance later *)
176 Definition default_low_level_rewriter_method : low_level_rewriter_method_opt
177 := precomputed_decision_tree.
178 (** What's the bitwidth? *)
179 Class machine_wordsize_opt := machine_wordsize : Z.
180 #[global]
181 Typeclasses Opaque machine_wordsize_opt.
182 (** Prefix function definitions with static/non-public? *)
183 Class static_opt := static : bool.
184 #[global]
185 Typeclasses Opaque static_opt.
186 (** Prefix internal/helper function definitions with inline? *)
187 Class inline_internal_opt := inline_internal : bool.
188 #[global]
189 Typeclasses Opaque inline_internal_opt.
190 (** Prefix all function definitions with inline? *)
191 Class inline_opt := inline : bool.
192 #[global]
193 Typeclasses Opaque inline_opt.
194 (** Prefix internal function definitions with static/non-public? *)
195 Class internal_static_opt := internal_static : bool.
196 #[global]
197 Typeclasses Opaque internal_static_opt.
198 (** Use the alternate cmovznz implementation using mul? *)
199 Class use_mul_for_cmovznz_opt := use_mul_for_cmovznz : bool.
200 #[global]
201 Typeclasses Opaque use_mul_for_cmovznz_opt.
202 (** Emit the primitive operations? *)
203 Class emit_primitives_opt := emit_primitives : bool.
204 #[global]
205 Typeclasses Opaque emit_primitives_opt.
206 (** Only allow signed integers in the output *)
207 Class only_signed_opt := only_signed : bool.
208 #[global]
209 Typeclasses Opaque only_signed_opt.
210 (** Rewrite zselect into expressions that don't require cmov? *)
211 Class no_select_opt := no_select : bool.
212 #[global]
213 Typeclasses Opaque no_select_opt.
214 (** If [None], don't rewrite zselects. If [Some w], rewrite zselects assuming w-bit words *)
215 Class no_select_size_opt := no_select_size : option Z.
216 #[global]
217 Typeclasses Opaque no_select_size_opt.
218 (** Split apart multiplications? *)
219 Class should_split_mul_opt := should_split_mul : bool.
220 #[global]
221 Typeclasses Opaque should_split_mul_opt.
222 (** If [None], don't split apart multiplications; if [Some (w, wc)], split apart multiplications to use wordsize [w] and widen carries to width [wc] *)
223 Class split_mul_to_opt := split_mul_to : option (Z * Z).
224 #[global]
225 Typeclasses Opaque split_mul_to_opt.
226 (** Split apart multi-return functions? *)
227 Class should_split_multiret_opt := should_split_multiret : bool.
228 #[global]
229 Typeclasses Opaque should_split_multiret_opt.
230 (** If [None], don't split apart multi-return functions; if [Some (w, wc)], split apart multi-return functions to use wordsize [w] and widen carries to width [wc] *)
231 Class split_multiret_to_opt := split_multiret_to : option (Z * Z).
232 #[global]
233 Typeclasses Opaque split_multiret_to_opt.
234 (** Widen carries to the machine wordsize? *)
235 Class widen_carry_opt := widen_carry : bool.
236 #[global]
237 Typeclasses Opaque widen_carry_opt.
238 (** Widen uint8 / bytes types to machine wordsize? *)
239 Class widen_bytes_opt := widen_bytes : bool.
240 #[global]
241 Typeclasses Opaque widen_bytes_opt.
242 (** Display rewriting pass information *)
243 Class debug_rewriting_opt := debug_rewriting : bool.
244 #[global]
245 Typeclasses Opaque debug_rewriting_opt.
246 (** Display rewriting pass information on success *)
247 Class debug_rewriting_on_success_opt := debug_rewriting_on_success : bool.
248 #[global]
249 Typeclasses Opaque debug_rewriting_on_success_opt.
250 (** Display rewriting pass information on failure *)
251 Class debug_rewriting_on_failure_opt := debug_rewriting_on_failure : bool.
252 #[global]
253 Typeclasses Opaque debug_rewriting_on_failure_opt.
254 (** Fancy Output *)
255 Record to_fancy_args := { invert_low : Z (*log2wordmax*) -> Z -> option Z ; invert_high : Z (*log2wordmax*) -> Z -> option Z ; value_range : zrange ; flag_range : zrange }.
256 Class translate_to_fancy_opt := translate_to_fancy : option to_fancy_args.
257 #[global]
258 Typeclasses Opaque translate_to_fancy_opt.
259 Definition default_translate_to_fancy : translate_to_fancy_opt := None.
260 Class translate_to_fancy_opt_correct {translate_to_fancy : translate_to_fancy_opt}
261 := translate_to_fancy_correct
262 : match translate_to_fancy with
263 | Some {| invert_low := il ; invert_high := ih |}
264 => (forall s v v' : Z, il s v = Some v' -> v = Z.land v' (2^(s/2)-1))
265 /\ (forall s v v' : Z, ih s v = Some v' -> v = Z.shiftr v' (s/2))
266 | None => True
267 end.
268 Global Arguments translate_to_fancy_opt_correct {_}, _.
269 #[global]
270 Typeclasses Opaque translate_to_fancy_opt_correct.
271 #[global]
272 Hint Mode translate_to_fancy_opt_correct + : typeclass_instances.
273 Global Instance default_translate_to_fancy_correct : translate_to_fancy_opt_correct default_translate_to_fancy := I.
274 (** Unfold value_barrier *)
275 Class unfold_value_barrier_opt := unfold_value_barrier : bool.
276 #[global]
277 Typeclasses Opaque unfold_value_barrier_opt.
278 (** Lines of assembly code (implicitly separated by \n) *)
279 Class assembly_hints_lines_opt := assembly_hints_lines : list (string (* file name *) * list string).
280 #[global]
281 Typeclasses Opaque assembly_hints_lines_opt.
282 (** Error if there are un-requested assembly functions *)
283 Class error_on_unused_assembly_functions_opt := error_on_unused_assembly_functions : bool.
284 #[global]
285 Typeclasses Opaque error_on_unused_assembly_functions_opt.
286 (** Ignore function-name mismatch errors when there's only one assembly function and only one actual function requested *)
287 Class ignore_unique_asm_names_opt := ignore_unique_asm_names : bool.
288 #[global]
289 Typeclasses Opaque ignore_unique_asm_names_opt.
290 Inductive synthesis_output_kind := normal_output | assembly_output.
291 Notation no_select_size_of_no_select machine_wordsize
292 := (if no_select return no_select_size_opt
293 then Some machine_wordsize
294 else None) (only parsing).
295 Notation split_mul_to_of_should_split_mul machine_wordsize possible_bitwidths
296 := (if should_split_mul return split_mul_to_opt
297 then Some (machine_wordsize, fold_right Z.min machine_wordsize (filter (fun x => (1 <=? x)%Z) possible_bitwidths))
298 else None) (only parsing).
299 Notation split_multiret_to_of_should_split_multiret machine_wordsize possible_bitwidths
300 := (if should_split_multiret return split_multiret_to_opt
301 then Some (machine_wordsize, fold_right Z.min machine_wordsize (filter (fun x => (1 <=? x)%Z) possible_bitwidths))
302 else None) (only parsing).
303 (* We include [0], so that even after bounds relaxation, we can
304 notice where the constant 0s are, and remove them. *)
305 Notation prefix_with_carry bitwidths :=
306 ((if widen_carry then (0::bitwidths) else (0::1::bitwidths))%Z)
307 (only parsing).
308 Notation prefix_with_carry_bytes bitwidths :=
309 (prefix_with_carry (match bitwidths return _ with bw => if widen_bytes then bw else 8::bw end)%Z) (* master and 8.9 are incompatible about scoping of multiple occurrences of an argument *)
310 (only parsing).
311
312 Definition typedef_info_of_typedef {relax_zrange : relax_zrange_opt} {t bounds} (td : @typedef t bounds)
313 : ToString.typedef_info
314 := (typedef.name,
315 typedef.description,
316 ToString.int.option.interp.to_union (ToString.int.option.interp.of_zrange_relaxed (ZRange.type.base.option.map_ranges relax_zrange bounds)),
317 existT _ t bounds).
318
319 #[global]
320 Declare Scope pipelineM_scope.
321 #[global]
322 Delimit Scope pipelineM_scope with pipelineM.
323 Module Pipeline.
324 Import GeneralizeVar.
325
326 Class BoundsPipelineOptions :=
327 { AbstractInterpretation_opts : AbstractInterpretation.Options
328 ; low_level_rewriter_method : low_level_rewriter_method_opt
329 ; only_signed : only_signed_opt
330 ; no_select_size : no_select_size_opt
331 ; split_mul_to : split_mul_to_opt
332 ; split_multiret_to : split_multiret_to_opt
333 ; unfold_value_barrier : unfold_value_barrier_opt
334 ; relax_adc_sbb_return_carry_to_bitwidth : relax_adc_sbb_return_carry_to_bitwidth_opt
335 ; translate_to_fancy : translate_to_fancy_opt
336 ; debug_rewriting : debug_rewriting_opt
337 ; with_dead_code_elimination : bool := true
338 ; with_let_bind_return : bool := true
339 (** convert adc/sbb which generates no carry to add/sub iff we're not fancy *)
340 ; adc_no_carry_to_add := match translate_to_fancy with Some _ => false | None => true end
341 }.
342 Definition default_BoundsPipelineOptions : BoundsPipelineOptions :=
343 {| AbstractInterpretation_opts := AbstractInterpretation.default_Options
344 ; low_level_rewriter_method := default_low_level_rewriter_method
345 ; only_signed := false
346 ; no_select_size := None
347 ; split_mul_to := None
348 ; split_multiret_to := None
349 ; unfold_value_barrier := true
350 ; relax_adc_sbb_return_carry_to_bitwidth := []
351 ; translate_to_fancy := default_translate_to_fancy
352 ; debug_rewriting := false
353 |}.
354
355 Global Existing Instances
356 Build_BoundsPipelineOptions
357 AbstractInterpretation_opts
358 low_level_rewriter_method
359 only_signed
360 no_select_size
361 split_mul_to
362 split_multiret_to
363 unfold_value_barrier
364 relax_adc_sbb_return_carry_to_bitwidth
365 translate_to_fancy
366 debug_rewriting
367 .
368 #[global]
369 Hint Cut [
370 ( _ * )
371 (AbstractInterpretation_opts
372 | low_level_rewriter_method
373 | only_signed
374 | no_select_size
375 | split_mul_to
376 | split_multiret_to
377 | unfold_value_barrier
378 | relax_adc_sbb_return_carry_to_bitwidth
379 | translate_to_fancy
380 | debug_rewriting
381 ) ( _ * )
382 (Build_BoundsPipelineOptions
383 )
384 ] : typeclass_instances.
385
386 Inductive ErrorMessage :=
387 | Computed_bounds_are_not_tight_enough
388 {t} (computed_bounds expected_bounds : ZRange.type.base.option.interp (type.final_codomain t))
389 (syntax_tree : Expr t) (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
390 | No_modular_inverse (descr : string) (v : Z) (m : Z)
391 | Value_not_leZ (descr : string) (lhs rhs : Z)
392 | Value_not_leQ (descr : string) (lhs rhs : Q)
393 | Value_not_ltZ (descr : string) (lhs rhs : Z)
394 | Value_not_lt_listZ (descr : string) (lhs rhs : list Z)
395 | Value_not_le_listZ (descr : string) (lhs rhs : list Z)
396 | Values_not_provably_distinctZ (descr : string) (lhs rhs : Z)
397 | Values_not_provably_equalZ (descr : string) (lhs rhs : Z)
398 | Values_not_provably_equal_listZ (descr : string) (lhs rhs : list Z)
399 | Unsupported_casts_in_input {t} (e : Expr t) (ls : list { t : _ & @expr (fun _ => string) t })
400 | Stringification_failed {t} (e : Expr t) (err : string)
401 | Invalid_argument (msg : string)
402 | Assembly_parsing_error (fname : string) (msg : Assembly.Parse.ParseValidatedError)
403 | Assembly_without_any_global_labels (fnames : list string)
404 | Unused_global_assembly_labels (fname_labels : list (string * list string)) (valid_requests : list string)
405 | Equivalence_checking_failure_pre_asm
406 {t} (e : Expr t) (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
407 (msg : Assembly.Equivalence.EquivalenceCheckingError)
408 | Equivalence_checking_failure
409 {t} (e : Expr t) (asm_fname : string) (asm : Assembly.Syntax.Lines) (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
410 (msg : Assembly.Equivalence.EquivalenceCheckingError)
411 .
412
413 Notation DebugM := (@DebugM string) (only parsing).
414 Notation ErrorT := (ErrorT ErrorMessage).
415 Notation M T := (DebugM (ErrorT T)).
416
417 Module M.
418 Definition bind {A B} (x : M A) (k : A -> M B) : M B
419 := (x <- x;
420 match x with
421 | Success x => k x
422 | Error err => Debug.ret (Error err)
423 end)%debugM.
424 Global Arguments bind {A B}%type_scope (x k)%pipelineM_scope.
425 Notation sequence x y := (@bind unit _ x%pipelineM (fun 'tt => y%pipelineM)).
426 Notation ret x := (@Debug.ret string _ (@Success ErrorMessage _ x)).
427 Notation err msg := (@Debug.ret string _ (@Error ErrorMessage _ msg)).
428 Notation debug msg := (Debug.sequence (Debug.debug msg) (ret tt)).
429 Module Export Notations.
430 Notation "x <- y ; f" := (bind y%pipelineM (fun x => f%pipelineM)) : pipelineM_scope.
431 Notation "f ;; g" := (sequence f%pipelineM g%pipelineM) : pipelineM_scope.
432 End Notations.
433 End M.
434 Export M.Notations.
435
436 Record ExtendedSynthesisResult t :=
437 { lines : list string
438 ; ident_infos : ToString.ident_infos
439 ; arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t
440 ; out_bounds : ZRange.type.base.option.interp (type.final_codomain t)
441 ; arg_typedefs : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_typedef_data t
442 ; out_typedefs : ToString.OfPHOAS.base_var_typedef_data (type.final_codomain t)
443 ; expr : Expr t
444 }.
445
446 Section show.
447 Context {machine_wordsize : machine_wordsize_opt}
448 {output_api : ToString.OutputLanguageAPI}.
449 Local Open Scope string_scope.
450 Global Instance show_low_level_rewriter_method_opt : Show low_level_rewriter_method_opt
451 := fun v => match v with
452 | precomputed_decision_tree => "precomputed_decision_tree"
453 | unreduced_decision_tree => "unreduced_decision_tree"
454 | unreduced_naive => "unreduced_naive"
455 end.
456 Fixpoint find_too_loose_base_bounds {t}
457 : ZRange.type.base.option.interp t -> ZRange.type.base.option.interp t-> bool * list (nat * nat) * list (zrange * zrange)
458 := match t return ZRange.type.base.option.interp t -> ZRange.type.option.interp t-> bool * list (nat * nat) * list (zrange * zrange) with
459 | base.type.unit
460 => fun 'tt 'tt => (false, nil, nil)
461 | base.type.type_base base.type.nat
462 | base.type.type_base base.type.positive
463 | base.type.type_base base.type.bool
464 | base.type.type_base base.type.zrange
465 | base.type.type_base base.type.string
466 => fun _ _ => (false, nil, nil)
467 | base.type.type_base base.type.Z
468 => fun a b
469 => match a, b with
470 | None, None => (false, nil, nil)
471 | Some _, None => (false, nil, nil)
472 | None, Some _ => (true, nil, nil)
473 | Some a, Some b
474 => if is_tighter_than_bool a b
475 then (false, nil, nil)
476 else (false, nil, ((a, b)::nil))
477 end
478 | base.type.option A
479 => fun a b
480 => match a, b with
481 | None, None => (false, nil, nil)
482 | Some _, None => (false, nil, nil)
483 | None, Some _ => (true, nil, nil)
484 | Some None, Some None
485 | Some (Some _), Some None
486 | Some None, Some (Some _)
487 => (false, nil, nil)
488 | Some (Some a), Some (Some b)
489 => @find_too_loose_base_bounds A a b
490 end
491 | base.type.prod A B
492 => fun '(ra, rb) '(ra', rb')
493 => let '(b1, lens1, ls1) := @find_too_loose_base_bounds A ra ra' in
494 let '(b2, lens2, ls2) := @find_too_loose_base_bounds B rb rb' in
495 (orb b1 b2, lens1 ++ lens2, ls1 ++ ls2)%list
496 | base.type.list A
497 => fun ls1 ls2
498 => match ls1, ls2 with
499 | None, None
500 | Some _, None
501 => (false, nil, nil)
502 | None, Some _
503 => (true, nil, nil)
504 | Some ls1, Some ls2
505 => List.fold_right
506 (fun '(b, len, err) '(bs, lens, errs)
507 => (orb b bs, len ++ lens, err ++ errs)%list)
508 (false,
509 (if (List.length ls1 =? List.length ls2)%nat
510 then nil
511 else ((List.length ls1, List.length ls2)::nil)),
512 nil)
513 (List.map
514 (fun '(a, b) => @find_too_loose_base_bounds A a b)
515 (List.combine ls1 ls2))
516 end
517 end.
518
519 Definition find_too_loose_bounds {t}
520 : ZRange.type.option.interp t -> ZRange.type.option.interp t-> bool * list (nat * nat) * list (zrange * zrange)
521 := match t with
522 | type.arrow s d => fun _ _ => (false, nil, nil)
523 | type.base t => @find_too_loose_base_bounds t
524 end.
525 Definition explain_too_loose_bounds {t} (b1 b2 : ZRange.type.option.interp t)
526 : string
527 := let '(none_some, lens, bs) := find_too_loose_bounds b1 b2 in
528 String.concat
529 String.NewLine
530 ((if none_some then "Found None where Some was expected"::nil else nil)
531 ++ (List.map
532 (A:=nat*nat)
533 (fun '(l1, l2) => "Found a list of length " ++ show l1 ++ " where a list of length " ++ show l2 ++ " was expected.")
534 lens)
535 ++ (List.map
536 (A:=zrange*zrange)
537 (fun '(b1, b2) => "The bounds " ++ show b1 ++ " are looser than the expected bounds " ++ show b2)
538 bs)).
539
540 (** show both with and without all casts, but don't try to convert to the low-level language like C *)
541 Definition show_lines_Expr_with_and_without_casts {t} : ShowLines (Expr t)
542 := fun syntax_tree
543 => ((let _ : PHOAS.with_all_casts := true in show_lines syntax_tree)
544 ++ ["Which with some casts elided is:"]
545 ++ (let _ : PHOAS.with_all_casts := false in show_lines syntax_tree))%list.
546
547 Definition show_lines_Expr {t} (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t) (include_input_bounds : bool)
548 : ShowLines (Expr t)
549 := fun syntax_tree
550 => let _ := default_language_naming_conventions in
551 let _ := default_documentation_options in
552 let _ := default_output_options in
553 let _ := AbstractInterpretation.default_Options in
554 match ToString.ToFunctionLines
555 (relax_zrange := fun r => r)
556 machine_wordsize
557 false (* do extra bounds check *) false (* internal static *) false (* static *) false (* all static *) false (* inline *) "" "f" syntax_tree (fun _ _ => nil) None arg_bounds ZRange.type.base.option.None (type.forall_each_lhs_of_arrow (@ToString.OfPHOAS.var_typedef_data_None)) ToString.OfPHOAS.base_var_typedef_data_None with
558 | inl (E_lines, types_used)
559 => ["The syntax tree:"]
560 ++ show_lines_Expr_with_and_without_casts syntax_tree
561 ++ [""; "which can be pretty-printed as:"]
562 ++ E_lines ++ [""]
563 ++ (if include_input_bounds then ["with input bounds " ++ show_lvl arg_bounds 0 ++ "." ++ String.NewLine]%string else [])
564 | inr errs
565 => (["(Unprintible syntax tree used in bounds analysis)" ++ String.NewLine]%string)
566 ++ ["Stringification failed on the syntax tree:"] ++ show_lines_Expr_with_and_without_casts syntax_tree ++ [errs]
567 end%list.
568
569 Global Instance show_lines_ErrorMessage : ShowLines ErrorMessage
570 := fun e
571 => let _ := default_language_naming_conventions in
572 let _ := default_documentation_options in
573 match e with
574 | Computed_bounds_are_not_tight_enough t computed_bounds expected_bounds syntax_tree arg_bounds
575 => ((["Computed bounds " ++ show_lvl computed_bounds 0 ++ " are not tight enough (expected bounds not looser than " ++ show_lvl expected_bounds 0 ++ ")."]%string)
576 ++ [explain_too_loose_bounds (t:=type.base _) computed_bounds expected_bounds]
577 ++ show_lines_Expr arg_bounds true (* re-print the input bounds at the end; they're very relevant *) syntax_tree)%list
578 | No_modular_inverse descr v m
579 => ["Could not compute a modular inverse (" ++ descr ++ ") for " ++ show v ++ " mod " ++ show m]%string
580 | Value_not_leZ descr lhs rhs
581 => ["Value not ≤ (" ++ descr ++ ") : expected " ++ show lhs ++ " ≤ " ++ show rhs]%string
582 | Value_not_leQ descr lhs rhs
583 => ["Value not ≤ (" ++ descr ++ ") : expected " ++ show lhs ++ " ≤ " ++ show rhs]%string
584 | Value_not_ltZ descr lhs rhs
585 => ["Value not < (" ++ descr ++ ") : expected " ++ show lhs ++ " < " ++ show rhs]%string
586 | Value_not_lt_listZ descr lhs rhs
587 => ["Value not < (" ++ descr ++ ") : expected " ++ show lhs ++ " < " ++ show rhs]%string
588 | Value_not_le_listZ descr lhs rhs
589 => ["Value not ≤ (" ++ descr ++ ") : expected " ++ show lhs ++ " ≤ " ++ show rhs]%string
590 | Values_not_provably_distinctZ descr lhs rhs
591 => ["Values not provably distinct (" ++ descr ++ ") : expected " ++ show lhs ++ " ≠ " ++ show rhs]%string
592 | Values_not_provably_equalZ descr lhs rhs
593 | Values_not_provably_equal_listZ descr lhs rhs
594 => ["Values not provably equal (" ++ descr ++ ") : expected " ++ show lhs ++ " = " ++ show rhs]%string
595 | Unsupported_casts_in_input t e ls
596 => ["Unsupported casts in input syntax tree:"]
597 ++ show_lines e
598 ++ ["Unsupported casts: " ++ @show_list _ (fun v => show (projT2 v)) ls]%string
599 | Stringification_failed t e err
600 => ["Stringification failed on the syntax tree:"]
601 ++ show_lines_Expr_with_and_without_casts e
602 ++ [err]
603 | Invalid_argument msg
604 => ["Invalid argument: " ++ msg]%string
605 | Assembly_parsing_error fname msgs
606 => (["In assembly file " ++ fname ++ ":"]%string)
607 ++ show_lines msgs
608 | Assembly_without_any_global_labels []
609 => ["Internal error: Assembly_without_any_global_labels []"]
610 | Assembly_without_any_global_labels fnames
611 => ["There are no global labels in " ++ String.concat ", " fnames ++ "."]%string
612 | Unused_global_assembly_labels fname_labels valid_requests
613 => ["The following global functions are present in the hints file but do not correspond to any requested function: " ++ String.concat ", " (List.map (fun '(fname, labels) => String.concat ", " labels ++ " (in " ++ fname ++ ")") fname_labels) ++ " (expected one of: " ++ String.concat ", " valid_requests ++ ")"]%string
614 | Equivalence_checking_failure_pre_asm _ e arg_bounds err
615 => (["Error while preparing to check for equivalence of syntax tree and assembly:"]
616 ++ show_lines_Expr arg_bounds false (* don't re-print input bounds; they're not relevant *) e
617 ++ [""; "(no assembly)"]%string
618 ++ [""; "Equivalence checking error:"]
619 ++ show_lines err)
620 | Equivalence_checking_failure _ e asm_fname asm arg_bounds err
621 => (["Error while checking for equivalence of syntax tree and assembly:"]
622 ++ show_lines_Expr arg_bounds false (* don't re-print input bounds; they're not relevant *) e
623 ++ [""; "Assembly (in " ++ asm_fname ++ "):"]%string
624 ++ match Equivalence.symbolic_state_of_EquivalenceCheckingError err with
625 | Some s => Equivalence.show_lines_AnnotatedLines (asm, s)
626 | None => show_lines asm
627 end
628 ++ [""; "Equivalence checking error:"]
629 ++ show_lines err)
630 end%list.
631 Local Instance show_ErrorMessage : Show ErrorMessage
632 := fun err => String.concat String.NewLine (show_lines err).
633 End show.
634
635 Definition debug_after_rewrite {debug_rewriting : debug_rewriting_opt} {t}
636 (descr : string)
637 (E : Expr t)
638 : DebugM unit
639 := if debug_rewriting
640 then Debug.debug ((["After rewriting " ++ descr ++ ":"]%string)
641 ++ (let _ : PHOAS.with_all_casts := true in show_lines E))
642 else Debug.ret tt.
643
644 Definition wrap_debug_rewrite {debug_rewriting : debug_rewriting_opt} {t}
645 (descr : string)
646 (DoRewrite : Expr t -> Expr t)
647 (E : Expr t)
648 : DebugM (Expr t)
649 := (let E := DoRewrite E in
650 debug_after_rewrite descr E;;
651 Debug.ret E).
652
653 (* version where the rewriter is already wrapped with debug info *)
654 Definition RewriteAndEliminateDeadAndInline_gen {debug_rewriting : debug_rewriting_opt} {t}
655 (descr : string)
656 (DoRewrite : Expr t -> DebugM (Expr t))
657 (with_dead_code_elimination : bool)
658 (with_subst01 : bool)
659 (with_let_bind_return : bool)
660 (E : Expr t)
661 : DebugM (Expr t)
662 := (E <- DoRewrite E;
663 E <- if with_subst01 return DebugM (Expr t)
664 then wrap_debug_rewrite ("subst01 for " ++ descr) (Subst01.Subst01 ident.is_comment) E
665 else if with_dead_code_elimination return DebugM (Expr t)
666 then wrap_debug_rewrite ("DCE for " ++ descr) (DeadCodeElimination.EliminateDead ident.is_comment) E
667 else Debug.ret E;
668 E <- if with_let_bind_return
669 then wrap_debug_rewrite ("LetBindReturn for " ++ descr) (UnderLets.LetBindReturn (@ident.is_var_like)) E
670 else Debug.ret E;
671 E <- DoRewrite E; (* after inlining, see if any new rewrite redexes are available *)
672 E <- if with_dead_code_elimination
673 then wrap_debug_rewrite ("DCE after " ++ descr) (DeadCodeElimination.EliminateDead ident.is_comment) E
674 else Debug.ret E;
675 Debug.ret E)%debugM.
676
677 Definition RewriteAndEliminateDeadAndInline {debug_rewriting : debug_rewriting_opt} {t}
678 (descr : string)
679 (DoRewrite : Expr t -> Expr t)
680 (with_dead_code_elimination : bool)
681 (with_subst01 : bool)
682 (with_let_bind_return : bool)
683 (E : Expr t)
684 : DebugM (Expr t)
685 := RewriteAndEliminateDeadAndInline_gen descr (wrap_debug_rewrite descr DoRewrite) with_dead_code_elimination with_subst01 with_let_bind_return E.
686
687 Definition opts_of_method
688 {low_level_rewriter_method : low_level_rewriter_method_opt}
689 := {| use_decision_tree
690 := match low_level_rewriter_method with
691 | precomputed_decision_tree => true
692 | unreduced_decision_tree => true
693 | unreduced_naive => false
694 end;
695 use_precomputed_functions
696 := match low_level_rewriter_method with
697 | precomputed_decision_tree => true
698 | unreduced_decision_tree => false
699 | unreduced_naive => false
700 end; |}.
701
702 Definition PreBoundsPipeline
703 {opts : AbstractInterpretation.Options}
704 {low_level_rewriter_method : low_level_rewriter_method_opt}
705 {only_signed : only_signed_opt}
706 {unfold_value_barrier : unfold_value_barrier_opt}
707 {translate_to_fancy : translate_to_fancy_opt}
708 {debug_rewriting : debug_rewriting_opt}
709 (with_dead_code_elimination : bool := true)
710 (with_subst01 : bool)
711 (with_let_bind_return : bool)
712 {t}
713 (E : Expr t)
714 (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
715 : DebugM (Expr t)
716 := ((*let E := expr.Uncurry E in*)
717 let opts := opts_of_method in
718 let E := PartialEvaluateWithListInfoFromBounds E arg_bounds in
719 E <- wrap_debug_rewrite "PartialEvaluate" (PartialEvaluate opts) E;
720 E <- if unfold_value_barrier
721 then wrap_debug_rewrite "RewriteUnfoldValueBarrier" (RewriteRules.RewriteUnfoldValueBarrier opts) E
722 else Debug.ret E;
723 E <- RewriteAndEliminateDeadAndInline "RewriteArith_0" (RewriteRules.RewriteArith 0 opts) with_dead_code_elimination with_subst01 with_let_bind_return E;
724 E <- wrap_debug_rewrite "RewriteArith_2⁸" (RewriteRules.RewriteArith (2^8) opts) E; (* reassociate small consts *)
725 E <- match translate_to_fancy with
726 | Some {| invert_low := invert_low ; invert_high := invert_high |}
727 => wrap_debug_rewrite "RewriteToFancy" (RewriteRules.RewriteToFancy invert_low invert_high opts) E
728 | None => Debug.ret E
729 end;
730 dlet_nd e := ToFlat E in
731 let E := FromFlat e in
732 Debug.ret E)%debugM.
733
734 (** Useful for rewriting to a prettier form sometimes *)
735 Definition RepeatRewriteAddAssocLeftAndFlattenThunkedRectsWithDebug
736 {low_level_rewriter_method : low_level_rewriter_method_opt}
737 {debug_rewriting : debug_rewriting_opt}
738 (n : nat)
739 {t}
740 (E : DebugM (Expr t))
741 : DebugM (Expr t)
742 := (let opts := Pipeline.opts_of_method in
743 E <- E;
744 E <- wrap_debug_rewrite "RewriteFlattenThunkedRects" (RewriteRules.RewriteFlattenThunkedRects opts) E;
745 E <- wrap_debug_rewrite ("repeat " ++ show n ++ " RewriteAddAssocLeft") (fun E => List.fold_right (fun f v => f v) E (List.repeat (RewriteRules.RewriteAddAssocLeft opts) n)) E;
746 Debug.ret E)%debugM.
747
748 Definition RepeatRewriteAddAssocLeftAndFlattenThunkedRects
749 {low_level_rewriter_method : low_level_rewriter_method_opt}
750 {debug_rewriting : debug_rewriting_opt}
751 (n : nat)
752 {t}
753 (E : DebugM (Expr t))
754 : Expr t
755 := Debug.eval_result (RepeatRewriteAddAssocLeftAndFlattenThunkedRectsWithDebug n E).
756
757 Definition BoundsPipelineWithDebug
758 {opts : BoundsPipelineOptions}
759 (with_subst01 : bool)
760 (possible_values : list Z)
761 (relax_zrange := relax_zrange_gen only_signed possible_values)
762 {t}
763 (E : Expr t)
764 arg_bounds
765 out_bounds
766 : M (Expr t)
767 := ((*let E := expr.Uncurry E in*)
768 let assume_cast_truncates := false in
769 let opts := opts_of_method in
770 E <- PreBoundsPipeline (* with_dead_code_elimination *) with_subst01 with_let_bind_return E arg_bounds;
771 (** We first do bounds analysis with no relaxation so that we
772 can do rewriting with casts, and then once that's out of the
773 way, we do bounds analysis again to relax the bounds. *)
774 (** To get better error messages, we don't check bounds until
775 after doing some extra rewriting *)
776 let E' := CheckedPartialEvaluateWithBounds (fun _ => None) assume_cast_truncates (@ident.is_comment) false E arg_bounds ZRange.type.base.option.None in
777 E' <- match E' with
778 | inl E
779 => (debug_after_rewrite "CheckedPartialEvaluateWithBounds" E;;
780 E <- RewriteAndEliminateDeadAndInline "RewriteArithWithCasts" (RewriteRules.RewriteArithWithCasts adc_no_carry_to_add opts) with_dead_code_elimination with_subst01 with_let_bind_return E;
781 dlet_nd e := ToFlat E in
782 let E := FromFlat e in
783 (** to give good error messages, we first look at
784 the version of the syntax tree annotated with
785 unrelaxed ranges *)
786 let E' := CheckedPartialEvaluateWithBounds (fun _ => None) assume_cast_truncates (@ident.is_comment) true (* strip pre-existing casts *) E arg_bounds out_bounds in
787 match E' with
788 | inl E
789 => debug_after_rewrite "CheckedPartialEvaluateWithBounds 2" E;;
790 dlet_nd e := ToFlat E in
791 let E := FromFlat e in
792 let E' := CheckedPartialEvaluateWithBounds relax_zrange assume_cast_truncates (@ident.is_comment) true (* strip pre-existing casts *) E arg_bounds out_bounds in
793 match E' with
794 | inl E
795 => debug_after_rewrite "CheckedPartialEvaluateWithBounds 3" E;;
796 Debug.ret (inl E)
797 | inr E
798 => Debug.ret (inr E)
799 end
800 | inr v => Debug.ret (inr v)
801 end)
802 | inr v => Debug.ret (inr v)
803 end;
804 match E' with
805 | inl E
806 => (E <- match split_mul_to with
807 | Some (max_bitwidth, lgcarrymax)
808 => wrap_debug_rewrite "RewriteMulSplit" (RewriteRules.RewriteMulSplit max_bitwidth lgcarrymax opts) E
809 | None => Debug.ret E
810 end;
811 E <- match split_multiret_to with
812 | Some (max_bitwidth, lgcarrymax)
813 => RewriteAndEliminateDeadAndInline "RewriteMultiRetSplit" (RewriteRules.RewriteMultiRetSplit max_bitwidth lgcarrymax opts) with_dead_code_elimination with_subst01 with_let_bind_return E
814 | None => Debug.ret E
815 end;
816 let rewrote_E_so_should_rewrite_arith_again
817 := match split_mul_to, split_multiret_to with
818 | Some _, _ | _, Some _ => true
819 | None, None => false
820 end in
821 E <- if rewrote_E_so_should_rewrite_arith_again
822 then RewriteAndEliminateDeadAndInline "RewriteArithWithCasts" (RewriteRules.RewriteArithWithCasts adc_no_carry_to_add opts) with_dead_code_elimination with_subst01 with_let_bind_return E
823 else Debug.ret E;
824 E <- match relax_adc_sbb_return_carry_to_bitwidth with
825 | [] => Debug.ret E
826 | _ => wrap_debug_rewrite "RewriteRelaxBitwidthAdcSbb" (RewriteRules.RewriteRelaxBitwidthAdcSbb relax_adc_sbb_return_carry_to_bitwidth opts) E
827 end;
828
829 E <- match translate_to_fancy with
830 | Some {| invert_low := invert_low ; invert_high := invert_high ; value_range := value_range ; flag_range := flag_range |}
831 => wrap_debug_rewrite "RewriteToFancyWithCasts" (RewriteRules.RewriteToFancyWithCasts invert_low invert_high value_range flag_range opts) E
832 | None => Debug.ret E
833 end;
834 E <- match no_select_size with
835 | Some bitwidth
836 => wrap_debug_rewrite "RewriteNoSelect" (RewriteRules.RewriteNoSelect bitwidth opts) E
837 | None => Debug.ret E
838 end;
839 E <- wrap_debug_rewrite "RewriteStripLiteralCasts" (RewriteRules.RewriteStripLiteralCasts opts) E;
840 M.ret E)
841 | inr (inl (b, E))
842 => M.err (Computed_bounds_are_not_tight_enough b out_bounds E arg_bounds)
843 | inr (inr unsupported_casts)
844 => M.err (Unsupported_casts_in_input E (@List.map { _ & forall var, _ } _ (fun '(existT t e) => existT _ t (e _)) unsupported_casts))
845 end)%debugM.
846
847 Definition BoundsPipeline
848 {opts : BoundsPipelineOptions}
849 (with_subst01 : bool)
850 (possible_values : list Z)
851 (relax_zrange := relax_zrange_gen only_signed possible_values)
852 {t}
853 (E : Expr t)
854 arg_bounds
855 out_bounds
856 : ErrorT (Expr t)
857 := Debug.eval_result (BoundsPipelineWithDebug with_subst01 possible_values E arg_bounds out_bounds).
858
859 Definition BoundsPipelineToExtendedResult
860 {opts : BoundsPipelineOptions}
861 {output_language_api : ToString.OutputLanguageAPI}
862 {language_naming_conventions : language_naming_conventions_opt}
863 {documentation_options : documentation_options_opt}
864 {output_options : output_options_opt}
865 {internal_static : internal_static_opt}
866 {static : static_opt}
867 {all_static : static_opt}
868 (type_prefix : string)
869 (name : string)
870 (with_subst01 : bool)
871 (inline : bool)
872 (possible_values : list Z)
873 (relax_zrangef : relax_zrange_opt
874 := fun r => Option.value (relax_zrange_gen only_signed possible_values r) r)
875 (machine_wordsize : Z)
876 {t}
877 (E : Expr t)
878 (comment : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_data t -> ToString.OfPHOAS.var_data (type.final_codomain t) -> list string)
879 (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
880 (out_bounds : ZRange.type.base.option.interp (type.final_codomain t))
881 (arg_typedefs : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_typedef_data t)
882 (out_typedefs : ToString.OfPHOAS.base_var_typedef_data (type.final_codomain t))
883 : M (ExtendedSynthesisResult t)
884 := (E' <- BoundsPipelineWithDebug
885 with_subst01
886 possible_values
887 E arg_bounds out_bounds;
888 let E := ToString.ToFunctionLines
889 machine_wordsize true (orb internal_static static) static all_static inline type_prefix name E' comment None arg_bounds out_bounds arg_typedefs out_typedefs in
890 match E with
891 | inl (lines, infos)
892 => M.ret {| lines := lines; ident_infos := infos; arg_bounds := arg_bounds; out_bounds := out_bounds; arg_typedefs := arg_typedefs ; out_typedefs := out_typedefs ; expr := E' |}
893 | inr err => M.err (Stringification_failed E' err)
894 end)%pipelineM.
895
896 Definition BoundsPipelineToStringsWithDebug
897 {opts : BoundsPipelineOptions}
898 {output_language_api : ToString.OutputLanguageAPI}
899 {language_naming_conventions : language_naming_conventions_opt}
900 {documentation_options : documentation_options_opt}
901 {output_options : output_options_opt}
902 {internal_static : internal_static_opt}
903 {static : static_opt}
904 {all_static : static_opt}
905 (type_prefix : string)
906 (name : string)
907 (with_dead_code_elimination : bool := true)
908 (with_subst01 : bool)
909 (inline : bool)
910 (possible_values : list Z)
911 (relax_zrangef : relax_zrange_opt
912 := fun r => Option.value (relax_zrange_gen only_signed possible_values r) r)
913 (machine_wordsize : Z)
914 {t}
915 (E : Expr t)
916 (comment : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_data t -> ToString.OfPHOAS.var_data (type.final_codomain t) -> list string)
917 arg_bounds
918 out_bounds
919 arg_typedefs
920 out_typedefs
921 : M (list string * ToString.ident_infos)
922 := (v <- BoundsPipelineToExtendedResult
923 (static:=static) (all_static:=all_static)
924 type_prefix name
925 with_subst01
926 inline
927 possible_values
928 machine_wordsize
929 E comment arg_bounds out_bounds arg_typedefs out_typedefs;
930 M.ret (v.(lines), v.(ident_infos)))%pipelineM.
931
932 Definition BoundsPipelineToStrings
933 {opts : BoundsPipelineOptions}
934 {output_language_api : ToString.OutputLanguageAPI}
935 {language_naming_conventions : language_naming_conventions_opt}
936 {documentation_options : documentation_options_opt}
937 {output_options : output_options_opt}
938 {internal_static : internal_static_opt}
939 {static : static_opt}
940 {all_static : static_opt}
941 (type_prefix : string)
942 (name : string)
943 (with_subst01 : bool)
944 (inline : bool)
945 (possible_values : list Z)
946 (relax_zrangef : relax_zrange_opt
947 := fun r => Option.value (relax_zrange_gen only_signed possible_values r) r)
948 (machine_wordsize : Z)
949 {t}
950 (E : Expr t)
951 (comment : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_data t -> ToString.OfPHOAS.var_data (type.final_codomain t) -> list string)
952 arg_bounds
953 out_bounds
954 arg_typedefs
955 out_typedefs
956 : ErrorT (list string * ToString.ident_infos)
957 := Debug.eval_result (BoundsPipelineToStringsWithDebug (static:=static) (all_static:=all_static) type_prefix name with_subst01 inline possible_values machine_wordsize E comment arg_bounds out_bounds arg_typedefs out_typedefs).
958
959 Definition BoundsPipelineToStringWithDebug
960 {opts : BoundsPipelineOptions}
961 {output_language_api : ToString.OutputLanguageAPI}
962 {language_naming_conventions : language_naming_conventions_opt}
963 {documentation_options : documentation_options_opt}
964 {output_options : output_options_opt}
965 {internal_static : internal_static_opt}
966 {static : static_opt}
967 {all_static : static_opt}
968 (type_prefix : string)
969 (name : string)
970 (with_subst01 : bool)
971 (inline : bool)
972 (possible_values : list Z)
973 (machine_wordsize : Z)
974 {t}
975 (E : Expr t)
976 (comment : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_data t -> ToString.OfPHOAS.var_data (type.final_codomain t) -> list string)
977 arg_bounds
978 out_bounds
979 arg_typedefs
980 out_typedefs
981 : M (string * ToString.ident_infos)
982 := (E <- BoundsPipelineToStringsWithDebug
983 (static:=static) (all_static:=all_static)
984 type_prefix name
985 with_subst01
986 inline
987 possible_values
988 machine_wordsize
989 E comment arg_bounds out_bounds arg_typedefs out_typedefs;
990 let '(E, types_used) := E in
991 M.ret (ToString.LinesToString E, types_used))%pipelineM.
992
993 Definition BoundsPipelineToString
994 {opts : BoundsPipelineOptions}
995 {output_language_api : ToString.OutputLanguageAPI}
996 {language_naming_conventions : language_naming_conventions_opt}
997 {documentation_options : documentation_options_opt}
998 {output_options : output_options_opt}
999 {internal_static : internal_static_opt}
1000 {static : static_opt}
1001 {all_static : static_opt}
1002 (type_prefix : string)
1003 (name : string)
1004 (with_subst01 : bool)
1005 (inline : bool)
1006 (possible_values : list Z)
1007 (machine_wordsize : Z)
1008 {t}
1009 (E : Expr t)
1010 (comment : type.for_each_lhs_of_arrow ToString.OfPHOAS.var_data t -> ToString.OfPHOAS.var_data (type.final_codomain t) -> list string)
1011 arg_bounds
1012 out_bounds
1013 arg_typedefs
1014 out_typedefs
1015 : ErrorT (string * ToString.ident_infos)
1016 := Debug.eval_result (BoundsPipelineToStringWithDebug (static:=static) (all_static:=all_static) type_prefix name with_subst01 inline possible_values machine_wordsize E comment arg_bounds out_bounds arg_typedefs out_typedefs).
1017
1018 Ltac typedef_var_data_of_bounds t bounds :=
1019 let t := (eval cbv [type.interp type.for_each_lhs_of_arrow ZRange.type.option.interp type.final_codomain] in t) in
1020 let do_prod a b
1021 := lazymatch (eval hnf in bounds) with
1022 | (?b1, ?b2) => let td1 := typedef_var_data_of_bounds a b1 in
1023 let td2 := typedef_var_data_of_bounds b b2 in
1024 uconstr:((td1, td2))
1025 | ?bounds => fail 1 "Unsupported" "non-literal-pair" "bounds" bounds "for" "type" t
1026 end in
1027 match constr:(Set) with
1028 | _ => let td := constr:(_ : @typedef t bounds) in
1029 constr:(Some (@typedef.name t bounds td))
1030 | _
1031 => lazymatch t with
1032 | ZRange.type.base.option.interp ?t => typedef_var_data_of_bounds t bounds
1033 | type.base ?t => typedef_var_data_of_bounds t bounds
1034 | type.arrow ?s ?d => fail 1 "Unsupported" "arrow" "in" "typedef_var_data_of_bounds" t
1035 | ?s -> ?d => fail 1 "Unsupported" "arrow" "in" "typedef_var_data_of_bounds" t
1036 | prod ?a ?b => do_prod a b
1037 | base.type.prod ?a ?b => do_prod a b
1038 | unit => constr:(tt)
1039 | base.type.unit => constr:(tt)
1040 | base.type.option _ => constr:(tt)
1041 | base.type.list _ => constr:(@None string)
1042 | base.type.type_base base.type.Z => constr:(@None string)
1043 | base.type.type_base _ => constr:(tt)
1044 | ?t => fail 1 "Unsupported" "type" "in" "typedef_var_data_of_bounds" t
1045 end
1046 end.
1047
1048 Notation type_of_pipeline result
1049 := ((fun a b possible_values t E arg_bounds out_bounds result' (H : @Pipeline.BoundsPipeline a b possible_values t E arg_bounds out_bounds = result') => t) _ _ _ _ _ _ _ result eq_refl)
1050 (only parsing).
1051 Notation arg_bounds_of_pipeline result
1052 := ((fun a b possible_values t E arg_bounds out_bounds result' (H : @Pipeline.BoundsPipeline a b possible_values t E arg_bounds out_bounds = result') => arg_bounds) _ _ _ _ _ _ _ result eq_refl)
1053 (only parsing).
1054 Notation out_bounds_of_pipeline result
1055 := ((fun a b possible_values t E arg_bounds out_bounds result' (H : @Pipeline.BoundsPipeline a b possible_values t E arg_bounds out_bounds = result') => out_bounds) _ _ _ _ _ _ _ result eq_refl)
1056 (only parsing).
1057 Notation possible_values_of_pipeline result
1058 := ((fun a b possible_values t E arg_bounds out_bounds result' (H : @Pipeline.BoundsPipeline a b possible_values t E arg_bounds out_bounds = result') => possible_values) _ _ _ _ _ _ _ result eq_refl)
1059 (only parsing).
1060 Notation arg_typedefs_via_tc_of_pipeline result
1061 := (match type_of_pipeline result, arg_bounds_of_pipeline result return _ with
1062 | t, arg_bounds
1063 => ltac:(let t := (eval cbv in t) in
1064 let arg_bounds := (eval cbv [arg_bounds] in arg_bounds) in
1065 let v := typedef_var_data_of_bounds (type.for_each_lhs_of_arrow ZRange.type.option.interp t) arg_bounds in
1066 let v := (eval cbv in v) in
1067 exact v)
1068 end) (only parsing).
1069 Notation out_typedefs_via_tc_of_pipeline result
1070 := (match type_of_pipeline result, out_bounds_of_pipeline result return _ with
1071 | t, out_bounds
1072 => ltac:(let t := (eval cbv in t) in
1073 let out_bounds := (eval cbv [out_bounds] in out_bounds) in
1074 let v := typedef_var_data_of_bounds (ZRange.type.base.option.interp (type.final_codomain t)) out_bounds in
1075 let v := (eval cbv in v) in
1076 exact v)
1077 end) (only parsing).
1078 Notation extend_pipeline_with_debug_info result
1079 := ((fun a b possible_values t E arg_bounds out_bounds result' (H : @Pipeline.BoundsPipeline a b possible_values t E arg_bounds out_bounds = result') => @Pipeline.BoundsPipelineWithDebug a b possible_values t E arg_bounds out_bounds) _ _ _ _ _ _ _ result eq_refl)
1080 (only parsing).
1081
1082 Notation FromPipelineToString_gen machine_wordsize is_internal prefix name result
1083 := (fun comment
1084 => ((prefix ++ name)%string,
1085 Debug.bind
1086 (extend_pipeline_with_debug_info result)
1087 (fun E'
1088 => match E' with
1089 | Success E'
1090 => let static : static_opt := _ in
1091 let internal_static : internal_static_opt := _ in
1092 let internal_static := orb static internal_static in
1093 let is_internal' := match is_internal return bool with
1094 | true => internal_static
1095 | false => static
1096 end in
1097 let inline : inline_opt := _ in
1098 let inline_internal : inline_internal_opt := _ in
1099 let inline_internal := orb inline_internal inline in
1100 let inline' := match is_internal return bool with
1101 | true => inline_internal
1102 | false => inline
1103 end in
1104 let adjust_name := convert_to_naming_convention (if is_internal' then private_function_naming_convention else public_function_naming_convention) in
1105 let arg_bounds := arg_bounds_of_pipeline result in
1106 let out_bounds := out_bounds_of_pipeline result in
1107 let arg_typedefs := arg_typedefs_via_tc_of_pipeline result in
1108 let out_typedefs := out_typedefs_via_tc_of_pipeline result in
1109 let E := ToString.ToFunctionLines
1110 (relax_zrange
1111 := fun r => Option.value (relax_zrange_gen (_ : only_signed_opt) (possible_values_of_pipeline result) r) r)
1112 machine_wordsize
1113 true internal_static is_internal' static inline'
1114 prefix (adjust_name (prefix ++ name)%string)
1115 E'
1116 (comment (adjust_name (prefix ++ name)%string))
1117 None
1118 arg_bounds
1119 out_bounds arg_typedefs out_typedefs in
1120 match E with
1121 | inl (lines, infos)
1122 => Debug.ret (Success {| lines := lines; ident_infos := infos; arg_bounds := arg_bounds; out_bounds := out_bounds; arg_typedefs := arg_typedefs ; out_typedefs := out_typedefs ; expr := E' |})
1123 | inr err => Debug.ret (Error (Pipeline.Stringification_failed E' err))
1124 end
1125 | Error err => Debug.ret (Error err)
1126 end)))
1127 (only parsing).
1128
1129 Notation FromPipelineToString machine_wordsize prefix name result
1130 := (FromPipelineToString_gen machine_wordsize false prefix name result) (only parsing).
1131 Notation FromPipelineToInternalString machine_wordsize prefix name result
1132 := (FromPipelineToString_gen machine_wordsize true prefix name result) (only parsing).
1133
1134 Ltac get_all_typedefs _ :=
1135 let all_typedefs := all_instances_of_family (@typedef) in
1136 let res := DynList.map_homogenous ltac:(fun td => constr:(typedef_info_of_typedef td)) all_typedefs in
1137 (* typecheck as a list (to infer the right argument for nil), then strip the cast *)
1138 match constr:(res : list ToString.typedef_info) with ?res => res end.
1139 Notation all_typedefs := (ltac:(let v := get_all_typedefs () in exact v)) (only parsing).
1140
1141 Local Ltac wf_interp_t_step :=
1142 first [ progress destruct_head'_and
1143 | progress cbv [Classes.base Classes.ident Classes.ident_interp Classes.base_interp Classes.exprInfo] in *
1144 | progress intros
1145 | progress rewrite_strat repeat topdown choice (hints interp_extra) (hints interp)
1146 | solve [ typeclasses eauto with nocore interp_extra wf_extra ]
1147 | solve [ typeclasses eauto ]
1148 | break_innermost_match_step
1149 | solve [ typeclasses eauto 100 with nocore wf_extra ] ].
1150
1151 Local Ltac wf_interp_t := repeat wf_interp_t_step.
1152
1153 Class bounds_goodT {t} bounds
1154 := bounds_good :
1155 Proper (type.and_for_each_lhs_of_arrow (t:=t) (@partial.abstract_domain_R base.type ZRange.type.base.option.interp (fun _ => eq)))
1156 bounds.
1157
1158 Class type_goodT (t : type.type base.type)
1159 := type_good : type.andb_each_lhs_of_arrow type.is_base t = true.
1160
1161 #[global]
1162 Hint Extern 1 (type_goodT _) => vm_compute; reflexivity : typeclass_instances.
1163
1164 Local Ltac handle_debug_step_t :=
1165 first [ progress cbv [Debug.bind Debug.ret wrap_debug_rewrite Debug.sequence fst snd] in *
1166 | progress cbn [Debug.eval_result fst snd] in *
1167 | match goal with
1168 | [ H : ?x = (?y, tt) :> DebugM unit |- _ ]
1169 => clear H y
1170 | [ H : ?x = (?y, ?z) :> DebugM _ |- _ ]
1171 => assert (Debug.eval_result x = z) by (now rewrite H);
1172 clear H; subst z; clear y
1173 end ].
1174 Local Ltac handle_debug_t := repeat handle_debug_step_t.
1175
1176 Lemma Wf_wrap_debug_rewrite {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite
1177 (Wf_DoRewrite : forall E, Wf E -> Wf (DoRewrite E))
1178 E
1179 (Hwf : Wf E)
1180 : Wf (Debug.eval_result (@wrap_debug_rewrite debug_rewriting t descr DoRewrite E)).
1181 Proof. cbv [wrap_debug_rewrite Let_In] in *; repeat (wf_interp_t; handle_debug_t). Qed.
1182
1183 Global Hint Resolve Wf_wrap_debug_rewrite : wf wf_extra.
1184 Global Hint Opaque wrap_debug_rewrite : wf wf_extra.
1185
1186 Lemma Interp_wrap_debug_rewrite {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite
1187 (Interp_DoRewrite : forall E, Wf E -> Interp (DoRewrite E) == Interp E)
1188 (Wf_DoRewrite : forall E, Wf E -> Wf (DoRewrite E))
1189 E
1190 (Hwf : Wf E)
1191 : Interp (Debug.eval_result (@wrap_debug_rewrite debug_rewriting t descr DoRewrite E))
1192 == Interp E.
1193 Proof.
1194 cbv [wrap_debug_rewrite Let_In];
1195 repeat (wf_interp_t || rewrite !Interp_DoRewrite || handle_debug_t).
1196 Qed.
1197
1198 #[global]
1199 Hint Rewrite @Interp_wrap_debug_rewrite : interp interp_extra.
1200
1201 Lemma Wf_RewriteAndEliminateDeadAndInline_gen {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return
1202 (Wf_DoRewrite : forall E, Wf E -> Wf (Debug.eval_result (DoRewrite E)))
1203 E
1204 (Hwf : Wf E)
1205 : Wf (Debug.eval_result (@RewriteAndEliminateDeadAndInline_gen debug_rewriting t descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return E)).
1206 Proof. cbv [RewriteAndEliminateDeadAndInline_gen Let_In] in *; repeat (wf_interp_t; handle_debug_t). Qed.
1207
1208 Global Hint Resolve Wf_RewriteAndEliminateDeadAndInline_gen : wf wf_extra.
1209 Global Hint Opaque RewriteAndEliminateDeadAndInline_gen : wf wf_extra.
1210
1211 Lemma Interp_RewriteAndEliminateDeadAndInline_gen {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return
1212 (Interp_DoRewrite : forall E, Wf E -> Interp (Debug.eval_result (DoRewrite E)) == Interp E)
1213 (Wf_DoRewrite : forall E, Wf E -> Wf (Debug.eval_result (DoRewrite E)))
1214 E
1215 (Hwf : Wf E)
1216 : Interp (Debug.eval_result (@RewriteAndEliminateDeadAndInline_gen debug_rewriting t descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return E))
1217 == Interp E.
1218 Proof.
1219 cbv [RewriteAndEliminateDeadAndInline_gen Let_In];
1220 repeat (wf_interp_t || rewrite !Interp_DoRewrite || handle_debug_t).
1221 Qed.
1222
1223 #[global]
1224 Hint Rewrite @Interp_RewriteAndEliminateDeadAndInline_gen : interp interp_extra.
1225
1226 Lemma Wf_RewriteAndEliminateDeadAndInline {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return
1227 (Wf_DoRewrite : forall E, Wf E -> Wf (DoRewrite E))
1228 E
1229 (Hwf : Wf E)
1230 : Wf (Debug.eval_result (@RewriteAndEliminateDeadAndInline debug_rewriting t descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return E)).
1231 Proof. cbv [RewriteAndEliminateDeadAndInline Let_In]; wf_interp_t. Qed.
1232
1233 Global Hint Resolve Wf_RewriteAndEliminateDeadAndInline : wf wf_extra.
1234 Global Hint Opaque RewriteAndEliminateDeadAndInline : wf wf_extra.
1235
1236 Lemma Interp_RewriteAndEliminateDeadAndInline {debug_rewriting : debug_rewriting_opt} {t} descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return
1237 (Interp_DoRewrite : forall E, Wf E -> Interp (DoRewrite E) == Interp E)
1238 (Wf_DoRewrite : forall E, Wf E -> Wf (DoRewrite E))
1239 E
1240 (Hwf : Wf E)
1241 : Interp (Debug.eval_result (@RewriteAndEliminateDeadAndInline debug_rewriting t descr DoRewrite with_dead_code_elimination with_subst01 with_let_bind_return E))
1242 == Interp E.
1243 Proof.
1244 cbv [RewriteAndEliminateDeadAndInline Let_In];
1245 repeat (wf_interp_t || rewrite !Interp_DoRewrite).
1246 Qed.
1247
1248 #[global]
1249 Hint Rewrite @Interp_RewriteAndEliminateDeadAndInline : interp interp_extra.
1250
1251 Local Notation interp_correctT V1 V2 arg_bounds
1252 := (forall arg1 arg2
1253 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1254 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1255 type.app_curried V1 arg1 = type.app_curried V2 arg2)
1256 (only parsing).
1257
1258 Local Lemma interp_correctT_trans {t} (arg_bounds : type.for_each_lhs_of_arrow _ t)
1259 : Transitive (fun x y => interp_correctT x y arg_bounds).
1260 Proof using Type.
1261 intros V1 V2 V3 H1 H2; intros arg1 arg2 Harg12 Harg1; etransitivity; [ eapply H1 | eapply H2 ]; clear H1 H2; try eassumption.
1262 { etransitivity; (idtac + symmetry); eassumption. }
1263 { rewrite <- Harg12; assumption. }
1264 Qed.
1265
1266 Local Lemma correct_of_final_iff_correct_of_initial {t} {rv intermediate e : Expr t} {arg_bounds out_bounds}
1267 (Hintermediate : interp_correctT (Interp intermediate) (Interp e) arg_bounds)
1268 (Hwf : Wf e)
1269 : ((forall arg1 arg2
1270 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1271 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1272 ZRange.type.base.option.is_bounded_by out_bounds (type.app_curried (Interp rv) arg1) = true
1273 /\ type.app_curried (Interp rv) arg1 = type.app_curried (Interp intermediate) arg2)
1274 /\ Wf rv)
1275 <-> ((forall arg1 arg2
1276 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1277 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1278 ZRange.type.base.option.is_bounded_by out_bounds (type.app_curried (Interp e) arg1) = true
1279 /\ type.app_curried (Interp rv) arg1 = type.app_curried (Interp e) arg2)
1280 /\ Wf rv).
1281 Proof using Type.
1282 split; intros [H1 H2]; (split; [ | exact H2 ]);
1283 repeat (let x := fresh in intro x; specialize (H1 x));
1284 destruct H1 as [H1' H2']; (split; [ rewrite <- H1', ?H2'; apply f_equal | ]);
1285 rewrite ?H2';
1286 try (erewrite ?Hintermediate; [ | (idtac + symmetry); eassumption | ]);
1287 try reflexivity.
1288 all: repeat match goal with
1289 | [ |- type.app_curried ?f ?x = type.app_curried ?f ?y ]
1290 => apply type.app_curried_Proper; [ now apply expr.Wf_Interp_Proper | (idtac + symmetry); assumption ]
1291 | [ H' : ?R ?y ?x |- type.andb_bool_for_each_lhs_of_arrow _ _ ?x = true ]
1292 => rewrite <- H'; assumption
1293 end.
1294 Qed.
1295
1296 (** It would be nice if [eauto] were faster, cf
1297 COQBUG(https://github.com/coq/coq/issues/12052). It doesn't
1298 share subterms, though, so we carefully build the proof term
1299 with forward reasoning *)
1300 Local Ltac fwd Hrv Hwf Hinterp :=
1301 cbv beta iota delta [Debug.sequence] in Hrv;
1302 (*let t := type of Hrv in idtac t;*)
1303 lazymatch type of Hrv with
1304 | Success ?x = Success ?y
1305 => let H' := fresh in
1306 assert (H : x = y) by (clear -Hrv; congruence);
1307 clear Hrv; rename H into Hrv
1308 | context G[(let x : ?T := ?v in @?F x) ?y]
1309 => let G' := context G[let x : T := v in F x y] in
1310 let G' := (eval cbv beta in G') in
1311 change G' in Hrv;
1312 fwd Hrv Hwf Hinterp
1313 | context G[Debug.eval_result (let x := ?y in @?F x)]
1314 => let G' := context G[let x := y in Debug.eval_result (F x)] in
1315 let G' := (eval cbv beta in G') in
1316 change G' in Hrv;
1317 fwd Hrv Hwf Hinterp
1318 | context G[Debug.eval_result (Debug.ret ?v)]
1319 => let G' := context G[v] in
1320 change G' in Hrv;
1321 fwd Hrv Hwf Hinterp
1322 | Debug.eval_result (@Debug.bind ?dbg ?A ?B ?x ?y) = _
1323 => rewrite (@Debug.eval_result_bind dbg A B x y) in Hrv;
1324 fwd Hrv Hwf Hinterp
1325 | (let z := Debug.eval_result (@Debug.bind ?dbg ?A ?B ?x ?y) in _) = _
1326 => rewrite (@Debug.eval_result_bind dbg A B x y) in Hrv;
1327 fwd Hrv Hwf Hinterp
1328 | (let x := @inl ?A ?B ?v in ?F) = Success ?rv
1329 => let x' := fresh in
1330 change ((let x' := v in match @inl A B x' with x => F end) = Success rv) in Hrv;
1331 fwd Hrv Hwf Hinterp
1332 | (let x := @inr ?A ?B ?v in ?F) = Success ?rv
1333 => let x' := fresh in
1334 change ((let x' := v in match @inr A B x' with x => F end) = Success rv) in Hrv;
1335 fwd Hrv Hwf Hinterp
1336 | (let x := let y := ?v in ?F1 in @?F2 x) = ?rhs
1337 => change ((let y := v in let x := F1 in F2 x) = rhs) in Hrv;
1338 fwd Hrv Hwf Hinterp
1339 | (let x : Expr _ := ?v in ?F) = Success ?rv
1340 => (tryif is_var v
1341 then (change (match v with x => F end = Success rv) in Hrv;
1342 fwd Hrv Hwf Hinterp)
1343 else
1344 (let e' := fresh "e" in
1345 pose v as e';
1346 change (match e' with x => F end = Success rv) in Hrv;
1347 let e := lazymatch type of Hwf with Wf ?e => e | ?T => constr_fail_with ltac:(fun _ => fail 1 "Expected Wf, got" T) end in
1348 let Hwf' := fresh "Hwf" in
1349 let Hinterp' := fresh "Hinterp" in
1350 lazymatch type of Hinterp with
1351 | interp_correctT _ ?rhs ?arg_bounds
1352 => assert (Hwf' : Wf e');
1353 [ | assert (Hinterp' : interp_correctT (Interp e') rhs arg_bounds) ];
1354 [ clear Hrv; subst e' ..
1355 | lazymatch type of Hrv with
1356 | context[e] => idtac (* keep interp and wf *)
1357 | _ => clear Hwf Hinterp; try clear e
1358 end;
1359 fwd Hrv Hwf' Hinterp' ]
1360 | ?T => constr_fail_with ltac:(fun _ => fail 1 "Expected related, got" T)
1361 end))
1362 | (let x : Expr _ + _ := ?v in ?F) = Success ?rv
1363 => (tryif is_var v
1364 then (change (match v with x => F end = Success rv) in Hrv;
1365 fwd Hrv Hwf Hinterp)
1366 else
1367 (let H := fresh in
1368 let e' := fresh "e" in
1369 destruct v as [e'|e'] eqn:H;
1370 cbv beta iota in Hrv;
1371 [ apply CheckedPartialEvaluateWithBounds_Correct in H;
1372 [ let Hwf' := fresh "Hwf" in
1373 rewrite (correct_of_final_iff_correct_of_initial Hinterp) in H by assumption;
1374 destruct H as [? Hwf']; split_and;
1375 lazymatch type of Hinterp with
1376 | interp_correctT _ ?rhs ?arg_bounds
1377 => let Hinterp' := fresh "Hinterp" in
1378 assert (Hinterp' : interp_correctT (Interp e') rhs arg_bounds) by assumption;
1379 fwd Hrv Hwf' Hinterp'
1380 end
1381 | clear H; try solve [ assumption | congruence | apply relax_zrange_gen_good ] .. ]
1382 | cbv beta iota zeta in Hrv;
1383 first [ clear -Hrv;
1384 repeat (rewrite ?Debug.eval_result_bind in Hrv; cbv [Debug.ret] in Hrv; cbn [fst snd Debug.eval_result] in Hrv);
1385 break_innermost_match_hyps;
1386 discriminate
1387 | let T := type of Hrv in
1388 idtac "WARNING: Could not discriminate on" T ] ]))
1389 | (let x : unit := ?v in ?F) = Success ?rv
1390 => (tryif unify v tt then idtac else destruct v);
1391 change (match tt with x => F end = Success rv) in Hrv;
1392 fwd Hrv Hwf Hinterp
1393 | (let x : ?T := ?v in ?F) = Success ?rv
1394 => let rec good_ty T
1395 := lazymatch T with
1396 | bool => idtac
1397 | zrange => idtac
1398 | RewriterOptions => idtac
1399 | Flat.expr _ => idtac
1400 | ?A -> ?B => good_ty A; good_ty B
1401 | option ?A => good_ty A
1402 | (?A * ?B)%type => good_ty A; good_ty B
1403 | _ => fail 0 "Unrecognized type" T "in" v
1404 end in
1405 tryif good_ty T
1406 then (change (match v with x => F end = Success rv) in Hrv;
1407 fwd Hrv Hwf Hinterp)
1408 else (let T := type of Hrv in idtac T)
1409 | ?T => idtac T
1410 end.
1411 Local Ltac fwd_side_condition_step :=
1412 first [ match goal with
1413 | [ |- Wf (Debug.eval_result (RewriteAndEliminateDeadAndInline _ _ _ _ _ _))]
1414 => apply Wf_RewriteAndEliminateDeadAndInline
1415 | [ |- type.app_curried (expr.Interp _ (Debug.eval_result (RewriteAndEliminateDeadAndInline _ _ _ _ _ _))) _ = _ ]
1416 => rewrite Interp_RewriteAndEliminateDeadAndInline
1417 end
1418 | assumption
1419 | progress intros
1420 | solve [ auto with nocore wf wf_extra ]
1421 | progress (rewrite_strat repeat topdown hints interp_extra)
1422 | match goal with
1423 | [ |- ?x = ?x ] => reflexivity
1424 | [ |- context[match ?x with Some _ => _ | _ => _ end] ] => destruct x
1425 | [ |- context[match ?x with (a, b) => _ end] ] => destruct x
1426 | [ |- context[match ?x with [] => _ | _ => _ end] ] => destruct x
1427 | [ |- context[match ?x with true => _ | _ => _ end] ] => destruct x
1428 | [ |- type.app_curried (Interp (PartialEvaluateWithListInfoFromBounds _ _)) _ = _ ]
1429 => erewrite Interp_PartialEvaluateWithListInfoFromBounds by eassumption
1430 end
1431 | progress cbv beta zeta in *
1432 | progress destruct_head'_and ].
1433
1434 Local Strategy -100 [Debug.eval_result Debug.bind Debug.sequence fst snd Debug.map Debug.ret].
1435 Lemma BoundsPipeline_correct
1436 {opts : BoundsPipelineOptions}
1437 {translate_to_fancy_correct : translate_to_fancy_opt_correct}
1438 (with_subst01 : bool)
1439 (possible_values : list Z)
1440 {t}
1441 (e : Expr t)
1442 arg_bounds
1443 out_bounds
1444 {type_good : type_goodT t}
1445 rv
1446 (Hrv : BoundsPipeline with_subst01 possible_values e arg_bounds out_bounds = Success rv)
1447 (Hwf : Wf e)
1448 : (forall arg1 arg2
1449 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1450 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1451 ZRange.type.base.option.is_bounded_by out_bounds (type.app_curried (Interp rv) arg1) = true
1452 /\ type.app_curried (Interp rv) arg1 = type.app_curried (Interp e) arg2)
1453 /\ Wf rv.
1454 Proof.
1455 assert (Hbounds_Proper : bounds_goodT arg_bounds) by (apply type.and_eqv_for_each_lhs_of_arrow_not_higher_order, type_good).
1456 assert (Hinterp : interp_correctT (Interp e) (Interp e) arg_bounds)
1457 by (intros; apply type.app_curried_Proper; [ now apply expr.Wf_Interp_Proper | assumption ]).
1458 (* talk about initial interp rather than final one *)
1459 rewrite (correct_of_final_iff_correct_of_initial Hinterp) by assumption.
1460 pose proof Hwf as Hwf'. (* keep an extra copy so it's not cleared *)
1461 cbv [translate_to_fancy_opt_correct] in *.
1462 cbv beta iota delta [BoundsPipeline BoundsPipelineWithDebug PreBoundsPipeline Let_In] in Hrv.
1463 cbv beta iota delta [Debug.sequence] in Hrv.
1464 fwd Hrv Hwf Hinterp; [ repeat fwd_side_condition_step .. | subst ].
1465 solve [ eauto using conj with nocore ].
1466 Qed.
1467
1468 Definition BoundsPipeline_correct_transT
1469 {t}
1470 arg_bounds
1471 out_bounds
1472 (InterpE : type.interp base.interp t)
1473 (rv : Expr t)
1474 := (forall arg1 arg2
1475 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1476 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1477 ZRange.type.base.option.is_bounded_by out_bounds (type.app_curried (Interp rv) arg1) = true
1478 /\ type.app_curried (Interp rv) arg1 = type.app_curried InterpE arg2)
1479 /\ Wf rv.
1480
1481 Lemma BoundsPipeline_correct_trans
1482 {opts : BoundsPipelineOptions}
1483 {translate_to_fancy_correct : translate_to_fancy_opt_correct}
1484 (with_subst01 : bool)
1485 (possible_values : list Z)
1486 {t}
1487 (e : Expr t)
1488 arg_bounds out_bounds
1489 {type_good : type_goodT t}
1490 (InterpE : type.interp base.interp t)
1491 (InterpE_correct_and_Wf
1492 : (forall arg1 arg2
1493 (Harg12 : type.and_for_each_lhs_of_arrow (@type.eqv) arg1 arg2)
1494 (Harg1 : type.andb_bool_for_each_lhs_of_arrow (@ZRange.type.option.is_bounded_by) arg_bounds arg1 = true),
1495 type.app_curried (Interp e) arg1 = type.app_curried InterpE arg2)
1496 /\ Wf e)
1497 rv
1498 (Hrv : BoundsPipeline (*with_dead_code_elimination*) with_subst01 possible_values e arg_bounds out_bounds = Success rv)
1499 : BoundsPipeline_correct_transT arg_bounds out_bounds InterpE rv.
1500 Proof.
1501 destruct InterpE_correct_and_Wf as [InterpE_correct Hwf].
1502 split; [ intros arg1 arg2 Harg12 Harg1; erewrite <- InterpE_correct | ]; try eapply @BoundsPipeline_correct;
1503 lazymatch goal with
1504 | [ |- type.andb_bool_for_each_lhs_of_arrow _ _ _ = true ] => eassumption
1505 | [ |- _ = Success _ ] => eassumption
1506 | _ => try assumption
1507 end; try eassumption.
1508 etransitivity; try eassumption; symmetry; assumption.
1509 Qed.
1510
1511 Ltac solve_bounds_good :=
1512 repeat first [ progress cbv [bounds_goodT Proper partial.abstract_domain_R type_base] in *
1513 | progress cbn [type.and_for_each_lhs_of_arrow type.for_each_lhs_of_arrow partial.abstract_domain type.interp ZRange.type.base.option.interp type.related] in *
1514 | exact I
1515 | apply conj
1516 | exact eq_refl ].
1517
1518 Module Export Instances.
1519 (*Global Existing Instance default_low_level_rewriter_method.*)
1520
1521 Global Instance bounds0_good {t : base.type} {bounds} : @bounds_goodT t bounds.
1522 Proof. solve_bounds_good. Qed.
1523
1524 Global Instance bounds1_good {s d : base.type} {bounds} : @bounds_goodT (s -> d) bounds.
1525 Proof. solve_bounds_good. Qed.
1526
1527 Global Instance bounds2_good {a b D : base.type} {bounds} : @bounds_goodT (a -> b -> D) bounds.
1528 Proof. solve_bounds_good. Qed.
1529
1530 Global Instance bounds3_good {a b c D : base.type} {bounds} : @bounds_goodT (a -> b -> c -> D) bounds.
1531 Proof. solve_bounds_good. Qed.
1532 End Instances.
1533 End Pipeline.
1534 Export Pipeline.M.Notations.
1535
1536 Module Export Hints.
1537 (* for storing the results of prove_pipeline_wf *)
1538 Create HintDb wf_op_cache discriminated.
1539
1540 Export Pipeline.Instances.
1541 #[global]
1542 Hint Extern 1 (@Pipeline.bounds_goodT _ _) => solve [ Pipeline.solve_bounds_good ] : typeclass_instances.
1543 Global Strategy -100 [type.interp ZRange.type.option.interp ZRange.type.base.option.interp GallinaReify.Reify_as GallinaReify.reify type_base].
1544 Global Strategy -10 [type.app_curried type.for_each_lhs_of_arrow type.and_for_each_lhs_of_arrow type.related type.interp Language.Compilers.base.interp base.base_interp type.andb_bool_for_each_lhs_of_arrow fst snd ZRange.type.option.is_bounded_by].
1545 Global Strategy 1000 [Pipeline.BoundsPipeline].
1546 End Hints.
1547
1548 Module PipelineTactics.
1549 Export Hints.
1550
1551 Ltac solve_side_conditions_of_BoundsPipeline_correct :=
1552 repeat first [ progress cbn [fst snd] in *
1553 | match goal with
1554 | [ |- ?x = ?x ] => reflexivity
1555 | [ |- unit ] => constructor
1556 | [ |- True ] => constructor
1557 | [ |- context[andb _ _ = true] ] => rewrite Bool.andb_true_iff
1558 | [ |- and _ _ ] => apply conj
1559 | [ |- ?x = ?y ] => is_evar y; reflexivity
1560 | [ |- ZRange.type.base.option.is_bounded_by _ _ = true ] => assumption
1561 end ].
1562
1563 Ltac do_unfolding :=
1564 cbv [type.interp ZRange.type.option.interp ZRange.type.base.option.interp GallinaReify.Reify_as GallinaReify.reify type_base] in *;
1565 cbn [type.app_curried type.for_each_lhs_of_arrow type.and_for_each_lhs_of_arrow type.related type.interp Language.Compilers.base.interp base.base_interp type.andb_bool_for_each_lhs_of_arrow fst snd ZRange.type.option.is_bounded_by] in *.
1566
1567 Ltac curry_args lem :=
1568 let T := type of lem in
1569 lazymatch (eval cbn [fst snd] in T) with
1570 | forall x : ?A * ?B, _
1571 => let a := fresh in
1572 let b := fresh in
1573 curry_args (fun (a : A) (b : B) => lem (a, b))
1574 | forall x : unit, _
1575 => curry_args (lem tt)
1576 | forall x : True, _
1577 => curry_args (lem I)
1578 | forall x : ?A /\ ?B, _
1579 => let a := fresh in
1580 let b := fresh in
1581 curry_args (fun (a : A) (b : B) => lem (conj a b))
1582 | forall x : ?A, _
1583 => constr:(fun x : A => ltac:(let v := curry_args (lem x) in exact v))
1584 | ?T
1585 => let T' := (eval cbn [fst snd] in T) in
1586 constr:(lem : T')
1587 end.
1588
1589 Create HintDb relax_zrange_gen_good discriminated.
1590 #[global]
1591 Hint Resolve relax_zrange_gen_good : relax_zrange_gen_good.
1592
1593 Ltac use_compilers_correctness Hres :=
1594 eapply Pipeline.BoundsPipeline_correct in Hres;
1595 [ | try typeclasses eauto with core relax_zrange_gen_good typeclass_instances.. ];
1596 [ do_unfolding;
1597 let Hres' := fresh in
1598 destruct Hres as [Hres' _] (* remove Wf conjunct *);
1599 let lem' := curry_args Hres' in
1600 pose proof lem' as Hres; clear Hres';
1601 let H1 := fresh in
1602 let H2 := fresh in
1603 edestruct Hres as [H1 H2]; revgoals;
1604 [ first [ ((* first try to be smart about which side of the lemma we use *)
1605 lazymatch goal with
1606 | [ |- _ = true ] => eapply H1
1607 | [ |- _ = _ ] => erewrite H2
1608 | [ |- ?list_Z_bounded_by _ _ ] => eapply H1
1609 end)
1610 (* but if that doesn't work, try both ways *)
1611 | eapply H1
1612 | erewrite H2
1613 | print_context_and_goal ();
1614 let G := match goal with |- ?G => G end in
1615 fail 1 "Could not figure out how to prove" G ];
1616 clear H1 H2 Hres
1617 | .. ];
1618 solve_side_conditions_of_BoundsPipeline_correct
1619 | lazymatch goal with |- Wf _ => idtac end;
1620 repeat match goal with
1621 | [ |- Wf (expr.APP _ _) ] => apply expr.Wf_APP
1622 end;
1623 try typeclasses eauto with nocore wf_extra wf_gen_cache;
1624 try typeclasses eauto with nocore wf wf_gen_cache ].
1625
1626 Ltac prove_pipeline_wf _ :=
1627 lazymatch goal with
1628 | [ Hres : _ = Success _ |- Wf _ ]
1629 => eapply Pipeline.BoundsPipeline_correct
1630 end;
1631 repeat first [ match goal with
1632 | [ Hres : _ = Success ?res |- _ = Success ?res ] => refine Hres (* eassumption is too slow *)
1633 | [ |- Wf (expr.APP _ _) ] => apply expr.Wf_APP
1634 | [ |- Wf (GallinaReify.Reify_as _ _) ] => apply expr.Wf_Reify_as
1635 end
1636 | exact I
1637 | exact _
1638 | solve [ auto with wf_gen_cache ] ].
1639 End PipelineTactics.