chiark / gitweb /
math/mpreduce.c: Add extensive commentary.
[catacomb] / math / mpreduce.c
1 /* -*-c-*-
2  *
3  * Efficient reduction modulo nice primes
4  *
5  * (c) 2004 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Catacomb.
11  *
12  * Catacomb is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU Library General Public License as
14  * published by the Free Software Foundation; either version 2 of the
15  * License, or (at your option) any later version.
16  *
17  * Catacomb is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with Catacomb; if not, write to the Free
24  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25  * MA 02111-1307, USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include <mLib/darray.h>
31 #include <mLib/macros.h>
32
33 #include "mp.h"
34 #include "mpreduce.h"
35 #include "mpreduce-exp.h"
36
37 /*----- Data structures ---------------------------------------------------*/
38
39 DA_DECL(instr_v, mpreduce_instr);
40
41 /*----- Theory ------------------------------------------------------------*
42  *
43  * We're given a modulus %$p = 2^n - d$%, where %$d < 2^n$%, and some %$x$%,
44  * and we want to compute %$x \bmod p$%.  We work in base %$2^w$%, for some
45  * appropriate %$w$%.  The important observation is that
46  * %$d \equiv 2^n \pmod p$%.
47  *
48  * Suppose %$x = x' + z 2^k$%, where %$k \ge n$%; then
49  * %$x \equiv x' + d z 2^{k-n} \pmod p$%.  We can use this to trim the
50  * representation of %$x$%; each time, we reduce %$x$% by a mutliple of
51  * %$2^{k-n} p$%.  We can do this in two passes: firstly by taking whole
52  * words off the top, and then (if necessary) by trimming the top word.
53  * Finally, if %$p \le x < 2^n$% then %$0 \le x - p < p$% and we're done.
54  *
55  * A common trick, apparently, is to choose %$d$% such that it has a very
56  * sparse non-adjacent form, and, moreover, that this form is nicely aligned
57  * with common word sizes.  (That is, write %$d = \sum_{0\le i<m} d_i 2^i$%,
58  * with %$d_i \in \{ -1, 0, +1 \}$% and most %$d_i = 0$%.)  Then adding
59  * %$z d$% is a matter of adding and subtracting appropriately shifted copies
60  * of %$z$%.
61  *
62  * Most libraries come with hardwired code for doing this for a few
63  * well-known values of %$p$%.  We take a different approach, for two
64  * reasons.
65  *
66  *   * Firstly, it privileges built-in numbers over user-selected ones, even
67  *     if the latter have the right (or better) properties.
68  *
69  *   * Secondly, writing appropriately optimized reduction functions when we
70  *     don't know the exact characteristics of the target machine is rather
71  *     difficult.
72  *
73  * Our solution, then, is to `compile' the value %$p$% at runtime, into a
74  * sequence of simple instructions for doing the reduction.
75  */
76
77 /*----- Main code ---------------------------------------------------------*/
78
79 /* --- @mpreduce_create@ --- *
80  *
81  * Arguments:   @gfreduce *r@ = structure to fill in
82  *              @mp *x@ = an integer
83  *
84  * Returns:     Zero if successful; nonzero on failure.
85  *
86  * Use:         Initializes a context structure for reduction.
87  */
88
89 int mpreduce_create(mpreduce *r, mp *p)
90 {
91   mpscan sc;
92   enum { Z = 0, Z1 = 2, X = 4, X0 = 6 };
93   unsigned st = Z;
94   instr_v iv = DA_INIT;
95   unsigned long d, i;
96   unsigned op;
97   size_t w, b, bb;
98
99   /* --- Fill in the easy stuff --- */
100
101   if (!MP_POSP(p))
102     return (-1);
103   d = mp_bits(p);
104   r->lim = d/MPW_BITS;
105   r->s = d%MPW_BITS;
106   if (r->s)
107     r->lim++;
108   r->p = mp_copy(p);
109
110   /* --- Stash a new instruction --- */
111
112 #define INSTR(op_, argx_, argy_) do {                                   \
113   DA_ENSURE(&iv, 1);                                                    \
114   DA(&iv)[DA_LEN(&iv)].op = (op_);                                      \
115   DA(&iv)[DA_LEN(&iv)].argx = (argx_);                                  \
116   DA(&iv)[DA_LEN(&iv)].argy = (argy_);                                  \
117   DA_EXTEND(&iv, 1);                                                    \
118 } while (0)
119
120   /* --- Main loop --- *
121    *
122    * A simple state machine decomposes @p@ conveniently into positive and
123    * negative powers of 2.
124    *
125    * Here's the relevant theory.  The important observation is that
126    * %$2^i = 2^{i+1} - 2^i$%, and hence
127    *
128    *   * %$\sum_{a\le i<b} 2^i = 2^b - 2^a$%, and
129    *
130    *   * %$2^c - 2^{b+1} + 2^b - 2^a = 2^c - 2^b - 2^a$%.
131    *
132    * The first of these gives us a way of combining a run of several one
133    * bits, and the second gives us a way of handling a single-bit
134    * interruption in such a run.
135    *
136    * We start with a number %$p = \sum_{0\le i<n} p_i 2^i$%, and scan
137    * right-to-left using a simple state-machine keeping (approximate) track
138    * of the two previous bits.  The @Z@ states denote that we're in a string
139    * of zeros; @Z1@ means that we just saw a 1 bit after a sequence of zeros.
140    * Similarly, the @X@ states denote that we're in a string of ones; and
141    * @X0@ means that we just saw a zero bit after a sequence of ones.  The
142    * state machine lets us delay decisions about what to do when we've seen a
143    * change to the status quo (a one after a run of zeros, or vice-versa)
144    * until we've seen the next bit, so we can tell whether this is an
145    * isolated bit or the start of a new sequence.
146    *
147    * More formally: we define two functions %$Z^b_i$% and %$X^b_i$% as
148    * follows.
149    *
150    *   * %$Z^0_i(S, 0) = S$%
151    *   * %$Z^0_i(S, n) = Z^0_{i+1}(S, n)$%
152    *   * %$Z^0_i(S, n + 2^i) = Z^1_{i+1}(S, n)$%
153    *   * %$Z^1_i(S, n) = Z^0_{i+1}(S \cup \{ 2^{i-1} \}, n)$%
154    *   * %$Z^1_i(S, n + 2^i) = X^1_{i+1}(S \cup \{ -2^{i-1} \}, n)$%
155    *   * %$X^0_i(S, n) = Z^0_{i+1}(S, \{ 2^{i-1} \})$%
156    *   * %$X^0_i(S, n + 2^i) = X^1_{i+1}(S \cup \{ -2^{i-1} \}, n)$%
157    *   * %$X^1_i(S, n) = X^0_{i+1}(S, n)$%
158    *   * %$X^1_i(S, n + 2^i) = X^1_{i+1}(S, n)$%
159    *
160    * The reader may verify (by induction on %$n$%) that the following
161    * properties hold.
162    *
163    *   * %$Z^0_0(\emptyset, n)$% is well-defined for all %$n \ge 0$%
164    *   * %$\sum Z^b_i(S, n) = \sum S + n + b 2^{i-1}$%
165    *   * %$\sum X^b_i(S, n) = \sum S + n + (b + 1) 2^{i-1}$%
166    *
167    * From these, of course, we can deduce %$\sum Z^0_0(\emptyset, n) = n$%.
168    *
169    * We apply the above recurrence to build a simple instruction sequence for
170    * adding an appropriate multiple of %$d$% to a given number.  Suppose that
171    * %$2^{w(N-1)} \le 2^{n-1} \le p < 2^n \le 2^{wN}$%.  The machine which
172    * interprets these instructions does so in the context of a
173    * single-precision multiplicand @z@ and a pointer @v@ to the
174    * %%\emph{most}%% significant word of an %$N + 1$%-word integer, and the
175    * instruction sequence should add %$z d$% to this integer.
176    *
177    * The available instructions are named @MPRI_{ADD,SUB}{,LSL}@; they add
178    * (or subtract) %$z$% (shifted left by some amount, in the @LSL@ variants)
179    * to some word earlier than @v@.  The relevant quantities are encoded in
180    * the instruction's immediate operands.
181    */
182
183 #ifdef DEBUG
184   for (i = 0, mp_scan(&sc, p); mp_step(&sc); i++) {
185     switch (st | mp_bit(&sc)) {
186       case  Z | 1: st = Z1; break;
187       case Z1 | 0: st =  Z; printf("+ %lu\n", i - 1); break;
188       case Z1 | 1: st =  X; printf("- %lu\n", i - 1); break;
189       case  X | 0: st = X0; break;
190       case X0 | 1: st =  X; printf("- %lu\n", i - 1); break;
191       case X0 | 0: st =  Z; printf("+ %lu\n", i - 1); break;
192     }
193   }
194   if (st >= X) printf("+ %lu\n", i - 1);
195   st = Z;
196 #endif
197
198   bb = MPW_BITS - (d + 1)%MPW_BITS;
199   for (i = 0, mp_scan(&sc, p); i < d && mp_step(&sc); i++) {
200     switch (st | mp_bit(&sc)) {
201       case  Z | 1: st = Z1; break;
202       case Z1 | 0: st =  Z; op = MPRI_SUB; goto instr;
203       case Z1 | 1: st =  X; op = MPRI_ADD; goto instr;
204       case  X | 0: st = X0; break;
205       case X0 | 1: st =  X; op = MPRI_ADD; goto instr;
206       case X0 | 0: st =  Z; op = MPRI_SUB; goto instr;
207       instr:
208         w = (d - i)/MPW_BITS + 1;
209         b = (bb + i)%MPW_BITS;
210         INSTR(op | !!b, w, b);
211     }
212   }
213
214   /* --- This doesn't always work --- *
215    *
216    * If %$d \ge 2^{n-1}$% then the above recurrence will output a subtraction
217    * as the final instruction, which may sometimes underflow.  (It interprets
218    * such numbers as being in the form %$2^{n-1} + d$%.)  This is clearly
219    * bad, so detect the situation and fail gracefully.
220    */
221
222   if (DA_LEN(&iv) && (DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
223     mp_drop(r->p);
224     DA_DESTROY(&iv);
225     return (-1);
226   }
227
228 #undef INSTR
229
230   /* --- Wrap up --- *
231    *
232    * Store the generated instruction sequence in our context structure.  If
233    * %$p$%'s bit length %$n$% is a multiple of the word size %$w$% then
234    * there's nothing much else to do here.  Otherwise, we have an additional
235    * job.
236    *
237    * The reduction operation has three phases.  The first trims entire words
238    * from the argument, and the instruction sequence constructed above does
239    * this well; the second phase reduces an integer which has the same number
240    * of words as %$p$%, but strictly more bits.  (The third phase is a single
241    * conditional subtraction of %$p$%, in case the argument is the same bit
242    * length as %$p$% but greater; this doesn't concern us here.)  To handle
243    * the second phase, we create another copy of the instruction stream, with
244    * all of the target shifts adjusted upwards by %$s = n \bmod w$%.
245    *
246    * In this case, we are acting on an %$(N - 1)$%-word operand, and so
247    * (given the remarks above) must check that this is still valid, but a
248    * moment's reflection shows that this must be fine: the most distant
249    * target must be the bit %$s$% from the top of the least-significant word;
250    * but since we shift all of the targets up by %$s$%, this now addresses
251    * the bottom bit of the next most significant word, and there is no
252    * underflow.
253    */
254
255   r->in = DA_LEN(&iv);
256   if (!r->in)
257     r->iv = 0;
258   else if (!r->s) {
259     r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
260     memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
261   } else {
262     r->iv = xmalloc(r->in * 2 * sizeof(mpreduce_instr));
263     for (i = 0; i < r->in; i++) {
264       r->iv[i] = DA(&iv)[i];
265       op = r->iv[i].op & ~1u;
266       w = r->iv[i].argx;
267       b = r->iv[i].argy;
268       b += r->s;
269       if (b >= MPW_BITS) {
270         b -= MPW_BITS;
271         w--;
272       }
273       if (b) op |= 1;
274       r->iv[i + r->in].op = op;
275       r->iv[i + r->in].argx = w;
276       r->iv[i + r->in].argy = b;
277     }
278   }
279   DA_DESTROY(&iv);
280
281 #ifdef DEBUG
282   mpreduce_dump(r, stdout);
283 #endif
284   return (0);
285 }
286
287 /* --- @mpreduce_destroy@ --- *
288  *
289  * Arguments:   @mpreduce *r@ = structure to free
290  *
291  * Returns:     ---
292  *
293  * Use:         Reclaims the resources from a reduction context.
294  */
295
296 void mpreduce_destroy(mpreduce *r)
297 {
298   mp_drop(r->p);
299   if (r->iv) xfree(r->iv);
300 }
301
302 /* --- @mpreduce_dump@ --- *
303  *
304  * Arguments:   @mpreduce *r@ = structure to dump
305  *              @FILE *fp@ = file to dump on
306  *
307  * Returns:     ---
308  *
309  * Use:         Dumps a reduction context.
310  */
311
312 void mpreduce_dump(mpreduce *r, FILE *fp)
313 {
314   size_t i;
315   static const char *opname[] = { "add", "addshift", "sub", "subshift" };
316
317   fprintf(fp, "mod = "); mp_writefile(r->p, fp, 16);
318   fprintf(fp, "\n  lim = %lu; s = %d\n", (unsigned long)r->lim, r->s);
319   for (i = 0; i < r->in; i++) {
320     assert(r->iv[i].op < N(opname));
321     fprintf(fp, "  %s %lu %lu\n",
322             opname[r->iv[i].op],
323             (unsigned long)r->iv[i].argx,
324             (unsigned long)r->iv[i].argy);
325   }
326   if (r->s) {
327     fprintf(fp, "tail end charlie\n");
328     for (i = r->in; i < 2 * r->in; i++) {
329       assert(r->iv[i].op < N(opname));
330       fprintf(fp, "  %s %lu %lu\n",
331               opname[r->iv[i].op],
332               (unsigned long)r->iv[i].argx,
333               (unsigned long)r->iv[i].argy);
334     }
335   }
336 }
337
338 /* --- @mpreduce_do@ --- *
339  *
340  * Arguments:   @mpreduce *r@ = reduction context
341  *              @mp *d@ = destination
342  *              @mp *x@ = source
343  *
344  * Returns:     Destination, @x@ reduced modulo the reduction poly.
345  */
346
347 static void run(const mpreduce_instr *i, const mpreduce_instr *il,
348                 mpw *v, mpw z)
349 {
350   for (; i < il; i++) {
351 #ifdef DEBUG
352     mp vv;
353     mp_build(&vv, v - i->argx, v + 1);
354     printf("  0x"); mp_writefile(&vv, stdout, 16);
355     printf(" %c (0x%lx << %u) == 0x",
356            (i->op & ~1u) == MPRI_ADD ? '+' : '-',
357            (unsigned long)z,
358            i->argy);
359 #endif
360     switch (i->op) {
361       case MPRI_ADD: MPX_UADDN(v - i->argx, v + 1, z); break;
362       case MPRI_ADDLSL: mpx_uaddnlsl(v - i->argx, v + 1, z, i->argy); break;
363       case MPRI_SUB: MPX_USUBN(v - i->argx, v + 1, z); break;
364       case MPRI_SUBLSL: mpx_usubnlsl(v - i->argx, v + 1, z, i->argy); break;
365       default:
366         abort();
367     }
368 #ifdef DEBUG
369     mp_build(&vv, v - i->argx, v + 1);
370     mp_writefile(&vv, stdout, 16);
371     printf("\n");
372 #endif
373   }
374 }
375
376 mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
377 {
378   mpw *v, *vl;
379   const mpreduce_instr *il;
380   mpw z;
381
382 #ifdef DEBUG
383   mp *_r = 0, *_rr = 0;
384 #endif
385
386   /* --- If source is negative, divide --- */
387
388   if (MP_NEGP(x)) {
389     mp_div(0, &d, x, r->p);
390     return (d);
391   }
392
393   /* --- Try to reuse the source's space --- */
394
395   MP_COPY(x);
396   if (d) MP_DROP(d);
397   MP_DEST(x, MP_LEN(x), x->f);
398
399   /* --- Stage one: trim excess words from the most significant end --- */
400
401 #ifdef DEBUG
402   _r = MP_NEW;
403   mp_div(0, &_r, x, r->p);
404   MP_PRINTX("x", x);
405   _rr = 0;
406 #endif
407
408   il = r->iv + r->in;
409   if (MP_LEN(x) >= r->lim) {
410     v = x->v + r->lim;
411     vl = x->vl;
412     while (vl-- > v) {
413       while (*vl) {
414         z = *vl;
415         *vl = 0;
416         run(r->iv, il, vl, z);
417 #ifdef DEBUG
418         MP_PRINTX("x", x);
419         mp_div(0, &_rr, x, r->p);
420         assert(MP_EQ(_r, _rr));
421 #endif
422       }
423     }
424
425     /* --- Stage two: trim excess bits from the most significant word --- */
426
427     if (r->s) {
428       while (*vl >> r->s) {
429         z = *vl >> r->s;
430         *vl &= ((1 << r->s) - 1);
431         run(r->iv + r->in, il + r->in, vl, z);
432 #ifdef DEBUG
433         MP_PRINTX("x", x);
434         mp_div(0, &_rr, x, r->p);
435         assert(MP_EQ(_r, _rr));
436 #endif
437       }
438     }
439   }
440
441   /* --- Stage three: conditional subtraction --- */
442
443   MP_SHRINK(x);
444   if (MP_CMP(x, >=, r->p))
445     x = mp_sub(x, x, r->p);
446
447   /* --- Done --- */
448
449 #ifdef DEBUG
450   assert(MP_EQ(_r, x));
451   mp_drop(_r);
452   mp_drop(_rr);
453 #endif
454   return (x);
455 }
456
457 /* --- @mpreduce_exp@ --- *
458  *
459  * Arguments:   @mpreduce *mr@ = pointer to reduction context
460  *              @mp *d@ = fake destination
461  *              @mp *a@ = base
462  *              @mp *e@ = exponent
463  *
464  * Returns:     Result, %$a^e \bmod m$%.
465  */
466
467 mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
468 {
469   mp *x = MP_ONE;
470   mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
471
472   MP_SHRINK(e);
473   MP_COPY(a);
474   if (MP_ZEROP(e))
475     ;
476   else {
477     if (MP_NEGP(e))
478       a = mp_modinv(a, a, mr->p);
479     if (MP_LEN(e) < EXP_THRESH)
480       EXP_SIMPLE(x, a, e);
481     else
482       EXP_WINDOW(x, a, e);
483   }
484   mp_drop(a);
485   mp_drop(d);
486   mp_drop(spare);
487   return (x);
488 }
489
490 /*----- Test rig ----------------------------------------------------------*/
491
492
493 #ifdef TEST_RIG
494
495 #define MP(x) mp_readstring(MP_NEW, #x, 0, 0)
496
497 static int vreduce(dstr *v)
498 {
499   mp *d = *(mp **)v[0].buf;
500   mp *n = *(mp **)v[1].buf;
501   mp *r = *(mp **)v[2].buf;
502   mp *c;
503   int ok = 1;
504   mpreduce rr;
505
506   mpreduce_create(&rr, d);
507   c = mpreduce_do(&rr, MP_NEW, n);
508   if (!MP_EQ(c, r)) {
509     fprintf(stderr, "\n*** reduction failed\n*** ");
510     mpreduce_dump(&rr, stderr);
511     fprintf(stderr, "\n*** n = "); mp_writefile(n, stderr, 10);
512     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
513     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
514     fprintf(stderr, "\n");
515     ok = 0;
516   }
517   mpreduce_destroy(&rr);
518   mp_drop(n); mp_drop(d); mp_drop(r); mp_drop(c);
519   assert(mparena_count(MPARENA_GLOBAL) == 0);
520   return (ok);
521 }
522
523 static int vmodexp(dstr *v)
524 {
525   mp *p = *(mp **)v[0].buf;
526   mp *g = *(mp **)v[1].buf;
527   mp *x = *(mp **)v[2].buf;
528   mp *r = *(mp **)v[3].buf;
529   mp *c;
530   int ok = 1;
531   mpreduce rr;
532
533   mpreduce_create(&rr, p);
534   c = mpreduce_exp(&rr, MP_NEW, g, x);
535   if (!MP_EQ(c, r)) {
536     fprintf(stderr, "\n*** modexp failed\n*** ");
537     fprintf(stderr, "\n*** p = "); mp_writefile(p, stderr, 10);
538     fprintf(stderr, "\n*** g = "); mp_writefile(g, stderr, 10);
539     fprintf(stderr, "\n*** x = "); mp_writefile(x, stderr, 10);
540     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
541     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
542     fprintf(stderr, "\n");
543     ok = 0;
544   }
545   mpreduce_destroy(&rr);
546   mp_drop(p); mp_drop(g); mp_drop(r); mp_drop(x); mp_drop(c);
547   assert(mparena_count(MPARENA_GLOBAL) == 0);
548   return (ok);
549 }
550
551 static test_chunk defs[] = {
552   { "reduce", vreduce, { &type_mp, &type_mp, &type_mp, 0 } },
553   { "modexp", vmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
554   { 0, 0, { 0 } }
555 };
556
557 int main(int argc, char *argv[])
558 {
559   test_run(argc, argv, defs, SRCDIR"/t/mpreduce");
560   return (0);
561 }
562
563 #endif
564
565 /*----- That's all, folks -------------------------------------------------*/