Debian Codegraph @

src/ArithmeticCPS/Saturated.v

raw
1 From Coq Require Import ZArith Lia.
2 From Coq Require Import List.
3 Require Import Crypto.Algebra.Ring.
4 Require Import Crypto.ArithmeticCPS.Core.
5 Require Import Crypto.Arithmetic.Partition.
6 Require Import Crypto.Util.CPSUtil.
7 Require Import Crypto.Util.CPSNotations.
8 Require Import Crypto.Util.Decidable.
9 Require Import Crypto.Util.LetIn.
10 Require Import Crypto.Util.ListUtil.
11 Require Import Crypto.Util.NatUtil.
12 Require Import Crypto.Util.Prod.
13 Require Import Crypto.Util.Tactics.BreakMatch.
14 Require Import Crypto.Util.Tactics.UniquePose.
15 Require Import Crypto.Util.ZUtil.Definitions.
16 Require Import Crypto.Util.ZUtil.AddGetCarry Crypto.Util.ZUtil.MulSplit.
17 Require Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.
18 Require Import Crypto.Util.ZUtil.Hints.Core.
19 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
20 Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
21 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
22
23 Require Import Crypto.Util.Notations.
24 Import ListNotations. Local Open Scope Z_scope.
25
26 Import CPSBindNotations.
27 Local Open Scope cps_scope.
28
29 Module Associational (Import RT : Runtime).
30 Section Associational.
31
32 Definition sat_multerm_cps s (t t' : (Z * Z)) : ~> list (Z * Z) :=
33 fun T k => dlet_nd xy := RT_Z.mul_split s (snd t) (snd t') in
34 k [(fst t * fst t', fst xy); (fst t * fst t' * s, snd xy)].
35
36 Definition sat_mul_cps s (p q : list (Z * Z)) : ~> list (Z * Z) :=
37 fun T => flat_map_cps (fun t T => flat_map_cps (fun t' => sat_multerm_cps s t t') q) p.
38
39 Definition sat_multerm_const_cps s (t t' : (Z * Z)) : ~> list (Z * Z) :=
40 fun T k
41 => if snd t =? 1
42 then k [(fst t * fst t', snd t')]
43 else if snd t =? -1
44 then k [(fst t * fst t', - snd t')]
45 else if snd t =? 0
46 then k nil
47 else dlet_nd xy := RT_Z.mul_split s (snd t) (snd t') in
48 k [(fst t * fst t', fst xy); (fst t * fst t' * s, snd xy)].
49
50 Definition sat_mul_const_cps s (p q : list (Z * Z)) : ~> list (Z * Z) :=
51 fun T => flat_map_cps (fun t T => flat_map_cps (fun t' => sat_multerm_const_cps s t t') q) p.
52 End Associational.
53 End Associational.
54
55 Module Columns (Import RT : Runtime).
56 Module Import Deps.
57 Module Import Positional := Positional RT.
58 End Deps.
59 Section Columns.
60 Context (weight : nat -> Z).
61
62 Definition eval n (x : list (list Z)) : Z := Positional.eval weight n (map sum x).
63
64 Section Flatten.
65 Section flatten_column.
66 Context (fw : Z). (* maximum size of the result *)
67
68 (* Outputs (sum, carry) *)
69 Definition flatten_column_cps (digit: list Z) : ~> (Z * Z) :=
70 list_rect (fun _ => ~> (Z * Z)%type) (return (0,0))
71 (fun xx tl flatten_column_tl =>
72 list_case
73 (fun _ => ~> (Z * Z)%type) (fun T k => k ((xx mod fw)%RT, (xx / fw)%RT))
74 (fun yy tl' =>
75 list_case
76 (fun _ => ~> (Z * Z)%type) (fun T k => dlet_nd x := xx in dlet_nd y := yy in k (RT_Z.add_get_carry_full fw x y))
77 (fun _ _ =>
78 flatten_column_tl <- flatten_column_tl;
79 fun T k => dlet_nd x := xx in
80 dlet_nd rec1 := fst flatten_column_tl in (* recursively get the sum and carry *)
81 dlet_nd rec2 := snd flatten_column_tl in
82 dlet_nd sum_carry := RT_Z.add_get_carry_full fw x rec1 in (* add the new value to the sum *)
83 dlet_nd carry' := (snd sum_carry + rec2)%RT in (* add the two carries together *)
84 k (fst sum_carry, carry'))
85 tl')
86 tl)
87 digit.
88 End flatten_column.
89
90 Definition flatten_step_cps (digit:list Z) (acc_carry:list Z * Z) : ~> list Z * Z :=
91 (sum_carry <- flatten_column_cps (weight (S (length (fst acc_carry))) / weight (length (fst acc_carry))) (snd acc_carry::digit);
92 dlet_nd sum := fst sum_carry in
93 dlet_nd carry := snd sum_carry in
94 return (fst acc_carry ++ sum :: nil, carry)).
95
96 Definition flatten (xs : list (list Z)) : ~> list Z * Z :=
97 fun T => fold_right_cps2 (fun a b => flatten_step_cps a b) (nil,0) (rev xs).
98 End Flatten.
99
100 Section FromAssociational.
101 (* nils *)
102 Definition nils n : list (list Z) := repeat nil n.
103 (* cons_to_nth *)
104 Definition cons_to_nth i x (xs : list (list Z)) : list (list Z) :=
105 ListUtil.update_nth i (fun y => cons x y) xs.
106
107 (* from_associational *)
108 Definition from_associational_cps n (p:list (Z*Z)) : ~> list (list Z) :=
109 fun T => fold_right_cps2 (fun t ls T k =>
110 let '(p1, p2) := Positional.place weight t (pred n) in
111 dlet_nd p2 := p2 in
112 k (cons_to_nth p1 p2 ls) ) (nils n) p.
113 End FromAssociational.
114 End Columns.
115 End Columns.
116
117 Module Rows (Import RT : Runtime).
118 Module Import Deps.
119 Module Associational := Associational RT.
120 Module Positional := Positional RT.
121 Module Columns := Columns RT.
122 Module Export Core.
123 Module Associational := ArithmeticCPS.Core.Associational RT.
124 End Core.
125 End Deps.
126 Section Rows.
127 Context (weight : nat -> Z).
128 Local Notation rows := (list (list Z)) (only parsing).
129 Local Notation cols := (list (list Z)) (only parsing).
130
131 Definition eval n (inp : rows) :=
132 sum (map (Positional.eval weight n) inp).
133
134 Section FromAssociational.
135 (* extract row *)
136 Definition extract_row (inp : cols) : cols * list Z := (map (fun c => tl c) inp, map (fun c => hd 0 c) inp).
137
138 Definition max_column_size (x:cols) := fold_right (fun a b => Nat.max a b) 0%nat (map (fun c => length c) x).
139
140 (* from_columns *)
141 Definition from_columns' n start_state : cols * rows :=
142 fold_right (fun _ (state : cols * rows) =>
143 let cols'_row := extract_row (fst state) in
144 (fst cols'_row, snd state ++ [snd cols'_row])
145 ) start_state (repeat 0 n).
146
147 Definition from_columns (inp : cols) : rows := snd (from_columns' (max_column_size inp) (inp, [])).
148
149 (* from associational *)
150 Definition from_associational_cps n (p : list (Z * Z)) : ~> _ :=
151 (p <- Columns.from_associational_cps weight n p; return (from_columns p)).
152 End FromAssociational.
153
154 Section Flatten.
155 Local Notation fw := (fun i => weight (S i) / weight i) (only parsing).
156
157 Section SumRows.
158 Definition sum_rows'_cps start_state (row1 row2 : list Z) : ~> list Z * Z * nat :=
159 fun T => fold_right_cps2 (fun next (state : list Z * Z * nat) T k =>
160 let i := snd state in
161 let low_high := fst state in
162 let low := fst low_high in
163 let high := snd low_high in
164 dlet_nd sum_carry := RT_Z.add_with_get_carry_full (fw i) high (fst next) (snd next) in
165 let low_high' := (low ++ [fst sum_carry], snd sum_carry) in
166 k (low_high', S i)) start_state (rev (combine row1 row2)).
167 Definition sum_rows_cps row1 row2 : ~> _ := (sum_rows' <- sum_rows'_cps (nil, 0, 0%nat) row1 row2; return (fst sum_rows')).
168 End SumRows.
169
170 Definition flatten'_cps (start_state : list Z * Z) (inp : rows) : ~> list Z * Z :=
171 fun T => fold_right_cps2 (fun next_row (state : list Z * Z)=>
172 out_carry <- sum_rows_cps (fst state) next_row;
173 return (fst out_carry, (snd state + snd out_carry)%RT)) start_state inp.
174
175 (* In order for the output to have the right length and bounds,
176 we insert rows of zeroes if there are fewer than two rows. *)
177 Definition flatten_cps n (inp : rows) : ~> list Z * Z :=
178 let default := Positional.zeros n in
179 flatten'_cps (hd default inp, 0) (hd default (tl inp) :: tl (tl inp)).
180 End Flatten.
181
182 Section Ops.
183 Definition add_cps n p q : ~> _ := flatten_cps n [p; q].
184
185 (* TODO: Although cleaner, using Positional.negate snd inserts
186 dlets which prevent add-opp=>sub transformation in partial
187 evaluation. Should probably either make partial evaluation
188 handle that or remove the dlet in Positional.from_associational.
189
190 NOTE(from jgross): I think partial evaluation now handles that
191 fine; we should check this. *)
192 Definition sub_cps n p q : ~> _ := (_q <- fun T => map_cps2 (fun x T k => dlet y := x in k (-y)%RT) q; flatten_cps n [p; _q]).
193
194 Definition conditional_add_cps n mask cond (p q:list Z) : ~> _ :=
195 (qq <- Positional.zselect_cps mask cond q;
196 add_cps n p qq).
197
198 (* Subtract q if and only if p >= q. *)
199 Definition conditional_sub_cps n (p q:list Z) : ~> _ :=
200 (vc <- sub_cps n p q;
201 let '(v, c) := vc in
202 return (Positional.select (-c)%RT v p)).
203
204 (* the carry will be 0 unless we underflow--we do the addition only
205 in the underflow case *)
206 Definition sub_then_maybe_add_cps n mask (p q r:list Z) : ~> _ :=
207 (p_minus_q_c <- sub_cps n p q;
208 let '(p_minus_q, c) := p_minus_q_c in
209 rr <- Positional.zselect_cps mask (-c)%RT r;
210 res_c' <- add_cps n p_minus_q rr;
211 let '(res, c') := res_c' in
212 return (res, (c' - c)%RT)).
213
214 Definition mul_cps base n m (p q : list Z) : ~> _ :=
215 let p_a := Positional.to_associational weight n p in
216 let q_a := Positional.to_associational weight n q in
217 (pq_a <- Associational.sat_mul_cps base p_a q_a;
218 pq_a <- from_associational_cps m pq_a;
219 flatten_cps m pq_a).
220
221 (* if [s] is not exactly equal to a weight, we must adjust it to
222 be a weight, so that rather than dividing by s and
223 multiplying by c, we divide by w and multiply by c*(w/s).
224 See
225 https://github.com/mit-plv/fiat-crypto/issues/326#issuecomment-404135131
226 for a bit more discussion *)
227 Definition adjust_s fuel s : Z * bool :=
228 fold_right
229 (fun w_i res
230 => let '(v, found_adjustment) := res in
231 let res := (v, found_adjustment) in
232 if found_adjustment:bool
233 then res
234 else if w_i mod s =? 0
235 then (w_i, true)
236 else res)
237 (s, false)
238 (map weight (List.rev (seq 0 fuel))).
239
240 (* TODO : move sat_reduce and repeat_sat_reduce to Saturated.Associational *)
241 Definition sat_reduce_cps base s c n (p : list (Z * Z)) : ~> _ :=
242 let '(s', _) := adjust_s (S (S n)) s in
243 let lo_hi := Associational.split s' p in
244 (p <- Associational.sat_mul_const_cps base c (snd lo_hi);
245 p <- Associational.sat_mul_const_cps base [(1, s'/s)] p;
246 return (fst lo_hi ++ p)).
247
248 Definition repeat_sat_reduce_cps base s c (p : list (Z * Z)) n : ~> _ :=
249 fun T => fold_right_cps2 (fun _ q => sat_reduce_cps base s c n q) p (seq 0 n).
250
251 Definition mulmod_cps base s c n nreductions (p q : list Z) : ~> _ :=
252 let p_a := Positional.to_associational weight n p in
253 let q_a := Positional.to_associational weight n q in
254 (pq_a <- Associational.sat_mul_cps base p_a q_a;
255 r_a <- repeat_sat_reduce_cps base s c pq_a nreductions;
256 r_a <- from_associational_cps n r_a;
257 flatten_cps n r_a).
258
259 (* returns all-but-lowest-limb and lowest limb *)
260 Definition divmod (p : list Z) : list Z * Z
261 := (tl p, hd 0 p).
262 End Ops.
263 End Rows.
264 End Rows.