Debian Codegraph @

src/PushButtonSynthesis/DettmanMultiplication.v

raw
1 (** * Push-Button Synthesis of Dettman Multiplication *)
2 From Coq Require Import String.
3 From Coq Require Import Lia.
4 From Coq Require Import ZArith.
5 From Coq Require Import MSetPositive.
6 From Coq Require Import List.
7 From Coq Require Import QArith_base Qround.
8 From Coq Require Import Derive.
9 Require Import Crypto.Util.ErrorT.
10 Require Import Crypto.Util.ListUtil.
11 Require Import Crypto.Util.ListUtil.FoldBool.
12 Require Import Crypto.Util.Strings.Decimal.
13 Require Import Crypto.Util.Strings.Show.
14 Require Import Crypto.Util.ZRange.
15 Require Import Crypto.Util.ZUtil.Definitions.
16 Require Import Crypto.Util.ZUtil.Zselect.
17 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
18 Require Import Crypto.Util.Tactics.HasBody.
19 Require Import Crypto.Util.Tactics.Head.
20 Require Import Crypto.Util.Tactics.SpecializeBy.
21 Require Import Rewriter.Language.Wf.
22 Require Import Rewriter.Language.Language.
23 Require Import Crypto.Language.API.
24 Require Import Crypto.AbstractInterpretation.AbstractInterpretation.
25 Require Import Crypto.Stringification.Language.
26 Require Import Crypto.Arithmetic.Core.
27 Require Import Crypto.Arithmetic.ModOps.
28 Require Import Crypto.BoundsPipeline.
29 Require Import Crypto.COperationSpecifications.
30 Require Import Crypto.PushButtonSynthesis.ReificationCache.
31 Require Import Crypto.PushButtonSynthesis.Primitives.
32 Require Import Crypto.PushButtonSynthesis.DettmanMultiplicationReificationCache.
33 Require Import Crypto.Arithmetic.DettmanMultiplication.
34
35 Require Import Crypto.Assembly.Equivalence.
36 Import ListNotations.
37 Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.
38
39 Import
40 Language.Wf.Compilers
41 Language.Compilers
42 AbstractInterpretation.Compilers
43 Stringification.Language.Compilers.
44 Import Compilers.API.
45
46 Import COperationSpecifications.Primitives.
47 Import COperationSpecifications.DettmanMultiplication.
48
49 Import Associational Positional.
50
51 Import dettman_multiplication_mod_ops.
52
53 Local Coercion Z.of_nat : nat >-> Z.
54 Local Coercion QArith_base.inject_Z : Z >-> Q.
55 Local Coercion Z.pos : positive >-> Z.
56
57 Local Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)
58 (* needed for making [autorewrite] not take a very long time *)
59 Local Opaque reified_mul_gen.
60 Local Opaque reified_square_gen.
61 (* needed for making [autorewrite] with [Set Keyed Unification] fast *)
62 Local Opaque expr.Interp.
63
64 Section __.
65 Context {output_language_api : ToString.OutputLanguageAPI}
66 {pipeline_opts : PipelineOptions}
67 {pipeline_to_string_opts : PipelineToStringOptions}
68 {synthesis_opts : SynthesisOptions}
69 (machine_wordsize : machine_wordsize_opt)
70 (s : Z)
71 (c_ : list (Z*Z))
72 (n : nat) (* number of limbs *)
73 (last_limb_width : nat)
74 (last_reduction : nat)
75 (inbounds_multiplier : option Q).
76
77 Local Instance override_pipeline_opts : PipelineOptions
78 := {| widen_bytes := true (* true, because we don't allow byte-sized things anyway, so we should not expect carries to be widened to byte-size when emitting C code *)
79 |}.
80
81 (* We include [0], so that even after bounds relaxation, we can
82 notice where the constant 0s are, and remove them. *)
83 Definition possible_values_of_machine_wordsize
84 := prefix_with_carry [machine_wordsize; 2 * machine_wordsize].
85
86 Local Notation c := (Associational.eval c_).
87 Definition m := s - c.
88
89 Local Notation possible_values := possible_values_of_machine_wordsize.
90
91 Definition input_magnitude := Option.value inbounds_multiplier 1.
92 Definition output_magnitude_first_limbs : Q := input_magnitude / 2 + 1 / 2.
93 Definition output_magnitude_last_limb : Q := input_magnitude / 2 + 1 / 4.
94 (* Where these bounds came from:
95 https://github.com/bitcoin-core/secp256k1/blob/0eb3000417fcf996e3805d0eb00f0f32b8849315/src/field_5x52_impl.h#L545
96 These bounds are correct, and reasonably tight, for the following parameters:
97 s = 2^256
98 c = 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
99 n = 5
100 last_limb_width = 48
101 last_reduction = 2.
102
103 s = 2^256
104 c = 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
105 n = 10
106 last_limb_width = 22
107 last_reduction = 6.
108 Given parameters dissimilar to those above, these bounds are no better than a guess.
109 I suppose they provide a reasonable default, though. *)
110
111 Definition weightf := dettman_multiplication_mod_ops.weight s n last_limb_width.
112 Definition input_bounds : list (ZRange.type.option.interp base.type.Z)
113 := fold_left (fun l i => Some r[0 ~> Qceiling (2 * input_magnitude * ((weightf (i + 1) / weightf i) - 1))]%zrange :: l) (seq 0 (n - 1)) [] ++
114 [Some r[0 ~> Qceiling (2 * input_magnitude * (2^last_limb_width - 1))]%zrange].
115 Definition output_bounds : list (ZRange.type.option.interp base.type.Z)
116 := fold_left (fun l i => Some r[0 ~> Qceiling (2 * output_magnitude_first_limbs * ((weightf (i + 1) / weightf i) - 1))]%zrange :: l) (seq 0 (n - 1)) [] ++
117 [Some r[0 ~> Qceiling (2 * output_magnitude_last_limb * (2^last_limb_width - 1))]%zrange].
118 Local Existing Instance default_translate_to_fancy.
119 Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.
120 Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.
121 Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.
122
123 (** Note: If you change the name or type signature of this
124 function, you will need to update the code in CLI.v *)
125 Definition check_args {T} (requests : list string) (res : Pipeline.ErrorT T)
126 : Pipeline.ErrorT T
127 := check_args_of_list
128 (List.map
129 (fun v => (true, v))
130 [(negb (s - c =? 0), Pipeline.Values_not_provably_distinctZ "s - c <> 0" (s - c) 0)
131 ; (4 <=? n, Pipeline.Value_not_leZ "4 <= n" 4 n)
132 ; (last_limb_width * n <=? Z.log2 s, Pipeline.Value_not_leZ "last_limb_width * n <= Z.log2 s" (last_limb_width * n) (Z.log2 s))
133 ; (1 <=? last_limb_width, Pipeline.Value_not_leZ "1 <= last_limb_width" 1 last_limb_width)
134 ; (2 ^ (Z.log2 s) =? s, Pipeline.Values_not_provably_equalZ "2 ^ (Z.log2 s) = s" (2 ^ Z.log2 s) s)
135 ; (Z.log2 s - last_limb_width <=? (Z.to_nat machine_wordsize) * (n - 1), Pipeline.Value_not_leZ "Z.log2 s - last_limb_width <= machine_wordsize * (n - 1)" (Z.log2 s - last_limb_width) (Z.to_nat machine_wordsize * (n - 1)))
136 ; (Z.log2 s <=? n * (Z.log2 s - last_limb_width) / (n - 1), Pipeline.Value_not_leZ "Z.log2 s <= n * (Z.log2 s - last_limb_width) / (n - 1)" (Z.log2 s) (n * (Z.log2 s - last_limb_width) / (n - 1)))
137 ])
138 res.
139
140 Context (requests : list string)
141 (curve_good : check_args requests (Success tt) = Success tt).
142
143 Lemma use_curve_good
144 : s - c <> 0
145 /\ (4 <= n)
146 /\ last_limb_width * n <= Z.log2 s
147 /\ 1 <= last_limb_width
148 /\ 2 ^ (Z.log2 s) = s
149 /\ Z.log2 s - last_limb_width <= (Z.to_nat machine_wordsize) * (n - 1)
150 /\ Z.log2 s <= n * (Z.log2 s - last_limb_width) / (n - 1).
151 Proof using curve_good. prepare_use_curve_good (). Qed.
152
153 Local Notation evalf := (eval weightf n).
154 Local Notation notations_for_docstring
155 := (CorrectnessStringification.dyn_context.cons
156 weightf "weight"
157 (CorrectnessStringification.dyn_context.cons
158 evalf "eval"
159 CorrectnessStringification.dyn_context.nil))%string.
160 Local Notation "'docstring_with_summary_from_lemma!' summary correctness"
161 := (docstring_with_summary_from_lemma_with_ctx!
162 notations_for_docstring
163 summary
164 correctness)
165 (only parsing, at level 10, summary at next level, correctness at next level).
166
167 Definition mul
168 := Pipeline.BoundsPipeline
169 false (* subst01 *)
170 possible_values
171 (reified_mul_gen
172 @ GallinaReify.Reify s @ GallinaReify.Reify c
173 @ GallinaReify.Reify (Z.to_nat machine_wordsize) @ GallinaReify.Reify n
174 @ GallinaReify.Reify last_limb_width @ GallinaReify.Reify last_reduction)
175 (Some input_bounds, (Some input_bounds, tt))
176 (Some output_bounds).
177
178 Definition square
179 := Pipeline.BoundsPipeline
180 false (* subst01 *)
181 possible_values
182 (reified_square_gen
183 @ GallinaReify.Reify s @ GallinaReify.Reify c
184 @ GallinaReify.Reify (Z.to_nat machine_wordsize) @ GallinaReify.Reify n
185 @ GallinaReify.Reify last_limb_width @ GallinaReify.Reify last_reduction)
186 (Some input_bounds, tt)
187 (Some output_bounds).
188
189 Definition smul (prefix : string)
190 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
191 := Eval cbv beta in
192 FromPipelineToString!
193 machine_wordsize prefix "mul" mul
194 (docstring_with_summary_from_lemma!
195 (fun fname : string => [text_before_function_name ++ fname ++ " multiplies two field elements."]%string)
196 (mul_correct weightf n m input_bounds output_bounds)).
197
198 Definition ssquare (prefix : string)
199 : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))
200 := Eval cbv beta in
201 FromPipelineToString!
202 machine_wordsize prefix "square" square
203 (docstring_with_summary_from_lemma!
204 (fun fname : string => [text_before_function_name ++ fname ++ " squares a field element."]%string)
205 (square_correct weightf n m input_bounds output_bounds)).
206
207 (** Work around COQBUG(https://github.com/coq/coq/issues/9286) *)
208 Local Opaque DettmanMultiplication.mulmod DettmanMultiplication.squaremod.
209
210 Local Ltac prove_correctness _ := Primitives.prove_correctness use_curve_good.
211
212 Lemma mul_correct res
213 (Hres : mul = Success res)
214 : mul_correct (weightf) n m input_bounds output_bounds (Interp res).
215 Proof using curve_good. prove_correctness (). Qed.
216
217 Lemma Wf_mul res (Hres : mul = Success res) : Wf res.
218 Proof using Type. prove_pipeline_wf (). Qed.
219
220 Lemma square_correct res
221 (Hres : square = Success res)
222 : square_correct (weightf) n m input_bounds output_bounds (Interp res).
223 Proof using curve_good. prove_correctness (). Qed.
224
225 Lemma Wf_square res (Hres : square = Success res) : Wf res.
226 Proof using Type. prove_pipeline_wf (). Qed.
227
228 Section for_stringification.
229 Local Open Scope string_scope.
230 Local Open Scope list_scope.
231
232 Definition known_functions
233 := [("mul", wrap_s smul);
234 ("square", wrap_s ssquare)].
235
236 Definition valid_names : string := Eval compute in String.concat ", " (List.map (@fst _ _) known_functions).
237
238 (** Note: If you change the name or type signature of this
239 function, you will need to update the code in CLI.v *)
240 Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)
241 : list (synthesis_output_kind * string * Pipeline.M (list string))
242 := Primitives.Synthesize
243 machine_wordsize valid_names known_functions (fun _ => nil) all_typedefs!
244 check_args
245 ((ToString.comment_file_header_block
246 (comment_header
247 ++ ["";
248 "Computed values:";
249 ""; ""]%string)))
250 function_name_prefix requests.
251 End for_stringification.
252 End __.
253
254 Module Export Hints.
255 #[global]
256 Hint Opaque
257 mul
258 square
259 : wf_op_cache.
260 #[global]
261 Hint Immediate
262 Wf_mul
263 Wf_square
264 : wf_op_cache.
265 End Hints.