Debian Codegraph @

src/Assembly/Equivalence.v

raw
1 From Coq Require Import String.
2 From Coq Require Import List.
3 From Coq Require Import ZArith.
4 From Coq Require Import NArith.
5 Require Import Crypto.Assembly.Syntax.
6 Require Import Crypto.Assembly.Parse.
7 Require Import Crypto.Assembly.Symbolic.
8 Require Import Crypto.Util.Strings.Parse.Common.
9 Require Import Crypto.Util.ErrorT.
10 Require Import Crypto.Util.Strings.String.
11 Require Import Crypto.Language.API.
12 Require Import Crypto.Language.APINotations.
13 Require Import Crypto.AbstractInterpretation.ZRange.
14 Require Import Crypto.Stringification.Language.
15 Require Import Crypto.Util.Strings.Show.
16 Require Import Crypto.Util.Option.
17 Require Import Crypto.Util.NUtil.Sorting.
18 Require Import Crypto.Util.ListUtil.
19 Require Import Crypto.Util.ListUtil.FoldMap.
20 Require Import Crypto.Util.ListUtil.CombineExtend.
21 Require Import Crypto.Util.ListUtil.RemoveN.
22 Require Import Crypto.Util.MSets.MSetN.
23 Require Import Crypto.Util.Sum.
24 Require Import Crypto.Util.ErrorT.List.
25 Require Import Crypto.Util.OptionList.
26 Require Import Crypto.Util.Notations.
27 Import API.Compilers APINotations.Compilers AbstractInterpretation.ZRange.Compilers.
28 Import ListNotations.
29 Local Open Scope string_scope.
30 Local Open Scope list_scope.
31
32
33 (** Permit labels to have arbitrary suffixes *)
34 Class assembly_labels_fuzzy_suffixes_opt := assembly_labels_fuzzy_suffixes : bool.
35 #[global]
36 Typeclasses Opaque assembly_labels_fuzzy_suffixes_opt.
37 Definition default_assembly_labels_fuzzy_suffixes : assembly_labels_fuzzy_suffixes_opt := true.
38 (** Permit labels to have arbitrary prefixes *)
39 Class assembly_labels_fuzzy_prefixes_opt := assembly_labels_fuzzy_prefixes : bool.
40 #[global]
41 Typeclasses Opaque assembly_labels_fuzzy_prefixes_opt.
42 Definition default_assembly_labels_fuzzy_prefixes : assembly_labels_fuzzy_prefixes_opt := true.
43 (** List of registers used for outputs/inputs *)
44 Class assembly_calling_registers_opt := assembly_calling_registers' : option (list REG).
45 #[global]
46 Typeclasses Opaque assembly_calling_registers_opt.
47 Definition default_assembly_calling_registers := [rdi;rsi;rdx;rcx;r8;r9].
48 Definition assembly_calling_registers {v : assembly_calling_registers_opt} : list REG
49 := Option.value v default_assembly_calling_registers.
50 (** List of callee-saved / non-volatile registers *)
51 Variant assembly_callee_saved_registers_opt := Microsoft_x64 | System_V_AMD64 | explicit_registers (_ : list REG).
52 Existing Class assembly_callee_saved_registers_opt.
53 (* https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention *)
54 (* The registers RAX, RCX, RDX, R8, R9, R10, R11 are considered volatile (caller-saved).[22]
55
56 The registers RBX, RBP, RDI, RSI, RSP, R12, R13, R14, and R15 are considered nonvolatile (callee-saved).[22]
57
58 -----
59 [22] https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170&viewFallbackFrom=vs-2019#callercallee-saved-registers *)
60 Definition microsoft_x64_assembly_callee_saved_registers := [rbx;rbp;rdi;rsi;rsp;r12;r13;r14;r15].
61 (* https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI *)
62 (* If the callee wishes to use registers RBX, RSP, RBP, and R12–R15, it must restore their original values before returning control to the caller. All other registers must be saved by the caller if it wishes to preserve their values.[25]: 16
63
64 [25] Michael Matz; Jan Hubička; Andreas Jaeger; et al., eds. (2018-01-28). "System V Application Binary Interface: AMD64 Architecture Processor Supplement (With LP64 and ILP32 Programming Models) Version 1.0" (PDF). 1.0. https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf *)
65 Definition system_v_amd64_assembly_callee_saved_registers := [rbx;rsp;rbp;r12;r13;r14;r15].
66 Definition default_assembly_callee_saved_registers := System_V_AMD64.
67 Definition assembly_callee_saved_registers {v : assembly_callee_saved_registers_opt} : list REG
68 := match v with
69 | Microsoft_x64 => microsoft_x64_assembly_callee_saved_registers
70 | System_V_AMD64 => system_v_amd64_assembly_callee_saved_registers
71 | explicit_registers ls => ls
72 end.
73 (** Are output arrays considered to come before input arrays, or after them? *)
74 Class assembly_output_first_opt := assembly_output_first : bool.
75 #[global]
76 Typeclasses Opaque assembly_output_first_opt.
77 (** Should we assign registers to the arguments in left-to-right or right-to-left order? *)
78 Class assembly_argument_registers_left_to_right_opt := assembly_argument_registers_left_to_right : bool.
79 #[global]
80 Typeclasses Opaque assembly_argument_registers_left_to_right_opt.
81 (** Stack size (in bytes) *)
82 Class assembly_stack_size_opt := assembly_stack_size' : option N.
83 #[global]
84 Typeclasses Opaque assembly_stack_size_opt.
85 (** The stack size is taken to be the given command line argument, or
86 else inferred to be assembly_stack_red_zone plus the maximum
87 statically knowable increase to rsp (via `push`, `pop`, `sub`,
88 `add`, and `lea` instructions) *)
89 Fixpoint assembly_stack_size_at (cur_stack_size : Z) (asm : _) : list Z
90 := match asm with
91 | [] => []
92 | l :: asm
93 => let cng := match l.(rawline) with
94 | INSTR {| Syntax.op := sub ; args := [reg rsp; Syntax.const n] |}
95 => n
96 | INSTR {| Syntax.op := Syntax.add ; args := [reg rsp; Syntax.const n] |}
97 => -n
98 | INSTR {| Syntax.op := lea ; args := [reg rsp; Syntax.mem {| mem_base_reg := Some rsp ; mem_offset := Some n ; mem_scale_reg := None ; mem_bits_access_size := None |}] |}
99 => -n
100 | INSTR {| Syntax.op := lea ; args := [reg rsp; Syntax.mem {| mem_base_reg := Some rsp ; mem_offset := Some n ; mem_scale_reg := None ; mem_bits_access_size := Some sz |}] |}
101 => if (sz =? 64)%N
102 then -n
103 else 0
104 | INSTR instr
105 => match Syntax.operation_size instr with
106 | Some s
107 => match instr with
108 | {| Syntax.op := push ; args := [_] |}
109 => Z.of_N s / 8
110 | {| Syntax.op := pop ; args := [_] |}
111 => -Z.of_N s / 8
112 | _ => 0
113 end
114 | None => 0
115 end
116 | _ => 0
117 end in
118 let new_stack_size := cur_stack_size + cng in
119 new_stack_size :: assembly_stack_size_at new_stack_size asm
120 end%Z.
121 (** According to https://en.m.wikipedia.org/wiki/Red_zone_(computing)
122
123 Whether a red zone is present depends on the calling convention. x86-64
124 systems that use the System V AMD64 ABI (including Linux and macOS) use a
125 128-byte red zone that begins directly under the current value of the stack
126 pointer.[1][2] The OpenRISC toolchain assumes a 128-byte red zone.[3]
127 Microsoft Windows does not have the concept of a red zone on x86.[4] In
128 fact, the ABI explicitly states that the memory beyond the stack pointer is
129 volatile and may be overwritten by debuggers or interrupt handlers.[5][6]
130 However, Microsoft Windows has a red zone of 16 bytes on IA-64, 8 bytes on
131 AArch32, and 16 bytes on AArch64.[6]
132 *)
133 Definition microsoft_x64_assembly_stack_red_zone : N := 0.
134 Definition system_v_amd64_assembly_stack_red_zone : N := 128.
135 Definition assembly_stack_red_zone {calling_convention : assembly_callee_saved_registers_opt} : N
136 := match calling_convention with
137 | Microsoft_x64 => microsoft_x64_assembly_stack_red_zone
138 | System_V_AMD64 => system_v_amd64_assembly_stack_red_zone
139 | explicit_registers _ => 0%N
140 end.
141 Definition assembly_stack_size {calling_convention : assembly_callee_saved_registers_opt} {v : assembly_stack_size_opt} (asm : _) : N
142 := match v with
143 | Some v => v
144 | None => let red_zone := Z.of_N assembly_stack_red_zone in
145 Z.to_N (fold_right Z.max red_zone (assembly_stack_size_at red_zone asm))
146 end.
147
148 Class assembly_conventions_opt :=
149 { #[global] assembly_calling_registers_ :: assembly_calling_registers_opt
150 ; #[global] assembly_stack_size_ :: assembly_stack_size_opt
151 ; #[global] assembly_output_first_ :: assembly_output_first_opt
152 ; #[global] assembly_argument_registers_left_to_right_ :: assembly_argument_registers_left_to_right_opt
153 ; #[global] assembly_callee_saved_registers_ :: assembly_callee_saved_registers_opt
154 ; #[global] assembly_labels_fuzzy_suffixes_ :: assembly_labels_fuzzy_suffixes_opt
155 ; #[global] assembly_labels_fuzzy_prefixes_ :: assembly_labels_fuzzy_prefixes_opt
156 }.
157 Definition default_assembly_conventions : assembly_conventions_opt
158 := {| assembly_calling_registers_ := None
159 ; assembly_stack_size_ := None
160 ; assembly_output_first_ := true
161 ; assembly_argument_registers_left_to_right_ := true
162 ; assembly_callee_saved_registers_ := default_assembly_callee_saved_registers
163 ; assembly_labels_fuzzy_suffixes_ := default_assembly_labels_fuzzy_suffixes
164 ; assembly_labels_fuzzy_prefixes_ := default_assembly_labels_fuzzy_prefixes
165 |}.
166
167 Module Export Options.
168 Export Assembly.Symbolic.Options.
169 Class equivalence_checker_options_opt :=
170 { assembly_conventions_ : assembly_conventions_opt
171 ; symbolic_options_ : symbolic_options_opt
172 }.
173 Definition default_equivalence_checker_options : equivalence_checker_options_opt
174 := {| assembly_conventions_ := default_assembly_conventions
175 ; symbolic_options_ := default_symbolic_options
176 |}.
177 End Options.
178
179 Module Export EquivalenceCheckerHints.
180 Export Assembly.Symbolic.Hints.
181 Global Existing Instances
182 Build_equivalence_checker_options_opt
183 assembly_conventions_
184 symbolic_options_
185 .
186 #[global]
187 Hint Cut [
188 ( _ * )
189 (assembly_conventions_
190 | symbolic_options_
191 ) ( _ * )
192 (Build_equivalence_checker_options_opt
193 )
194 ] : typeclass_instances.
195 End EquivalenceCheckerHints.
196
197 Global Instance show_assembly_callee_saved_registers_opt : Show assembly_callee_saved_registers_opt | 10
198 := fun v => match v with
199 | Microsoft_x64 => "Microsoft x64"
200 | System_V_AMD64 => "System V AMD64"
201 | explicit_registers ls => show ls
202 end.
203
204 Definition parse_assembly_callee_saved_registers_opt : ParserAction assembly_callee_saved_registers_opt
205 := ((parse_strs
206 [(show Microsoft_x64, Microsoft_x64); ("Microsoft x64", Microsoft_x64); ("Microsoft_x64", Microsoft_x64); ("Microsoft-x64", Microsoft_x64); ("microsoft", Microsoft_x64); ("Microsoft", Microsoft_x64)
207 ; (show System_V_AMD64, System_V_AMD64); ("System V", System_V_AMD64); ("System_V_AMD64", System_V_AMD64); ("system-v", System_V_AMD64); ("System-V-AMD64", System_V_AMD64); ("AMD64", System_V_AMD64); ("amd64", System_V_AMD64); ("system v", System_V_AMD64)])
208 ||->{fun v => match v with inl v => v | inr ls => explicit_registers ls end}
209 parse_comma_list parse_REG)%parse.
210
211 (** N.B. The printer of these error messages will always know the
212 assembly function lines and the AST used for equivalence checking, so
213 these error messages need not include this information. However, they
214 should include as much information as possible about the local source
215 of the inequivalence. It's not out of the question, for example, to
216 include enough information in the error message to generate .dot files
217 of the equivalence graphs. If desired, we can parameterize the error
218 printing functions on command-lines options indicating how verbose to
219 be in printing the error message. *)
220 Inductive EquivalenceCheckingError :=
221 | Symbolic_execution_failed (_ : Symbolic.error) (_ : symbolic_state)
222 | Internal_error_output_load_failed (_ : option Symbolic.error) (_ : list ((REG + idx) + idx)) (_ : symbolic_state)
223 | Internal_error_extra_input_arguments (t : API.type) (unused_arguments : list (idx + list idx))
224 | Internal_error_lingering_memory (_ : symbolic_state)
225 | Internal_error_LoadOutputs_length_mismatch (outputaddrs : list ((REG + idx) + idx)) (output_types : list (option nat))
226 | Not_enough_registers (num_given num_extra_needed : nat)
227 | Registers_too_narrow (bad_reg : list REG)
228 | Callee_saved_registers_too_narrow (bad_reg : list REG)
229 | Duplicate_registers (bad_reg : list REG)
230 | Incorrect_array_input_dag_node
231 | Incorrect_Z_input_dag_node
232 | Not_enough_input_dag_nodes (t : API.type)
233 | Expected_const_in_reference_code (_ : idx)
234 | Expected_power_of_two (w : N) (_ : idx)
235 | Unknown_array_length (t : base.type)
236 | Registers_not_saved (regs : list (REG * (idx (* before *) * idx (* after *)))) (_ : symbolic_state)
237 | Invalid_arrow_type (t : API.type)
238 | Invalid_argument_type (t : API.type)
239 | Invalid_return_type (t : base.type)
240 | Invalid_higher_order_application {var} {s d : API.type} (f : API.expr (var:=var) (s -> d)) (x : API.expr (var:=var) s)
241 | Invalid_higher_order_let {var} {s : API.type} (x : API.expr (var:=var) s)
242 | Unhandled_identifier {t} (idc : ident t)
243 | Unhandled_cast (_ _ : Z)
244 | Unable_to_unify (_ _ : list (idx + list idx)) (first_new_idx_after_all_old_idxs : option idx) (_ : symbolic_state)
245 | Missing_ret
246 | Code_after_ret (significant : Lines) (l : Lines)
247 .
248
249 Definition symbolic_state_of_EquivalenceCheckingError (e : EquivalenceCheckingError) : option symbolic_state
250 := match e with
251 | Symbolic_execution_failed _ s
252 | Internal_error_output_load_failed _ _ s
253 | Internal_error_lingering_memory s
254 | Unable_to_unify _ _ _ s
255 | Registers_not_saved _ s
256 => Some s
257 | Internal_error_extra_input_arguments _ _
258 | Internal_error_LoadOutputs_length_mismatch _ _
259 | Not_enough_registers _ _
260 | Registers_too_narrow _
261 | Callee_saved_registers_too_narrow _
262 | Duplicate_registers _
263 | Incorrect_array_input_dag_node
264 | Incorrect_Z_input_dag_node
265 | Not_enough_input_dag_nodes _
266 | Expected_const_in_reference_code _
267 | Expected_power_of_two _ _
268 | Unknown_array_length _
269 | Invalid_arrow_type _
270 | Invalid_argument_type _
271 | Invalid_return_type _
272 | Invalid_higher_order_application _ _ _ _ _
273 | Invalid_higher_order_let _ _ _
274 | Unhandled_identifier _ _
275 | Unhandled_cast _ _
276 | Missing_ret
277 | Code_after_ret _ _
278 => None
279 end.
280
281 Definition AnnotatedLine := (Line * dag.eager.t)%type.
282 Definition AnnotatedLines := (Lines * symbolic_state)%type.
283
284 Definition show_annotated_Line : Show AnnotatedLine
285 := fun '(l, d)
286 => let l_n := show_Line_with_line_number l in
287 let l := show l in
288 (l ++ match dag.eager.description_lookup d l_n with
289 | [] => ""
290 | new_idxs
291 => String.Tab ++ "; " ++ String.concat ", " (List.map (fun i => "#" ++ show i) new_idxs)
292 end)%string.
293
294 Global Instance show_lines_AnnotatedLines : ShowLines AnnotatedLines
295 := fun '(ls, ss)
296 => let d := dag.eager.force ss.(dag_state) in
297 List.map (fun l => show_annotated_Line (l, d)) ls.
298
299 Fixpoint remove_common_indices {T} (eqb : T -> T -> bool) (xs ys : list T) (start_idx : nat) : list (nat * T) * list T
300 := match xs with
301 | [] => (List.map (fun '(idx, x) => (start_idx + idx, x)) (List.enumerate xs),
302 ys)
303 | x :: xs
304 => let '(xs', ys') := remove_common_indices eqb xs (List.removen (eqb x) ys 1) (S start_idx) in
305 if List.existsb (eqb x) ys
306 then (xs', ys')
307 else ((start_idx, x) :: xs', ys')
308 end.
309
310 Definition show_expr_node_lite : Show Symbolic.expr
311 := fix show_expr_node_lite (e : Symbolic.expr) : string
312 := match e with
313 | ExprRef i => "#" ++ show i
314 | ExprApp (op, e)
315 => "(" ++ show op ++ ", " ++ @show_list _ show_expr_node_lite e ++ ")"
316 end%string.
317
318 Definition show_node_lite : Show (node idx)
319 := fun '(op, e)
320 => show_expr_node_lite (ExprApp (op, List.map ExprRef e)).
321
322 Definition recursive_deps_list_step
323 (recursive_deps : NSet.t -> idx -> NSet.t)
324 (so_far : NSet.t)
325 (ls : list idx)
326 : NSet.t
327 := fold_left recursive_deps ls so_far.
328
329 Definition recursive_deps_step
330 (recursive_deps : NSet.t -> idx -> NSet.t)
331 (dag : dag)
332 (so_far : NSet.t)
333 (i : idx)
334 : NSet.t
335 := if NSet.mem i so_far
336 then so_far
337 else let so_far := NSet.add i so_far in
338 match dag.lookup dag i with
339 | Some (_op, args)
340 => recursive_deps_list_step recursive_deps so_far args
341 | None => so_far
342 end.
343
344 Fixpoint recursive_deps
345 (fuel : nat)
346 (dag : dag)
347 (init : NSet.t)
348 (i : idx)
349 : NSet.t
350 := match fuel with
351 | 0 => NSet.singleton i
352 | S fuel => recursive_deps_step (recursive_deps fuel dag) dag init i
353 end.
354
355 Definition recursive_deps_list
356 (fuel : nat) (dag : dag)
357 (init : NSet.t)
358 (ls : list idx)
359 : NSet.t
360 := recursive_deps_list_step (recursive_deps fuel dag) init ls.
361
362 Definition at_leaves_fold
363 {T} (f : idx -> T -> Symbolic.expr * T)
364 := fix at_leaves_fold (e : Symbolic.expr) : T -> Symbolic.expr * T
365 := match e with
366 | ExprRef i => f i
367 | ExprApp (op0, args)
368 => fun st => let '(args, st) := List.foldmap at_leaves_fold args st in
369 (ExprApp (op0, args), st)
370 end.
371
372 Definition at_leaves (f : idx -> Symbolic.expr) (e : Symbolic.expr) : Symbolic.expr
373 := fst (at_leaves_fold (fun i 'tt => (f i, tt)) e tt).
374
375 Definition reveal_one_except (dag : dag) (except : idx -> bool) (e : Symbolic.expr) : Symbolic.expr * (bool (* revealed something *))
376 := at_leaves_fold
377 (fun i revealed
378 => if except i
379 then (ExprRef i, revealed)
380 else match dag.lookup dag i with
381 | Some (op0, args)
382 => (ExprApp (op0, List.map ExprRef args), true)
383 | None => (ExprRef i, revealed)
384 end)
385 e
386 false.
387
388 Definition indices_at_leaves_map (ls : list Symbolic.expr) : list idx
389 := N.sort (NSet.elements (snd (List.foldmap (at_leaves_fold (fun i idxs => (ExprRef i, NSet.add i idxs))) ls NSet.empty))).
390
391 Definition indices_at_leaves (e : Symbolic.expr) : list idx
392 := indices_at_leaves_map [e].
393
394 Fixpoint make_iteratively_revealed_exprs
395 (dag : dag)
396 (max_depth : nat)
397 (except : idx -> bool)
398 (ls : list Symbolic.expr)
399 := match max_depth with
400 | 0 => [] (* should not get here *)
401 | S max_depth
402 => let res := List.map (reveal_one_except dag except) ls in
403 let ls := List.map fst res in
404 let progress := List.existsb (fun b => b) (List.map snd res) in
405 if progress
406 then ls :: make_iteratively_revealed_exprs dag max_depth except ls
407 else []
408 end.
409
410 Definition describe_idx_from_state
411 (show_full : bool)
412 (st : symbolic_state) (idx : idx) : list string
413 := let description_from_state
414 := match reverse_lookup_widest_reg st.(symbolic_reg_state) idx, reverse_lookup_flag st.(symbolic_flag_state) idx, reverse_lookup_mem st.(symbolic_mem_state) idx with
415 | Some r, _, _ => Some ("the value of the register " ++ show r)
416 | None, Some f, _ => Some ("the value of the flag " ++ show f)
417 | None, None, Some (ptr, ptsto) => Some ("the memory location at pseudo-address " ++ Hex.show_N ptr ++ " which points to dag index " ++ show ptsto ++ " which holds the value " ++ show (reveal st.(dag_state) 1 ptsto))
418 | None, None, None => None
419 end%string in
420 let is_old := match reveal st.(dag_state) 1 idx with
421 | ExprApp (old _ _, _) => true
422 | _ => false
423 end in
424 match is_old, description_from_state, show_full, dag.lookup st.(dag_state) idx with
425 | true, Some descr, false, _
426 | _, Some descr, _, None
427 => [show idx ++ " is " ++ descr ++ "."]
428 | _, Some descr, true, Some e
429 => [show idx ++ " is " ++ descr ++ " (" ++ show_node_lite e ++ ")."]
430 | true, None, _, _
431 => [show idx ++ " is a special value no longer present in the symbolic machine state at the end of execution."]
432 | _, _, false, _ => []
433 | _, None, true, Some e
434 => [show idx ++ " is " ++ show_node_lite e ++ "."]
435 | _, None, true, None
436 => [show idx ++ " is not in the dag."]
437 end%string.
438
439 Definition iteratively_describe_idxs_after
440 (first_new_idx_after_all_old_idxs : option idx)
441 (dag : dag)
442 (describe_idx : idx -> list string)
443 (show_initial : bool)
444 (idxs : list idx)
445 : list string
446 := let deps := recursive_deps_list (S (N.to_nat (dag.size dag))) dag NSet.empty idxs in
447 let deps := if show_initial then List.fold_right NSet.add deps idxs else deps in
448 let deps := List.rev (N.sort (NSet.elements deps)) in
449 let deps := match first_new_idx_after_all_old_idxs with
450 | Some first_new_idx_after_all_old_idxs
451 => filter (fun i => (first_new_idx_after_all_old_idxs <=? i)%N) deps
452 | None => deps
453 end in
454 List.flat_map describe_idx deps.
455
456 Definition iteratively_describe_idx
457 (dag : dag)
458 (describe_idx : idx -> list string)
459 (show_initial : bool)
460 (i : idx)
461 : list string
462 := iteratively_describe_idxs_after None dag describe_idx show_initial [i].
463
464 Definition describe_full_idx_from_state (st : symbolic_state) (i : idx)
465 : list string
466 := iteratively_describe_idx st (describe_idx_from_state true st) true i.
467
468 Fixpoint explain_array_unification_error_single
469 (dag : dag)
470 (first_new_idx_after_all_old_idxs : option idx)
471 (singular plural : string)
472 (left_descr right_descr : string)
473 (explain_idx_unification_error : idx -> idx -> list string)
474 (describe_idx : idx -> list string)
475 (modulo_commutativity : bool)
476 (asm_array PHOAS_array : list idx) (start_idx : nat)
477 : list string
478 := let recr := explain_array_unification_error_single dag first_new_idx_after_all_old_idxs singular plural left_descr right_descr explain_idx_unification_error describe_idx modulo_commutativity in
479 match asm_array, PHOAS_array with
480 | [], []
481 => ["Internal Error: Unifiable " ++ plural ++ (if modulo_commutativity then " modulo commutativity" else "")]
482 | [], PHOAS_array
483 => ((["The " ++ right_descr ++ " " ++ singular ++ " contains " ++ show (List.length PHOAS_array) ++ " more values than the " ++ left_descr ++ " " ++ singular ++ "."]%string)
484 ++ List.flat_map describe_idx PHOAS_array)%list
485 | asm_array, []
486 => ((["The " ++ left_descr ++ " " ++ singular ++ " contains " ++ show (List.length asm_array) ++ " more values than the " ++ right_descr ++ " " ++ singular ++ "."]%string)
487 ++ List.flat_map describe_idx asm_array)%list
488 | asm_value :: asm_array, PHOAS_value :: PHOAS_array
489 => if Decidable.dec (asm_value = PHOAS_value)
490 then recr asm_array PHOAS_array (S start_idx)
491 else
492 if modulo_commutativity && List.existsb (N.eqb asm_value) PHOAS_array
493 then
494 recr asm_array (PHOAS_value :: List.removen (N.eqb asm_value) PHOAS_array 1) (S start_idx)
495 else
496 ((["index " ++ show start_idx ++ ": " ++ show_expr_node_lite (ExprRef asm_value) ++ " ≠ " ++ show_expr_node_lite (ExprRef PHOAS_value)]%string)
497 (* if there we are entering into territory where all values were computed both by asm and PHOAS, and leaving territory where some values were computed only by the one that ran second, we will print out extra information about the smallest value that ran second *)
498 (* When we transition from an inequality that contains indices appearing only in assembly to an inequality containing indices that appear in both, recursively expand all indices appearing only in asm, before (after?) continuing on describing why the first arguments are not equal *)
499 ++ match first_new_idx_after_all_old_idxs with
500 | None => []
501 | Some first_new_idx_after_all_old_idxs
502 => if ((asm_value <? first_new_idx_after_all_old_idxs) && (PHOAS_value <? first_new_idx_after_all_old_idxs))%N%bool
503 then
504 match filter (fun i => first_new_idx_after_all_old_idxs <=? i)%N (asm_array ++ PHOAS_array) with
505 | [] => []
506 | new_idxs
507 => iteratively_describe_idxs_after
508 None (* if we don't want to display the ones from only PHOAS, we could pass (Some first_new_idx_after_all_old_idxs) instead *)
509 dag
510 describe_idx
511 true (* show initial *)
512 new_idxs
513 end
514 else []
515 end
516 ++ explain_idx_unification_error asm_value PHOAS_value
517 )%list
518 end%string%list%bool.
519
520 Definition iteratively_explain_array_unification_error_modulo_commutativity
521 (dag : dag)
522 (describe_idx : idx -> list string)
523 (op : option op)
524 (show_initial : bool)
525 (asm_array : list (nat * idx)) (PHOAS_array : list idx)
526 : list string
527 := let recursive_deps := recursive_deps_list (S (N.to_nat (dag.size dag))) dag NSet.empty in
528 let asm_deps := recursive_deps (List.map snd asm_array) in
529 let PHOAS_deps := recursive_deps PHOAS_array in
530 let common_deps := NSet.inter asm_deps PHOAS_deps in
531 let make_iteratively_revealed_exprs := make_iteratively_revealed_exprs dag (S (N.to_nat (dag.size dag))) (fun i => NSet.mem i common_deps) in
532 let asm_exprs := List.map ExprRef (List.map snd asm_array) in
533 let PHOAS_exprs := List.map ExprRef PHOAS_array in
534 let asm_reveals := make_iteratively_revealed_exprs asm_exprs in
535 let PHOAS_reveals := make_iteratively_revealed_exprs PHOAS_exprs in
536 let reveals := List.combine_extend asm_exprs PHOAS_exprs asm_reveals PHOAS_reveals in
537 let '(last_asm, last_PHOAS) := List.last reveals (asm_exprs, PHOAS_exprs) in
538 (* reveal one more time *)
539 let reveal_one_final_time := List.map (at_leaves (reveal dag 1)) in
540 let last_asm := reveal_one_final_time last_asm in
541 let last_PHOAS := reveal_one_final_time last_PHOAS in
542 let reveals := (if show_initial then [(asm_exprs, PHOAS_exprs)] else [])
543 ++ reveals ++ [(last_asm, last_PHOAS)] in
544 let show_array array
545 := let args := @show_list _ show_expr_node_lite array in
546 match op with
547 | Some op => "(" ++ show op ++ ", " ++ args ++ ")"
548 | None => args
549 end%string in
550 let show_array_pretty array
551 := match op with
552 | Some op => show_expr_pretty (ExprApp (op, array))
553 | None => @show_list _ show_expr_pretty array
554 end%string in
555 List.map
556 (fun '(asm_array, PHOAS_array)
557 => (show_array asm_array ++ " ≠ " ++ show_array PHOAS_array)%string)
558 reveals
559 ++ [show_array_pretty last_asm ++ " ≠ " ++ show_array_pretty last_PHOAS]%string
560 ++ (List.flat_map
561 describe_idx
562 (indices_at_leaves_map (last_asm ++ last_PHOAS))).
563
564 Definition explain_array_unification_error
565 (first_new_idx_after_all_old_idxs : option idx)
566 (dag : dag)
567 (singular plural : string)
568 (left_descr right_descr : string)
569 (explain_idx_unification_error : idx -> idx -> list string)
570 (describe_idx : idx -> list string)
571 (op : option op)
572 (asm_array PHOAS_array : list idx)
573 : list string
574 := let modulo_commutativity := match op with Some o => commutative o | None => false end in
575 if (modulo_commutativity && negb (List.length asm_array =? List.length PHOAS_array))%nat%bool
576 then
577 let orig_asm_array := asm_array in
578 let orig_PHOAS_array := PHOAS_array in
579 match remove_common_indices N.eqb asm_array PHOAS_array 0 with
580 | ([], [])
581 => ["Internal Error: Unifiable " ++ plural ++ " modulo commutativity"]
582 | ([], PHOAS_array)
583 => ((["The " ++ right_descr ++ " " ++ singular ++ " contains " ++ show (List.length PHOAS_array) ++ " more values than the " ++ left_descr ++ " " ++ singular ++ "."]%string)
584 ++ List.flat_map describe_idx PHOAS_array)%list
585 | (asm_array, [])
586 => ((["The " ++ left_descr ++ " " ++ singular ++ " contains " ++ show (List.length asm_array) ++ " more values than the " ++ right_descr ++ " " ++ singular ++ "."]%string)
587 ++ List.flat_map describe_idx (List.map snd asm_array))%list
588 | ([(arr_index, asm_value)], [PHOAS_value])
589 => (* there's only one idx on each side, so we can just naively compare them *)
590 ((["index " ++ show arr_index ++ ": " ++ show_expr_node_lite (ExprRef asm_value) ++ " ≠ " ++ show_expr_node_lite (ExprRef PHOAS_value)]%string)
591 ++ explain_idx_unification_error asm_value PHOAS_value
592 )%list
593 | (asm_array, PHOAS_array)
594 => (* show init state when there are some common indices; otherwise we don't want to duplicate the expression *)
595 let show_initial_state := (negb ((List.length asm_array =? List.length orig_asm_array) && (List.length PHOAS_array =? List.length orig_PHOAS_array)))%nat in
596 iteratively_explain_array_unification_error_modulo_commutativity
597 dag describe_idx op show_initial_state asm_array PHOAS_array
598 end%string%list%bool
599 else
600 explain_array_unification_error_single dag first_new_idx_after_all_old_idxs singular plural left_descr right_descr explain_idx_unification_error describe_idx modulo_commutativity asm_array PHOAS_array 0.
601
602 Definition explain_mismatch_from_state
603 (left_descr right_descr : string)
604 (st : symbolic_state) (asm_idx PHOAS_idx : idx) : list string
605 := ((describe_idx_from_state false (*left_descr*) st asm_idx)
606 ++ (describe_idx_from_state false (*right_descr*) st PHOAS_idx))%list.
607
608 Fixpoint explain_idx_unification_error
609 (first_new_idx_after_all_old_idxs : option idx)
610 (left_descr right_descr : string)
611 (st : symbolic_state) (fuel : nat) (asm_idx PHOAS_idx : idx) {struct fuel} : list string
612 := let recr := match fuel with
613 | O => fun _ _ => ["Internal error: out of fuel in explain_expr_unification_error"]
614 | S fuel => explain_idx_unification_error first_new_idx_after_all_old_idxs left_descr right_descr st fuel
615 end in
616 let reveal_idx idx := dag.lookup st.(dag_state) idx in
617 let reveal_show_idx idx
618 := match reveal_idx idx with
619 | Some n => show n
620 | None => show_expr_node_lite (ExprRef idx)
621 end in
622 let reveal_show_node '(op, e)
623 := ("(" ++ show op ++ ", " ++ @show_list _ reveal_show_idx e ++ ")")%string in
624 match reveal_idx asm_idx, reveal_idx PHOAS_idx with
625 | None, None
626 => ["Internal error: neither expression is in the dag"]
627 | None, Some _
628 => ["Internal error: assembly index " ++ show asm_idx ++ " is not in the dag"]
629 | Some _, None
630 => ["Internal error: synthesized index " ++ show PHOAS_idx ++ " is not in the dag"]
631 | Some ((asm_o, asm_e) as asm), Some ((PHOAS_o, PHOAS_e) as PHOAS)
632 => (([show_node_lite asm ++ " ≠ " ++ show_node_lite PHOAS]%string)
633 ++ (if Decidable.dec (asm_o = PHOAS_o)
634 then explain_array_unification_error first_new_idx_after_all_old_idxs st "argument" "arguments" left_descr right_descr recr (describe_idx_from_state false st) (Some asm_o) asm_e PHOAS_e
635 else (([reveal_show_node asm ++ " ≠ " ++ reveal_show_node PHOAS
636 ; "Operation mismatch: " ++ show asm_o ++ " ≠ " ++ show PHOAS_o]%string)
637 ++ explain_mismatch_from_state left_descr right_descr st asm_idx PHOAS_idx)%list))%list
638 end%string.
639
640 Definition explain_unification_default_fuel (st : symbolic_state) : nat
641 := N.to_nat (10 + (2 * dag.size st.(dag_state))) (* we since the dag is acyclic, we shouldn't have to do more recursive lookups than its length; we double and add 10 for safety *).
642
643 Fixpoint explain_unification_error (asm_output PHOAS_output : list (idx + list idx)) (first_new_idx_after_all_old_idxs : option idx) (start_idx : nat) (st : symbolic_state)
644 : list string
645 := let fuel := explain_unification_default_fuel st in
646 match asm_output, PHOAS_output with
647 | [], []
648 => ["Internal Error: Unifiable"]
649 | [], PHOAS_output
650 => ["The synthesized code returns " ++ show (List.length PHOAS_output) ++ " more values than the assembly code."]
651 | asm_output, []
652 => ["The assembly code returns " ++ show (List.length asm_output) ++ " more values than the synthesized code."]
653 | asm_value :: asm_output, PHOAS_value :: PHOAS_output
654 => if Decidable.dec (asm_value = PHOAS_value)
655 then explain_unification_error asm_output PHOAS_output first_new_idx_after_all_old_idxs (S start_idx) st
656 else let prefix := ("Could not unify the values at index " ++ show start_idx ++ ":")%string in
657 match asm_value, PHOAS_value with
658 | inl _, inr _ => [prefix; "The assembly code returns a scalar while the synthesized code returns an array."]
659 | inr _, inl _ => [prefix; "The assembly code returns an array while the synthesized code returns a scalar."]
660 | inl asm_idx, inl PHOAS_idx
661 => (["index " ++ show start_idx ++ ": " ++ show_expr_node_lite (ExprRef asm_idx) ++ " ≠ " ++ show_expr_node_lite (ExprRef PHOAS_idx)]%string)
662 ++ explain_idx_unification_error first_new_idx_after_all_old_idxs "assembly" "synthesized" st fuel asm_idx PHOAS_idx
663 | inr asm_idxs, inr PHOAS_idxs
664 => ([prefix ++ " " ++ @show_list _ show_expr_node_lite (List.map ExprRef asm_idxs) ++ " ≠ " ++ @show_list _ show_expr_node_lite (List.map ExprRef PHOAS_idxs)]%string)
665 ++ (explain_array_unification_error
666 first_new_idx_after_all_old_idxs st "array" "arrays" "assembly" "synthesized" (explain_idx_unification_error first_new_idx_after_all_old_idxs "assembly" "synthesized" st fuel) (describe_idx_from_state false st) None
667 asm_idxs PHOAS_idxs)
668 end%list
669 end%string%list.
670
671 Global Instance show_lines_EquivalenceCheckingError : ShowLines EquivalenceCheckingError
672 := fun err => match err with
673 | Symbolic_execution_failed l r
674 => ["In combined state:"]
675 ++ show_lines r ++ ["Symbolic execution failed:"] ++ show_lines l
676 ++ match l with
677 | error.load idx s
678 | error.store idx _ s
679 | error.remove idx s
680 | error.remove_has_duplicates idx _ s
681 => describe_full_idx_from_state s idx
682 | _ => []
683 end
684 | Internal_error_lingering_memory s
685 => ["In combined state:"] ++ show_lines s ++ ["Some memory remained after all known memory was removed: " ++ show s.(symbolic_mem_state)]%string
686 | Internal_error_output_load_failed err l r => ["In combined state:"] ++ show_lines r ++ ["Internal error. Output load failed: " ++ show l ++ match err with Some err => "(" ++ show err ++ ")" | None => "" end]%string
687 | Internal_error_extra_input_arguments t unused_arguments
688 => ["Internal error. Too many input arguments for type " ++ show t ++ ". Unused arguments: " ++ show unused_arguments]%string
689 | Internal_error_LoadOutputs_length_mismatch l1 l2
690 => ["Internal error. Length mismatch for " ++ show l1 ++ " and " ++ show l2 ++ "."; show (List.length l1) ++ " ≠ " ++ show (List.length l2)]%string
691 | Not_enough_registers num_given num_extra_needed
692 => ["Not enough registers available for storing input and output (given " ++ show num_given ++ ", needed an additional " ++ show num_extra_needed ++ "."]%string
693 | Registers_too_narrow regs
694 => ["Some registers given were more narrow than 64 bits: " ++ String.concat ", " (List.map (fun r => show r ++ " (width: " ++ show (reg_size r) ++ ")") regs)]%string
695 | Callee_saved_registers_too_narrow regs
696 => ["Some callee-saved / non-volatile registers given were more narrow than 64 bits: " ++ String.concat ", " (List.map (fun r => show r ++ " (width: " ++ show (reg_size r) ++ ")") regs)]%string
697 | Duplicate_registers regs
698 => ["List of registers contains duplicates: " ++ String.concat ", " (List.map show regs)]%string
699 | Incorrect_array_input_dag_node
700 => ["Internal error: Input dag node had an unexpected array."]
701 | Incorrect_Z_input_dag_node
702 => ["Internal error: Input dag node had an unexpected Z."]
703 | Not_enough_input_dag_nodes t
704 => ["Internal error: Not enough input dag nodes to allocate for type " ++ show t ++ "."]%string
705 | Expected_const_in_reference_code i => ["Expected N const in reference code for dag node " ++ show i]%string
706 | Expected_power_of_two w i => ["Expected power of 2, got " ++ show w ++ " (index " ++ show i ++ ")"]%string
707 | Invalid_argument_type t
708 => ["Invalid type for argument: " ++ show t]%string
709 | Invalid_return_type t
710 => ["Invalid type for return: " ++ show t]%string
711 | Unknown_array_length t => ["Unknown array length of type " ++ show t ++ "."]%string
712 | Invalid_arrow_type t => ["Invalid higher order function involving the type " ++ show t ++ "."]%string
713 | Invalid_higher_order_application var s d f x
714 => let __ := @Compilers.ToString.PHOAS.expr.partially_show_expr in
715 ["Invalid higher-order application node with argument of type " ++ show s ++ ":"
716 ; "Function expression: " ++ show f
717 ; "Argument expression: " ++ show x]%string
718 | Invalid_higher_order_let var s x
719 => let __ := @Compilers.ToString.PHOAS.expr.partially_show_expr in
720 ["Invalid higher-order let-in node with argument of type " ++ show s ++ ":"
721 ; "Let-bound expression: " ++ show x]%string
722 | Unhandled_identifier t idc
723 => ["Identifier not yet handled by symbolic evaluation: " ++ show idc ++ "."]%string
724 | Unhandled_cast l u
725 => ["Argument not yet handled by symbolic evaluation: " ++ show (l, u)]%string
726 | Registers_not_saved regs r
727 => let reg_before := List.map (fun '(r, (idx_before, idx_after)) => idx_before) regs in
728 let reg_after := List.map (fun '(r, (idx_before, idx_after)) => idx_after) regs in
729 let regs := List.map (fun '(r, (idx_before, idx_after)) => r) regs in
730 (["Unable to establish that callee-saved non-volatile registers were preserved: " ++ String.concat ", " (List.map show regs); "In environment:"]%string)
731 ++ show_lines r
732 ++ ["Unable to establish that callee-saved non-volatile registers were preserved: " ++ String.concat ", " (List.map show regs); "Unable to unify: " ++ show reg_before ++ " == " ++ show reg_after]%string
733 ++ (let first_new_idx_after_all_old_idxs := None in (* dummy, since we don't know the value here, and it's hard to pipe the info through, and it's not super-important *)
734 explain_array_unification_error
735 first_new_idx_after_all_old_idxs r "list" "lists" "original" "final" (explain_idx_unification_error first_new_idx_after_all_old_idxs "original" "final" r (explain_unification_default_fuel r)) (describe_idx_from_state false r) None
736 reg_before reg_after)
737 | Unable_to_unify asm_output PHOAS_output first_new_idx_after_all_old_idxs r
738 => ["Unable to unify:"; "In environment:"]
739 ++ show_lines r
740 ++ ["Unable to unify: " ++ show asm_output ++ " == " ++ show PHOAS_output]%string
741 ++ explain_unification_error asm_output PHOAS_output first_new_idx_after_all_old_idxs 0 r
742 | Missing_ret
743 => ["Missing 'ret' at the end of the function"]
744 | Code_after_ret significant l
745 => ["Code after ret:"; "In:"] ++ show_lines l ++ ["Found instructions after ret:"] ++ show_lines significant
746 end%list.
747 Global Instance show_EquivalenceCheckingError : Show EquivalenceCheckingError
748 := fun err => String.concat String.NewLine (show_lines err).
749
750 Definition merge_fresh_symbol {descr:description} : dag.M idx := fun d => merge_node (dag.gensym 64%N d) d.
751 Definition merge_literal {descr:description} (l:Z) : dag.M idx := merge_node ((const l, nil)).
752
753 Definition SetRegFresh {opts : symbolic_options_computed_opt} {descr:description} (r : REG) : M idx :=
754 (idx <- lift_dag merge_fresh_symbol;
755 _ <- SetReg r idx;
756 Symbolic.ret idx).
757
758 (** symbolic evaluations live in the state monad, pushed to the leaves of a PHOAS type *)
759 Definition symexM T := dag -> ErrorT EquivalenceCheckingError (T * dag).
760 Definition symex_return {T} (v : T) : symexM T := fun st => Success (v, st).
761 Definition symex_error {T} err : symexM T := fun st => Error err.
762 Definition symex_bind {A B} (v : symexM A) (f : A -> symexM B) : symexM B
763 := fun st => (v <- v st; let '(a, st) := v in f a st)%error.
764 Declare Scope symex_scope.
765 Delimit Scope symex_scope with symex.
766 Bind Scope symex_scope with symexM.
767 Notation "'slet' x .. y <- X ; B" := (symex_bind X (fun x => .. (fun y => B%symex) .. )) : symex_scope.
768 Notation "A <- X ; B" := (symex_bind X (fun A => B%symex)) : symex_scope.
769 (* light alias *)
770 Definition App {opts : symbolic_options_computed_opt} {descr:description} (e : Symbolic.node idx) : symexM idx := fun st => Success (merge (simplify st e) st).
771 Definition RevealConstant (i : idx) : symexM N := fun st =>
772 match reveal st 1 i with
773 | ExprApp (const n, nil) =>
774 if Z.leb 0 n then Success (Z.to_N n, st) else Error (Expected_const_in_reference_code i)
775 | _ => Error (Expected_const_in_reference_code i)
776 end.
777 Definition RevealWidth (i : idx) : symexM N :=
778 s <- RevealConstant i;
779 let w := N.log2 s in
780 if N.eqb s (N.pow 2 w)
781 then symex_return w
782 else symex_error (Expected_power_of_two s i).
783
784 Definition type_spec := list (option nat). (* list of array lengths; None means not an array *)
785
786 (** Convert PHOAS info about types and argument bounds into a simplified specification *)
787 Fixpoint simplify_base_type
788 (t : base.type)
789 : forall arg_bounds : ZRange.type.base.option.interp t, ErrorT EquivalenceCheckingError type_spec
790 := match t return ZRange.type.base.option.interp t -> _ with
791 | base.type.unit
792 => fun 'tt => Success []
793 | base.type.type_base base.type.Z
794 => fun _ => Success [None]
795 | base.type.prod A B
796 => fun '(bA, bB)
797 => (vA <- simplify_base_type A bA;
798 vB <- simplify_base_type B bB;
799 Success (vA ++ vB))
800 | base.type.list (base.type.type_base base.type.Z)
801 => fun b
802 => match b with
803 | None => Error (Unknown_array_length t)
804 | Some bs => Success [Some (List.length bs)]
805 end
806 | base.type.type_base _
807 | base.type.option _
808 | base.type.list _
809 => fun _ => Error (Invalid_argument_type (type.base t))
810 end%error.
811 Definition simplify_type
812 (t : API.type)
813 : forall arg_bounds : ZRange.type.option.interp t, ErrorT EquivalenceCheckingError type_spec
814 := match t with
815 | type.base t => simplify_base_type t
816 | type.arrow _ _ => fun _ => Error (Invalid_argument_type t)
817 end.
818 Fixpoint simplify_input_type
819 (t : API.type)
820 : forall arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t, ErrorT EquivalenceCheckingError type_spec
821 := match t return type.for_each_lhs_of_arrow ZRange.type.option.interp t -> _ with
822 | type.base _ => fun 'tt => Success []
823 | type.arrow A B
824 => fun '(bA, bB)
825 => (vA <- simplify_type A bA;
826 vB <- simplify_input_type B bB;
827 Success (vA ++ vB))
828 end%error.
829
830 Definition build_inputarray {descr:description} (len : nat) : dag.M (list idx) :=
831 List.foldmap (fun _ => merge_fresh_symbol) (List.seq 0 len).
832
833 Fixpoint build_inputs {descr:description} (types : type_spec) : dag.M (list (idx + list idx))
834 := match types with
835 | [] => dag.ret []
836 | None :: tys
837 => (idx <- merge_fresh_symbol;
838 rest <- build_inputs tys;
839 dag.ret (inl idx :: rest))
840 | Some len :: tys
841 => (idxs <- build_inputarray len;
842 rest <- build_inputs tys;
843 dag.ret (inr idxs :: rest))
844 end%dagM.
845
846 (* we factor this out so that conversion is not slow when proving things about this *)
847 Definition compute_array_address {opts : symbolic_options_computed_opt} {descr:description} (base : idx) (i : nat)
848 := (offset <- Symbolic.App (zconst 64%N (8 * Z.of_nat i), nil);
849 Symbolic.App (add 64%N, [base; offset]))%x86symex.
850
851 Definition build_merge_array_addresses {opts : symbolic_options_computed_opt} {descr:description} (base : idx) (items : list idx) : M (list idx)
852 := mapM (fun '(i, idx) =>
853 (addr <- compute_array_address base i;
854 (fun s => Success (addr, update_mem_with s (cons (addr,idx)))))
855 )%x86symex (List.enumerate items).
856
857 Fixpoint build_merge_base_addresses {opts : symbolic_options_computed_opt} {descr:description} {dereference_scalar:bool} (items : list (idx + list idx)) (reg_available : list REG) : M (list ((REG + idx) + idx))
858 := match items, reg_available with
859 | [], _ | _, [] => Symbolic.ret []
860 | inr idxs :: xs, r :: reg_available
861 => (base <- SetRegFresh r; (* note: overwrites initial value *)
862 addrs <- build_merge_array_addresses base idxs; (* note: overwrites initial value *)
863 rest <- build_merge_base_addresses (dereference_scalar:=dereference_scalar) xs reg_available;
864 Symbolic.ret (inr base :: rest))
865 | inl idx :: xs, r :: reg_available =>
866 (addr <- (if dereference_scalar
867 then
868 (addr <- SetRegFresh r;
869 fun s => Success (inr addr, update_mem_with s (cons (addr, idx))))
870 else
871 (_ <- SetReg r idx; (* note: overwrites initial value *)
872 ret (inl r)));
873 rest <- build_merge_base_addresses (dereference_scalar:=dereference_scalar) xs reg_available;
874 Symbolic.ret (inl addr :: rest))
875 end%N%x86symex.
876
877 Fixpoint dag_gensym_n {descr:description} (n : nat) : dag.M (list symbol) :=
878 match n with
879 | O => dag.ret nil
880 | S n =>
881 (i <- merge_fresh_symbol;
882 rest <- dag_gensym_n n;
883 dag.ret (cons i rest))
884 end%dagM.
885
886 (** PHOAS var type, storing dag indices or nat literals *)
887 Fixpoint base_var (t : base.type) : Set
888 := match t with
889 | base.type.unit
890 => unit
891 | base.type.type_base base.type.Z => idx
892 | base.type.prod A B => base_var A * base_var B
893 | base.type.list A => list (base_var A)
894 | base.type.type_base base.type.nat => nat
895 | base.type.type_base base.type.zrange => ZRange.zrange
896 | base.type.type_base _
897 | base.type.option _
898 => Empty_set (* should not happen *)
899 end.
900 Definition var (t : API.type) : Set
901 := match t with
902 | type.base t => base_var t
903 | type.arrow s d => Empty_set
904 end.
905
906 (* true iff simplify_base_var (and all other things that process input and output types) can succeed *)
907 Fixpoint check_base_type_ok (t : base.type) : bool
908 := match t with
909 | base.type.unit => true
910 | base.type.type_base base.type.Z => true
911 | base.type.prod A B => check_base_type_ok A && check_base_type_ok B
912 | base.type.list (base.type.type_base base.type.Z) => true
913 | base.type.list _
914 | base.type.type_base _
915 | base.type.option _
916 => false
917 end.
918 Class base_type_ok t : Prop := base_type_is_ok : check_base_type_ok t = true.
919 Global Hint Extern 1 (base_type_ok ?t) => abstract vm_cast_no_check (eq_refl true) : typeclass_instances.
920 Definition check_argument_type_ok (t : API.type) : bool
921 := match t with
922 | type.base t => check_base_type_ok t
923 | type.arrow _ _ => false
924 end.
925 Class argument_type_ok t : Prop := argument_type_is_ok : check_argument_type_ok t = true.
926 Global Hint Extern 1 (argument_type_ok ?t) => abstract vm_cast_no_check (eq_refl true) : typeclass_instances.
927 Class type_ok (t : API.type) : Prop
928 := type_is_ok : (type.andb_each_lhs_of_arrow check_argument_type_ok t && check_base_type_ok (type.final_codomain t))%bool = true.
929 Global Hint Extern 1 (type_ok ?t) => abstract vm_cast_no_check (eq_refl true) : typeclass_instances.
930
931 Fixpoint simplify_base_var {t : base.type} : base_var t -> ErrorT EquivalenceCheckingError (list (idx + list idx))
932 := match t return base_var t -> ErrorT EquivalenceCheckingError (list (idx + list idx)) with
933 | base.type.unit
934 => fun 'tt => Success []
935 | base.type.type_base base.type.Z => fun idx => Success [inl idx]
936 | base.type.prod A B => fun ab => (a <- simplify_base_var (fst ab); b <- simplify_base_var (snd ab); Success (a ++ b))
937 | base.type.list (base.type.type_base base.type.Z)
938 => fun ls : list idx => Success [inr ls]
939 | base.type.list _
940 | base.type.type_base _
941 | base.type.option _
942 => fun _ => Error (Invalid_return_type t)
943 end%error.
944
945 Fixpoint base_var_beq {t : base.type} : base_var t -> base_var t -> bool :=
946 match t return base_var t -> base_var t -> bool with
947 | base.type.unit => fun _ _ => true
948 | base.type.type_base base.type.Z => N.eqb
949 | base.type.prod _ _ => fun a b => base_var_beq (fst a) (fst b) && base_var_beq (snd a) (snd b)
950 | base.type.list _ => @list_beq _ base_var_beq
951 | base.type.type_base base.type.nat => Nat.eqb
952 | base.type.type_base base.type.zrange => ZRange.zrange_beq
953 | _ => fun _ _ => false
954 end%bool.
955
956 Fixpoint show_base_var {t : base.type} : Show (base_var t) :=
957 match t return base_var t -> string with
958 | base.type.unit => @show unit _
959 | base.type.type_base base.type.Z => @show N _
960 | base.type.prod _ _ => @show_prod _ _ show_base_var show_base_var
961 | base.type.list _ => @show_list _ show_base_var
962 | base.type.type_base base.type.nat => @show nat _
963 | base.type.type_base base.type.zrange => @show ZRange.zrange _
964 | _ => fun _ => "..."
965 end.
966 Global Existing Instance show_base_var.
967
968 (** From the information about dag nodes for inputs, build up the var
969 data we're passing into PHOAS, and return as well the indices that
970 we've not consumed *)
971 Fixpoint build_base_var (t : base.type) (indices : list (idx + list idx))
972 : ErrorT EquivalenceCheckingError (base_var t * list (idx + list idx))
973 := match t, indices return ErrorT _ (base_var t * list (idx + list idx)) with
974 | base.type.unit, _
975 => Success (tt, indices)
976 | base.type.type_base base.type.Z, inl idx :: indices
977 => Success (idx, indices)
978 | base.type.prod A B, _
979 => (vA <- build_base_var A indices;
980 let '(vA, indices) := vA in
981 vB <- build_base_var B indices;
982 let '(vB, indices) := vB in
983 Success ((vA, vB), indices))
984 | base.type.list (base.type.type_base base.type.Z), inr idxs :: indices
985 => Success (idxs, indices)
986 | base.type.type_base base.type.Z, inr _ :: _
987 => Error Incorrect_array_input_dag_node
988 | base.type.list (base.type.type_base base.type.Z), inl _ :: _
989 => Error Incorrect_Z_input_dag_node
990 | base.type.type_base _, []
991 | base.type.list _, []
992 => Error (Not_enough_input_dag_nodes (type.base t))
993 | base.type.type_base _, _
994 | base.type.option _, _
995 | base.type.list _, _ :: _
996 => Error (Invalid_argument_type (type.base t))
997 end%error.
998 Definition build_var (t : API.type) (indices : list (idx + list idx))
999 : ErrorT EquivalenceCheckingError (var t * list (idx + list idx))
1000 := match t with
1001 | type.base t => build_base_var t indices
1002 | type.arrow _ _ => Error (Invalid_argument_type t)
1003 end.
1004 Fixpoint build_input_var (t : API.type) (indices : list (idx + list idx))
1005 : ErrorT EquivalenceCheckingError (type.for_each_lhs_of_arrow var t * list (idx + list idx))
1006 := match t with
1007 | type.base _ => Success (tt, indices)
1008 | type.arrow A B
1009 => (vA <- build_var A indices;
1010 let '(vA, indices) := vA in
1011 vB <- build_input_var B indices;
1012 let '(vB, indices) := vB in
1013 Success ((vA, vB), indices))
1014 end%error.
1015
1016 (** Symbolic evaluation does not support higher-order functions *)
1017 Fixpoint symex_T (t : API.type) : Type
1018 := match t with
1019 | type.base t => symexM (base_var t)
1020 | type.arrow s d => var s -> symex_T d
1021 end.
1022 Definition symex_T_return {t : API.type} : var t -> symex_T t
1023 := match t return var t -> symex_T t with
1024 | type.base t => symex_return
1025 | type.arrow s d
1026 => fun f : Empty_set => match f with end
1027 end.
1028 Fixpoint symex_T_error {t} err : symex_T t
1029 := match t return symex_T t with
1030 | type.base t => symex_error err
1031 | type.arrow s d => fun _ => @symex_T_error d err
1032 end.
1033 Fixpoint symex_T_bind_base {T t} : symexM T -> (T -> symex_T t) -> symex_T t
1034 := match t with
1035 | type.base _ => symex_bind
1036 | type.arrow s d
1037 => fun v f x => @symex_T_bind_base T d v (fun w => f w x)
1038 end.
1039 Fixpoint symex_T_app_curried {t : API.type} : symex_T t -> type.for_each_lhs_of_arrow var t -> symexM (base_var (type.final_codomain t))
1040 := match t with
1041 | type.base t => fun f 'tt => f
1042 | type.arrow s d => fun f '(x, xs) => @symex_T_app_curried d (f x) xs
1043 end.
1044
1045 Bind Scope symex_scope with symex_T.
1046
1047 Definition symex_ident {opts : symbolic_options_computed_opt} {descr:description} {t} (idc : ident t) : symex_T t.
1048 Proof.
1049 refine (let symex_mod_zrange idx '(ZRange.Build_zrange l u) :=
1050 let u := Z.succ u in
1051 let lu := Z.log2 u in
1052 if (Z.eqb l 0 && Z.eqb u (2^lu))%bool
1053 then
1054 App (((slice 0 (Z.to_N lu)), [idx]))
1055 else symex_error (Unhandled_cast l u)
1056 in
1057 match idc in ident t return symex_T t with
1058 | ident.Literal base.type.Z v
1059 => App (const v, nil)
1060 | ident.Z_add => fun x y => App (addZ, [x; y])
1061 | ident.Z_mul => fun x y => App (mulZ, [x; y])
1062 | ident.Z_sub => fun x y => y' <- App (negZ, [y]); App (addZ, [x;y'])
1063 | ident.Z_shiftr => fun x y => App (shrZ, [x; y])
1064 | ident.Z_shiftl => fun x y => App (shlZ, [x; y])
1065 | ident.Z_land => fun x y => App (andZ, [x; y])
1066 | ident.Z_lor => fun x y => App (orZ, [x; y])
1067 | ident.Z_mul_split => fun bs x y =>
1068 vs <- RevealWidth bs; s <- App (const (Z.of_N vs), nil);
1069 v <- App (mulZ, [x; y]);
1070 lo <- App (slice 0 vs, [v]);
1071 hi <- App (shrZ, [v; s]);
1072 symex_return (lo, hi)
1073 | ident.Z_mul_high => fun bs x y =>
1074 vs <- RevealWidth bs; s <- App (const (Z.of_N vs), nil);
1075 v <- App (mulZ, [x; y]);
1076 App (shrZ, [v; s])
1077 | ident.Z_add_get_carry => fun s x y =>
1078 s <- RevealWidth s;
1079 a <- App (add s, [x; y]);
1080 c <- App (addcarryZ s, [x; y]);
1081 symex_return (a, c)
1082 | ident.Z_add_with_carry => fun x y z => App (addZ, [x; y; z])
1083 | ident.Z_add_with_get_carry => fun s x y z =>
1084 s <- RevealWidth s;
1085 a <- App (add s, [x; y; z]);
1086 c <- App (addcarryZ s, [x; y; z]);
1087 symex_return (a, c)
1088 | ident.Z_sub_get_borrow => fun s x y =>
1089 s <- RevealWidth s;
1090 y' <- App (neg s, [y]);
1091 a <- App (add s, [x;y']);
1092 c <- App (subborrowZ s, [x;y]);
1093 symex_return (a, c)
1094 | ident.Z_sub_with_get_borrow => fun s z x y =>
1095 s <- RevealWidth s;
1096 y' <- App (neg s, [y]);
1097 z' <- App (neg s, [z]);
1098 a <- App (add s, [x;y';z']);
1099 c <- App (subborrowZ s, [x;y;z]);
1100 symex_return (a, c)
1101 | ident.Z_zselect => fun c x y => App (Symbolic.selectznz, [c; x; y])
1102 | ident.Z_truncating_shiftl => fun s x y =>
1103 s <- RevealConstant s;
1104 App (shl s, [x; y])
1105
1106 | ident.comment _
1107 | ident.comment_no_keep _
1108 => fun _ => symex_return tt
1109 | ident.value_barrier
1110 => fun v => symex_return v
1111 | ident.tt
1112 => symex_return tt
1113 | ident.Literal base.type.zrange v
1114 | ident.Literal base.type.nat v
1115 => symex_return v
1116 | ident.pair _ _
1117 => fun a b => symex_return (a, b)
1118 | ident.fst _ _
1119 => fun a => symex_return (fst a)
1120 | ident.snd _ _
1121 => fun a => symex_return (snd a)
1122 | ident.nil _
1123 => symex_return []
1124 | ident.cons _
1125 => fun x xs => symex_return (x :: xs)
1126 | ident.Nat_succ as idc
1127 | ident.Nat_pred as idc
1128 => fun v => symex_return (ident.interp idc v)
1129 | ident.Nat_max as idc
1130 | ident.Nat_mul as idc
1131 | ident.Nat_add as idc
1132 | ident.Nat_sub as idc
1133 | ident.List_seq as idc
1134 => fun a b => symex_return (ident.interp idc a b)
1135 | ident.List_nth_default _
1136 | ident.eager_List_nth_default _
1137 => fun default ls n => symex_return (List.nth_default default ls n)
1138 | ident.List_length _
1139 => fun ls => symex_return (List.length ls)
1140 | ident.List_firstn _
1141 => fun n ls => symex_return (List.firstn n ls)
1142 | ident.List_skipn _
1143 => fun n ls => symex_return (List.skipn n ls)
1144 | ident.List_repeat _
1145 => fun v n => symex_return (List.repeat v n)
1146 | ident.List_combine _ _
1147 => fun ls1 ls2 => symex_return (List.combine ls1 ls2)
1148 | ident.List_app _
1149 => fun ls1 ls2 => symex_return (List.app ls1 ls2)
1150 | ident.List_rev _
1151 => fun ls => symex_return (List.rev ls)
1152 | ident.Build_zrange (* do we need to handle this? *)
1153 => fun l r => symex_error (Unhandled_identifier idc)
1154 (* we should handle these the same way that we handle truncation/modulo *)
1155 | ident.Z_cast
1156 => fun r v_idx => idx <- symex_mod_zrange v_idx r; symex_return idx
1157 | ident.Z_cast2
1158 => fun '(r1, r2) '(v1_idx, v2_idx)
1159 => idx1 <- symex_mod_zrange v1_idx r1;
1160 idx2 <- symex_mod_zrange v2_idx r2;
1161 symex_return (idx1, idx2)
1162 | ident.Z_of_nat
1163 => fun n => App (const (Z.of_nat n), nil)
1164
1165 | ident.Z_modulo
1166 | ident.Z_pow
1167 | ident.Z_opp
1168 | ident.Z_div
1169 | ident.Z_log2
1170 | ident.Z_log2_up
1171 | ident.Z_to_nat
1172 | ident.Z_min
1173 | ident.Z_max
1174 | ident.Z_abs
1175 | ident.Z_ltz
1176 | ident.Z_add_modulo
1177 | ident.Z_bneg
1178 | ident.Z_lnot_modulo
1179 | ident.Z_lxor
1180 | ident.Z_rshi
1181 | ident.Z_cc_m
1182 | ident.Z_combine_at_bitwidth
1183 | ident.Literal base.type.bool _
1184 | ident.Literal base.type.string _
1185 | ident.Literal base.type.positive _
1186 | ident.None _
1187 | ident.Some _
1188 | ident.Z_eqb
1189 | ident.Z_leb
1190 | ident.Z_ltb
1191 | ident.Z_geb
1192 | ident.Z_gtb
1193
1194 | ident.Nat_eqb
1195 | ident.prod_rect _ _ _
1196 | ident.bool_rect _
1197 | ident.bool_rect_nodep _
1198 | ident.nat_rect _
1199 | ident.eager_nat_rect _
1200 | ident.nat_rect_arrow _ _
1201 | ident.eager_nat_rect_arrow _ _
1202 | ident.list_rect _ _
1203 | ident.eager_list_rect _ _
1204 | ident.list_rect_arrow _ _ _
1205 | ident.eager_list_rect_arrow _ _ _
1206 | ident.nat_rect_fbb_b _ _ _
1207 | ident.nat_rect_fbb_b_b _ _ _ _
1208 | ident.list_rect_fbb_b _ _ _ _
1209 | ident.list_rect_fbb_b_b _ _ _ _ _
1210 | ident.list_rect_fbb_b_b_b _ _ _ _ _ _
1211 | ident.list_rect_fbb_b_b_b_b _ _ _ _ _ _ _
1212 | ident.list_rect_fbb_b_b_b_b_b _ _ _ _ _ _ _ _
1213 | ident.list_case _ _
1214 | ident.List_map _ _
1215 | ident.List_flat_map _ _
1216 | ident.List_partition _
1217 | ident.List_filter _
1218 | ident.List_fold_right _ _
1219 | ident.List_update_nth _
1220 | ident.option_rect _ _
1221 | ident.zrange_rect _
1222 | ident.Pos_add
1223 | ident.Pos_mul
1224 | ident.Z_pos
1225 | ident.Z_to_pos
1226 | ident.fancy_add
1227 | ident.fancy_addc
1228 | ident.fancy_sub
1229 | ident.fancy_subb
1230 | ident.fancy_mulll
1231 | ident.fancy_mullh
1232 | ident.fancy_mulhl
1233 | ident.fancy_mulhh
1234 | ident.fancy_rshi
1235 | ident.fancy_selc
1236 | ident.fancy_selm
1237 | ident.fancy_sell
1238 | ident.fancy_addm
1239 => symex_T_error (Unhandled_identifier idc)
1240 end%symex).
1241 all: cbn in *.
1242 Defined.
1243
1244 Fixpoint symex_expr {opts : symbolic_options_computed_opt} {descr:description} {t} (e : API.expr (var:=var) t) : symex_T t
1245 := let _ := @Compilers.ToString.PHOAS.expr.partially_show_expr in
1246 match e in expr.expr t return symex_T t with
1247 | expr.Ident _ idc => symex_ident idc
1248 | expr.Var _ v => symex_T_return v
1249 | expr.Abs (type.base _) _ f => fun v => symex_expr (f v)
1250 | expr.App (type.base _) _ f x
1251 => let ef := symex_expr f in
1252 let ex := symex_expr x in
1253 symex_T_bind_base ex ef
1254 | expr.LetIn (type.base _) _ x f
1255 => let ef v := symex_expr (f v) in
1256 let ex := symex_expr (descr:=Build_description (show x) false) x in
1257 symex_T_bind_base ex ef
1258 | expr.App (type.arrow _ _) _ f x
1259 => symex_T_error (Invalid_higher_order_application f x)
1260 | expr.LetIn (type.arrow _ _) _ x f
1261 => symex_T_error (Invalid_higher_order_let x)
1262 | expr.Abs (type.arrow _ _) _ _
1263 => fun v : Empty_set => match v with end
1264 end.
1265
1266 (* takes and returns PHOAS-style things *)
1267 Definition symex_PHOAS_PHOAS {opts : symbolic_options_computed_opt} {t} (expr : API.Expr t) (input_var_data : type.for_each_lhs_of_arrow _ t) (d : dag)
1268 : ErrorT EquivalenceCheckingError (base_var (type.final_codomain t) * dag)
1269 := let ast : API.expr (type.base (type.final_codomain t))
1270 := invert_expr.smart_App_curried (expr _) input_var_data in
1271 symex_expr (descr:=no_description) ast d.
1272
1273 (* takes and returns assembly/list style things *)
1274 Definition symex_PHOAS
1275 {opts : symbolic_options_computed_opt}
1276 {t} (expr : API.Expr t)
1277 (inputs : list (idx + list idx))
1278 (d : dag)
1279 : ErrorT EquivalenceCheckingError (list (idx + list idx) * dag)
1280 := (input_var_data <- build_input_var t inputs;
1281 let '(input_var_data, unused_inputs) := input_var_data in
1282 _ <- (if (List.length unused_inputs =? 0)%nat
1283 then Success tt
1284 else Error (Internal_error_extra_input_arguments t unused_inputs));
1285 symevaled_PHOAS <- symex_PHOAS_PHOAS expr input_var_data d;
1286 let '(PHOAS_output, d) := symevaled_PHOAS in
1287 PHOAS_output <- simplify_base_var PHOAS_output;
1288 Success (PHOAS_output, d)).
1289
1290 Definition init_symbolic_state_descr : description := Build_description "init_symbolic_state" true.
1291
1292 Definition init_symbolic_state (d : dag) : symbolic_state
1293 := let _ := init_symbolic_state_descr in
1294 let '(initial_reg_idxs, d) := dag_gensym_n (List.length widest_registers) d in
1295 {|
1296 dag_state := d;
1297 symbolic_reg_state := Tuple.from_list_default None _ (List.map Some initial_reg_idxs);
1298 symbolic_mem_state := [];
1299 symbolic_flag_state := Tuple.repeat None 6;
1300 |}.
1301
1302 Definition compute_stack_base {opts : symbolic_options_computed_opt} {descr:description} (stack_size : nat) : M idx
1303 := (rsp_val <- SetRegFresh rsp;
1304 stack_size <- Symbolic.App (zconst 64 (-8 * Z.of_nat stack_size), []);
1305 Symbolic.App (add 64%N, [rsp_val; stack_size]))%x86symex.
1306
1307 Definition build_merge_stack_placeholders {opts : symbolic_options_computed_opt} {descr:description} (stack_size : nat)
1308 : M idx
1309 := (stack_placeholders <- lift_dag (build_inputarray stack_size);
1310 stack_base <- compute_stack_base stack_size;
1311 _ <- build_merge_array_addresses stack_base stack_placeholders;
1312 ret stack_base)%x86symex.
1313
1314 Definition LoadArray {opts : symbolic_options_computed_opt} {descr:description} (base : idx) (len : nat) : M (list idx)
1315 := mapM (fun i =>
1316 (addr <- compute_array_address base i;
1317 Remove64 addr)%x86symex)
1318 (seq 0 len).
1319
1320 Definition LoadOutputs_internal {opts : symbolic_options_computed_opt} {descr:description} {dereference_scalar:bool} (outputaddrs : list ((REG + idx) + idx)) (output_types : type_spec)
1321 : M (list (idx + list idx))
1322 := (mapM (fun '(ocells, spec) =>
1323 match ocells, spec with
1324 | inl _, Some _ | inr _, None => err (error.unsupported_memory_access_size 0)
1325 | inl addr, None
1326 => (v <- match addr, dereference_scalar with
1327 | inl r, false
1328 => GetReg r
1329 | inr addr, true
1330 => Remove64 addr
1331 | inl _, true | inr _, false => err (error.unsupported_memory_access_size 0)
1332 end;
1333 ret (inl v))
1334 | inr base, Some len
1335 => (v <- LoadArray base len;
1336 ret (inr v))
1337 end) (List.combine outputaddrs output_types))%N%x86symex.
1338
1339 Definition LoadOutputs {opts : symbolic_options_computed_opt} {descr:description} {dereference_scalar:bool} (outputaddrs : list ((REG + idx) + idx)) (output_types : type_spec)
1340 : M (ErrorT EquivalenceCheckingError (list (idx + list idx)))
1341 := (* In the following line, we match on the result so we can emit Internal_error_output_load_failed in the calling function, rather than passing through the placeholder error from LoadOutputs *)
1342 fun s => if (List.length outputaddrs =? List.length output_types)%nat
1343 then match LoadOutputs_internal (dereference_scalar:=dereference_scalar) outputaddrs output_types s with
1344 | Success (v, s) => Success (Success v, s)
1345 | Error (err, s)
1346 => Success (Error (Internal_error_output_load_failed
1347 match err with
1348 | error.unsupported_memory_access_size 0%N => None (* placeholder *)
1349 | _ => Some err
1350 end
1351 outputaddrs s), s)
1352 end
1353 else
1354 Success (Error (Internal_error_LoadOutputs_length_mismatch outputaddrs output_types), s).
1355
1356 Definition symex_asm_func_M
1357 {opts : symbolic_options_computed_opt}
1358 (dereference_input_scalars:=false)
1359 {dereference_output_scalars:bool}
1360 (callee_saved_registers : list REG)
1361 (output_types : type_spec) (stack_size : nat)
1362 (inputs : list (idx + list idx)) (reg_available : list REG) (asm : Lines)
1363 : M (ErrorT EquivalenceCheckingError (list (idx + list idx)))
1364 := (output_placeholders <- lift_dag (build_inputs (descr:=Build_description "output_placeholders" true) output_types);
1365 let n_outputs := List.length output_placeholders in
1366 (* to make proofs easier, we merge addresses in reverse order from reading them *)
1367 inputaddrs <- build_merge_base_addresses (descr:=Build_description "inputaddrs" true) (dereference_scalar:=dereference_input_scalars) inputs (skipn n_outputs reg_available);
1368 outputaddrs <- build_merge_base_addresses (descr:=Build_description "outputaddrs" true) (dereference_scalar:=dereference_output_scalars) output_placeholders (firstn n_outputs reg_available);
1369 stack_base <- build_merge_stack_placeholders (descr:=Build_description "stack_base" true) stack_size;
1370 initial_register_values <- mapM (GetReg (descr:=Build_description "initial_register_values" true)) callee_saved_registers;
1371 _ <- SymexLines asm;
1372 final_register_values <- mapM (GetReg (descr:=Build_description "final_register_values" true)) callee_saved_registers;
1373 _ <- LoadArray (descr:=Build_description "load final stack" true) stack_base stack_size;
1374 let unsaved_registers : list (REG * (idx * idx)) := List.filter (fun '(r, (init, final)) => negb (init =? final)%N) (List.combine callee_saved_registers (List.combine initial_register_values final_register_values)) in
1375 asm_output <- LoadOutputs (descr:=Build_description "asm_output" true) (dereference_scalar:=dereference_output_scalars) outputaddrs output_types;
1376 (* also load inputs, for the sake of the proof *)
1377 (* reconstruct input types *)
1378 let input_types := List.map (fun v => match v with inl _ => None | inr ls => Some (List.length ls) end) inputs in
1379 asm_input <- LoadOutputs (descr:=Build_description "asm_input <- LoadOutputs" true) (dereference_scalar:=dereference_input_scalars) inputaddrs input_types;
1380 (fun s => Success
1381 (match asm_output, asm_input, unsaved_registers, s.(symbolic_mem_state) with
1382 | Success asm_output, Success _, [], []
1383 => Success asm_output
1384 | Error err, _, _, _
1385 | _, Error err, _, _
1386 => Error err
1387 | Success _, Success _, (_ :: _) as unsaved_registers, _
1388 => Error (Registers_not_saved unsaved_registers s)
1389 | Success _, Success _, _, (_ :: _) as mem_remaining
1390 => Error (Internal_error_lingering_memory s)
1391 end,
1392 s)))%N%x86symex.
1393
1394 Definition symex_asm_func
1395 {opts : symbolic_options_computed_opt}
1396 {dereference_output_scalars:bool}
1397 (d : dag) (callee_saved_registers : list REG) (output_types : type_spec) (stack_size : nat)
1398 (inputs : list (idx + list idx)) (reg_available : list REG) (asm : Lines)
1399 : ErrorT EquivalenceCheckingError (list (idx + list idx) * symbolic_state)
1400 := let num_reg_given := List.length reg_available in
1401 let num_reg_needed := List.length inputs + List.length output_types in
1402 if (num_reg_given <? num_reg_needed)%nat
1403 then
1404 Error (Not_enough_registers num_reg_given num_reg_needed)
1405 else
1406 let register_wide_enough := fun reg => (reg_size reg =? 64)%N in
1407 if negb (forallb register_wide_enough reg_available)
1408 then
1409 Error (Registers_too_narrow (filter (fun reg => negb (register_wide_enough reg)) reg_available))
1410 else
1411 if negb (forallb register_wide_enough callee_saved_registers)
1412 then
1413 Error (Callee_saved_registers_too_narrow (filter (fun reg => negb (register_wide_enough reg)) callee_saved_registers))
1414 else
1415 if negb (list_beq _ REG_beq (remove_duplicates REG_beq reg_available) reg_available)
1416 then
1417 Error (Duplicate_registers (find_duplicates REG_beq reg_available))
1418 else
1419 match symex_asm_func_M (dereference_output_scalars:=dereference_output_scalars) callee_saved_registers output_types stack_size inputs reg_available asm (init_symbolic_state d) with
1420 | Error (e, s) => Error (Symbolic_execution_failed e s)
1421 | Success (Error err, s) => Error err
1422 | Success (Success asm_output, s) => Success (asm_output, s)
1423 end.
1424
1425 Section check_equivalence.
1426 Context {symbolic_opts : symbolic_options_computed_opt}
1427 {assembly_calling_registers' : assembly_calling_registers_opt}
1428 {assembly_stack_size' : assembly_stack_size_opt}
1429 {assembly_output_first : assembly_output_first_opt}
1430 {assembly_argument_registers_left_to_right : assembly_argument_registers_left_to_right_opt}
1431 {assembly_callee_saved_registers' : assembly_callee_saved_registers_opt}.
1432
1433 Section with_expr.
1434 Context {t}
1435 (asm : list (string (* fname *) * Lines))
1436 (expr : API.Expr t)
1437 (arg_bounds : type.for_each_lhs_of_arrow ZRange.type.option.interp t)
1438 (out_bounds : ZRange.type.base.option.interp (type.final_codomain t)).
1439
1440 Definition strip_ret (asm : Lines) :=
1441 let isinstr := fun l => match l.(rawline) with INSTR _ => true | _ => false end in
1442 let notret := fun l => match l.(rawline) with
1443 | INSTR {| Syntax.op := Syntax.ret ; Syntax.args := nil |} => false
1444 | _ => true
1445 end in
1446 match dropWhile notret asm with
1447 | nil => Error Missing_ret
1448 | cons _r trailer =>
1449 if List.existsb isinstr trailer then Error (Code_after_ret (List.filter isinstr trailer) trailer)
1450 else Success (takeWhile notret asm)
1451 end.
1452
1453 Local Notation map_err_None v := (ErrorT.map_error (fun e => (None, e)) v).
1454 Local Notation map_err_Some label v := (ErrorT.map_error (fun e => (Some label, e)) v).
1455
1456 Definition map_symex_asm (inputs : list (idx + list idx)) (output_types : type_spec) (d : dag)
1457 : ErrorT
1458 (option (string (* fname *) * Lines (* asm lines *)) * EquivalenceCheckingError)
1459 (list ((string (* fname *) * Lines (* asm lines *)) * (list (idx + list idx) * symbolic_state))) :=
1460 let reg_available := assembly_calling_registers (* registers available for calling conventions *) in
1461 (ls <-- (List.map
1462 (fun '((fname, asm) as label)
1463 => (asm <- map_err_Some label (strip_ret asm);
1464 let stack_size : nat := N.to_nat (assembly_stack_size asm) in
1465 symevaled_asm <- map_err_Some label (symex_asm_func (dereference_output_scalars:=false) d assembly_callee_saved_registers output_types stack_size inputs reg_available asm);
1466 Success (label, symevaled_asm)))
1467 asm);
1468 Success ls)%error.
1469
1470 Definition check_equivalence : ErrorT (option (string (* fname *) * Lines (* asm lines *)) * EquivalenceCheckingError) unit :=
1471 let d := dag.empty in
1472 input_types <- map_err_None (simplify_input_type t arg_bounds);
1473 output_types <- map_err_None (simplify_base_type (type.final_codomain t) out_bounds);
1474 let '(inputs, d) := build_inputs (descr:=Build_description "build_inputs" true) input_types d in
1475
1476 ls <- (
1477 if negb debug_symex_asm_first then (
1478 PHOAS_output <- map_err_None (symex_PHOAS expr inputs d);
1479 let '(PHOAS_output, d) := PHOAS_output in
1480
1481 let first_new_idx_after_all_old_idxs : option idx := Some (dag.size d) in
1482
1483 asm_output <- map_symex_asm inputs output_types d;
1484
1485 let ls := List.map (fun '(lbl, (asm_output, s)) => (lbl, asm_output, PHOAS_output, s, first_new_idx_after_all_old_idxs)) asm_output in
1486 Success ls
1487 ) else ( (* debug version, do asm first *)
1488 asm_output <- map_symex_asm inputs output_types d;
1489
1490 ls <-- (List.map (fun '(lbl, (asm_output, s)) =>
1491 let d := s.(dag_state) in
1492 let first_new_idx_after_all_old_idxs : option idx := Some (dag.size d) in
1493
1494 PHOAS_output <- map_err_None (symex_PHOAS expr inputs d);
1495 let '(PHOAS_output, d) := PHOAS_output in
1496
1497 let s := {| dag_state := d; symbolic_reg_state := s.(symbolic_reg_state); symbolic_flag_state := s.(symbolic_flag_state); symbolic_mem_state := s.(symbolic_mem_state) |} in
1498
1499 Success (lbl, asm_output, PHOAS_output, s, first_new_idx_after_all_old_idxs))
1500 asm_output);
1501 Success ls
1502 ));
1503
1504 _ <-- List.map (fun '(lbl, asm_output, PHOAS_output, s, first_new_idx_after_all_old_idxs) =>
1505 if list_beq _ (sum_beq _ _ N.eqb (list_beq _ N.eqb)) asm_output PHOAS_output
1506 then Success tt
1507 else Error (Some lbl, Unable_to_unify asm_output PHOAS_output first_new_idx_after_all_old_idxs s))
1508 ls;
1509 Success tt.
1510
1511
1512 (** We don't actually generate assembly, we just check equivalence and pass assembly through unchanged *)
1513 Definition generate_assembly_of_hinted_expr : ErrorT (option (string (* fname *) * Lines (* asm lines *)) * EquivalenceCheckingError) (list (string * Lines))
1514 := match check_equivalence with
1515 | Success tt => Success asm (* the asm is equivalent, so we can emit this asm *)
1516 | Error err => Error err
1517 end.
1518 End with_expr.
1519 End check_equivalence.