Bugfix: Added special case for x mod 1.
[libfirm] / ir / ir / irarch.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Machine dependent Firm optimizations.
23  * @date    28.9.2004
24  * @author  Sebastian Hack, Michael Beck
25  * @version $Id$
26  *
27  * Implements "Strength Reduction of Multiplications by Integer Constants"
28  * by Youfeng Wu.
29  * Implements Division and Modulo by Consts from "Hackers Delight",
30  */
31 #include "config.h"
32
33 #include <stdlib.h>
34 #include <assert.h>
35
36 #include "irnode_t.h"
37 #include "irgraph_t.h"
38 #include "irmode_t.h"
39 #include "iropt_t.h"
40 #include "ircons_t.h"
41 #include "irgmod.h"
42 #include "irverify.h"
43 #include "tv_t.h"
44 #include "dbginfo_t.h"
45 #include "iropt_dbg.h"
46 #include "irflag_t.h"
47 #include "irhooks.h"
48 #include "ircons.h"
49 #include "irarch.h"
50 #include "irflag.h"
51 #include "be.h"
52 #include "error.h"
53
54 /** The bit mask, which optimizations to apply. */
55 static arch_dep_opts_t opts;
56
57 void arch_dep_set_opts(arch_dep_opts_t the_opts)
58 {
59         opts = the_opts;
60 }
61
62 /** check, whether a mode allows a Mulh instruction. */
63 static int allow_Mulh(const ir_settings_arch_dep_t *params, ir_mode *mode)
64 {
65         if (get_mode_size_bits(mode) > params->max_bits_for_mulh)
66                 return 0;
67         return (mode_is_signed(mode) && params->allow_mulhs) || (!mode_is_signed(mode) && params->allow_mulhu);
68 }
69
70 /**
71  * An instruction,
72  */
73 typedef struct instruction instruction;
74 struct instruction {
75         insn_kind   kind;        /**< the instruction kind */
76         instruction *in[2];      /**< the ins */
77         unsigned    shift_count; /**< shift count for LEA and SHIFT */
78         ir_node     *irn;        /**< the generated node for this instruction if any. */
79         int         costs;       /**< the costs for this instruction */
80 };
81
82 /**
83  * The environment for the strength reduction of multiplications.
84  */
85 typedef struct mul_env {
86         struct obstack obst;       /**< an obstack for local space. */
87         const ir_settings_arch_dep_t *params;
88         ir_mode        *mode;      /**< the mode of the multiplication constant */
89         unsigned       bits;       /**< number of bits in the mode */
90         unsigned       max_S;      /**< the maximum LEA shift value. */
91         instruction    *root;      /**< the root of the instruction tree */
92         ir_node        *op;        /**< the operand that is multiplied */
93         ir_node        *blk;       /**< the block where the new graph is built */
94         ir_graph       *irg;
95         dbg_info       *dbg;       /**< the debug info for the new graph. */
96         ir_mode        *shf_mode;  /**< the (unsigned) mode for the shift constants */
97         int            fail;       /**< set to 1 if the instruction sequence fails the constraints */
98         int            n_shift;    /**< maximum number of allowed shift instructions */
99
100         evaluate_costs_func evaluate;  /**< the evaluate callback */
101 } mul_env;
102
103 /**
104  * Some kind of default evaluator. Return the cost of
105  * instructions.
106  */
107 static int default_evaluate(insn_kind kind, const ir_mode *mode, ir_tarval *tv)
108 {
109         (void) mode;
110         (void) tv;
111
112         if (kind == MUL)
113                 return 13;
114         return 1;
115 }
116
117 /**
118  * emit a LEA (or an Add) instruction
119  */
120 static instruction *emit_LEA(mul_env *env, instruction *a, instruction *b, unsigned shift)
121 {
122         instruction *res = OALLOC(&env->obst, instruction);
123         res->kind = shift > 0 ? LEA : ADD;
124         res->in[0] = a;
125         res->in[1] = b;
126         res->shift_count = shift;
127         res->irn = NULL;
128         res->costs = -1;
129         return res;
130 }
131
132 /**
133  * emit a SHIFT (or an Add or a Zero) instruction
134  */
135 static instruction *emit_SHIFT(mul_env *env, instruction *a, unsigned shift)
136 {
137         instruction *res = OALLOC(&env->obst, instruction);
138         if (shift == env->bits) {
139                 /* a 2^bits with bits resolution is a zero */
140                 res->kind = ZERO;
141                 res->in[0] = NULL;
142                 res->in[1] = NULL;
143                 res->shift_count = 0;
144         } else if (shift != 1) {
145                 res->kind = SHIFT;
146                 res->in[0] = a;
147                 res->in[1] = NULL;
148                 res->shift_count = shift;
149         } else {
150                 res->kind = ADD;
151                 res->in[0] = a;
152                 res->in[1] = a;
153                 res->shift_count = 0;
154         }
155         res->irn = NULL;
156         res->costs = -1;
157         return res;
158 }
159
160 /**
161  * emit a SUB instruction
162  */
163 static instruction *emit_SUB(mul_env *env, instruction *a, instruction *b)
164 {
165         instruction *res = OALLOC(&env->obst, instruction);
166         res->kind = SUB;
167         res->in[0] = a;
168         res->in[1] = b;
169         res->shift_count = 0;
170         res->irn = NULL;
171         res->costs = -1;
172         return res;
173 }
174
175 /**
176  * emit the ROOT instruction
177  */
178 static instruction *emit_ROOT(mul_env *env, ir_node *root_op)
179 {
180         instruction *res = OALLOC(&env->obst, instruction);
181         res->kind = ROOT;
182         res->in[0] = NULL;
183         res->in[1] = NULL;
184         res->shift_count = 0;
185         res->irn = root_op;
186         res->costs = 0;
187         return res;
188 }
189
190
191 /**
192  * Returns the condensed representation of the tarval tv
193  */
194 static unsigned char *value_to_condensed(mul_env *env, ir_tarval *tv, int *pr)
195 {
196         ir_mode *mode = get_tarval_mode(tv);
197         int     bits = get_mode_size_bits(mode);
198         char    *bitstr = get_tarval_bitpattern(tv);
199         int     i, l, r;
200         unsigned char *R = (unsigned char*)obstack_alloc(&env->obst, bits);
201
202         l = r = 0;
203         for (i = 0; bitstr[i] != '\0'; ++i) {
204                 if (bitstr[i] == '1') {
205                         R[r] = i - l;
206                         l = i;
207                         ++r;
208                 }
209         }
210         free(bitstr);
211
212         *pr = r;
213         return R;
214 }
215
216 /**
217  * Calculate the gain when using the generalized complementary technique
218  */
219 static int calculate_gain(unsigned char *R, int r)
220 {
221         int max_gain = 0;
222         int idx = -1, i;
223         int gain;
224
225         /* the gain for r == 1 */
226         gain = 2 - 3 - R[0];
227         for (i = 2; i < r; ++i) {
228                 /* calculate the gain for r from the gain for r-1 */
229                 gain += 2 - R[i - 1];
230
231                 if (gain > max_gain) {
232                         max_gain = gain;
233                         idx = i;
234                 }
235         }
236         return idx;
237 }
238
239 /**
240  * Calculates the condensed complement of a given (R,r) tuple
241  */
242 static unsigned char *complement_condensed(mul_env *env, unsigned char *R, int r, int gain, int *prs)
243 {
244         unsigned char *value = (unsigned char*)obstack_alloc(&env->obst, env->bits);
245         int i, l, j;
246         unsigned char c;
247
248         memset(value, 0, env->bits);
249
250         j = 0;
251         for (i = 0; i < gain; ++i) {
252                 j += R[i];
253                 value[j] = 1;
254         }
255
256         /* negate and propagate 1 */
257         c = 1;
258         for (i = 0; i <= j; ++i) {
259                 unsigned char v = !value[i];
260
261                 value[i] = v ^ c;
262                 c = v & c;
263         }
264
265         /* condense it again */
266         l = r = 0;
267         R = value;
268         for (i = 0; i <= j; ++i) {
269                 if (value[i] == 1) {
270                         R[r] = i - l;
271                         l = i;
272                         ++r;
273                 }
274         }
275
276         *prs = r;
277         return R;
278 }
279
280 /**
281  * creates a tarval from a condensed representation.
282  */
283 static ir_tarval *condensed_to_value(mul_env *env, unsigned char *R, int r)
284 {
285         ir_tarval *res, *tv;
286         int i, j;
287
288         j = 0;
289         tv = get_mode_one(env->mode);
290         res = NULL;
291         for (i = 0; i < r; ++i) {
292                 j = R[i];
293                 if (j) {
294                         ir_tarval *t = new_tarval_from_long(j, mode_Iu);
295                         tv = tarval_shl(tv, t);
296                 }
297                 res = res ? tarval_add(res, tv) : tv;
298         }
299         return res;
300 }
301
302 /* forward */
303 static instruction *basic_decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N);
304
305 /*
306  * handle simple cases with up-to 2 bits set
307  */
308 static instruction *decompose_simple_cases(mul_env *env, unsigned char *R, int r, ir_tarval *N)
309 {
310         instruction *ins, *ins2;
311
312         (void) N;
313         if (r == 1) {
314                 return emit_SHIFT(env, env->root, R[0]);
315         } else {
316                 assert(r == 2);
317
318                 ins = env->root;
319                 if (R[1] <= env->max_S) {
320                         ins = emit_LEA(env, ins, ins, R[1]);
321                         if (R[0] != 0) {
322                                 ins = emit_SHIFT(env, ins, R[0]);
323                         }
324                         return ins;
325                 }
326                 if (R[0] != 0) {
327                         ins = emit_SHIFT(env, ins, R[0]);
328                 }
329
330                 ins2 = emit_SHIFT(env, env->root, R[0] + R[1]);
331                 return emit_LEA(env, ins, ins2, 0);
332         }
333 }
334
335 /**
336  * Main decompose driver.
337  */
338 static instruction *decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N)
339 {
340         unsigned i;
341         int gain;
342
343         if (r <= 2)
344                 return decompose_simple_cases(env, R, r, N);
345
346         if (env->params->also_use_subs) {
347                 gain = calculate_gain(R, r);
348                 if (gain > 0) {
349                         instruction *instr1, *instr2;
350                         unsigned char *R1, *R2;
351                         int r1, r2, i, k, j;
352
353                         R1 = complement_condensed(env, R, r, gain, &r1);
354                         r2 = r - gain + 1;
355                         R2 = (unsigned char*)obstack_alloc(&env->obst, r2);
356
357                         k = 1;
358                         for (i = 0; i < gain; ++i) {
359                                 k += R[i];
360                         }
361                         R2[0] = k;
362                         R2[1] = R[gain] - 1;
363                         j = 2;
364                         if (R2[1] == 0) {
365                                 /* Two identical bits: normalize */
366                                 ++R2[0];
367                                 --j;
368                                 --r2;
369                         }
370                         for (i = gain + 1; i < r; ++i) {
371                                 R2[j++] = R[i];
372                         }
373
374                         instr1 = decompose_mul(env, R1, r1, NULL);
375                         instr2 = decompose_mul(env, R2, r2, NULL);
376                         return emit_SUB(env, instr2, instr1);
377                 }
378         }
379
380         if (N == NULL)
381                 N = condensed_to_value(env, R, r);
382
383         for (i = env->max_S; i > 0; --i) {
384                 ir_tarval *div_res, *mod_res;
385                 ir_tarval *tv = new_tarval_from_long((1 << i) + 1, env->mode);
386
387                 div_res = tarval_divmod(N, tv, &mod_res);
388                 if (mod_res == get_mode_null(env->mode)) {
389                         unsigned char *Rs;
390                         int rs;
391
392                         Rs = value_to_condensed(env, div_res, &rs);
393                         if (rs < r) {
394                                 instruction *N1 = decompose_mul(env, Rs, rs, div_res);
395                                 return emit_LEA(env, N1, N1, i);
396                         }
397                 }
398         }
399         return basic_decompose_mul(env, R, r, N);
400 }
401
402 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
403
404 /**
405  * basic decomposition routine
406  */
407 static instruction *basic_decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N)
408 {
409         instruction *Ns;
410         unsigned t;
411
412         if (R[0] == 0) {                    /* Case 1 */
413                 t = R[1] > IMAX(env->max_S, R[1]);
414                 R[1] -= t;
415                 Ns = decompose_mul(env, &R[1], r - 1, N);
416                 return emit_LEA(env, env->root, Ns, t);
417         } else if (R[0] <= env->max_S) {    /* Case 2 */
418                 t = R[0];
419                 R[1] += t;
420                 Ns = decompose_mul(env, &R[1], r - 1, N);
421                 return emit_LEA(env, Ns, env->root, t);
422         } else {
423                 t = R[0];
424                 R[0] = 0;
425                 Ns = decompose_mul(env, R, r, N);
426                 return emit_SHIFT(env, Ns, t);
427         }
428 }
429
430 /**
431  * recursive build the graph form the instructions.
432  *
433  * @param env   the environment
434  * @param inst  the instruction
435  */
436 static ir_node *build_graph(mul_env *env, instruction *inst)
437 {
438         ir_node *l, *r, *c;
439         ir_graph *irg = env->irg;
440
441         if (inst->irn)
442                 return inst->irn;
443
444         switch (inst->kind) {
445         case LEA:
446                 l = build_graph(env, inst->in[0]);
447                 r = build_graph(env, inst->in[1]);
448                 c = new_r_Const_long(irg, env->shf_mode, inst->shift_count);
449                 r = new_rd_Shl(env->dbg, env->blk, r, c, env->mode);
450                 return inst->irn = new_rd_Add(env->dbg, env->blk, l, r, env->mode);
451         case SHIFT:
452                 l = build_graph(env, inst->in[0]);
453                 c = new_r_Const_long(irg, env->shf_mode, inst->shift_count);
454                 return inst->irn = new_rd_Shl(env->dbg, env->blk, l, c, env->mode);
455         case SUB:
456                 l = build_graph(env, inst->in[0]);
457                 r = build_graph(env, inst->in[1]);
458                 return inst->irn = new_rd_Sub(env->dbg, env->blk, l, r, env->mode);
459         case ADD:
460                 l = build_graph(env, inst->in[0]);
461                 r = build_graph(env, inst->in[1]);
462                 return inst->irn = new_rd_Add(env->dbg, env->blk, l, r, env->mode);
463         case ZERO:
464                 return inst->irn = new_r_Const(irg, get_mode_null(env->mode));
465         default:
466                 panic("Unsupported instruction kind");
467         }
468 }
469
470 /**
471  * Calculate the costs for the given instruction sequence.
472  * Note that additional costs due to higher register pressure are NOT evaluated yet
473  */
474 static int evaluate_insn(mul_env *env, instruction *inst)
475 {
476         int costs;
477
478         if (inst->costs >= 0) {
479                 /* was already evaluated */
480                 return 0;
481         }
482
483         switch (inst->kind) {
484         case LEA:
485         case SUB:
486         case ADD:
487                 costs  = evaluate_insn(env, inst->in[0]);
488                 costs += evaluate_insn(env, inst->in[1]);
489                 costs += env->evaluate(inst->kind, env->mode, NULL);
490                 inst->costs = costs;
491                 return costs;
492         case SHIFT:
493                 if (inst->shift_count > env->params->highest_shift_amount)
494                         env->fail = 1;
495                 if (env->n_shift <= 0)
496                         env->fail = 1;
497                 else
498                         --env->n_shift;
499                 costs  = evaluate_insn(env, inst->in[0]);
500                 costs += env->evaluate(inst->kind, env->mode, NULL);
501                 inst->costs = costs;
502                 return costs;
503         case ZERO:
504                 inst->costs = costs = env->evaluate(inst->kind, env->mode, NULL);
505                 return costs;
506         case MUL:
507         case ROOT:
508                 break;
509         }
510         panic("Unsupported instruction kind");
511 }
512
513 /**
514  * Evaluate the replacement instructions and build a new graph
515  * if faster than the Mul.
516  * Returns the root of the new graph then or irn otherwise.
517  *
518  * @param irn      the Mul operation
519  * @param operand  the multiplication operand
520  * @param tv       the multiplication constant
521  *
522  * @return the new graph
523  */
524 static ir_node *do_decomposition(ir_node *irn, ir_node *operand, ir_tarval *tv)
525 {
526         mul_env       env;
527         instruction   *inst;
528         unsigned char *R;
529         int           r;
530         ir_node       *res = irn;
531         int           mul_costs;
532
533         obstack_init(&env.obst);
534         env.params   = be_get_backend_param()->dep_param;
535         env.mode     = get_tarval_mode(tv);
536         env.bits     = (unsigned)get_mode_size_bits(env.mode);
537         env.max_S    = 3;
538         env.root     = emit_ROOT(&env, operand);
539         env.fail     = 0;
540         env.n_shift  = env.params->maximum_shifts;
541         env.evaluate = env.params->evaluate != NULL ? env.params->evaluate : default_evaluate;
542         env.irg      = get_irn_irg(irn);
543
544         R = value_to_condensed(&env, tv, &r);
545         inst = decompose_mul(&env, R, r, tv);
546
547         /* the paper suggests 70% here */
548         mul_costs = (env.evaluate(MUL, env.mode, tv) * 7 + 5) / 10;
549         if (evaluate_insn(&env, inst) <= mul_costs && !env.fail) {
550                 env.op       = operand;
551                 env.blk      = get_nodes_block(irn);
552                 env.dbg      = get_irn_dbg_info(irn);
553                 env.shf_mode = find_unsigned_mode(env.mode);
554                 if (env.shf_mode == NULL)
555                         env.shf_mode = mode_Iu;
556
557                 res = build_graph(&env, inst);
558         }
559         obstack_free(&env.obst, NULL);
560         return res;
561 }
562
563 /* Replace Muls with Shifts and Add/Subs. */
564 ir_node *arch_dep_replace_mul_with_shifts(ir_node *irn)
565 {
566         ir_node   *res  = irn;
567         ir_mode   *mode = get_irn_mode(irn);
568         ir_graph  *irg;
569         ir_node   *left;
570         ir_node   *right;
571         ir_node   *operand;
572         ir_tarval *tv;
573         const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
574
575
576         /* If the architecture dependent optimizations were not initialized
577            or this optimization was not enabled. */
578         if (params == NULL || (opts & arch_dep_mul_to_shift) == 0)
579                 return irn;
580
581         if (!is_Mul(irn) || !mode_is_int(mode))
582                 return res;
583
584         /* we should never do the reverse transformations again
585            (like x+x -> 2*x) */
586         irg = get_irn_irg(irn);
587         set_irg_state(irg, IR_GRAPH_STATE_ARCH_DEP);
588
589         left    = get_binop_left(irn);
590         right   = get_binop_right(irn);
591         tv      = NULL;
592         operand = NULL;
593
594         /* Look, if one operand is a constant. */
595         if (is_Const(left)) {
596                 tv = get_Const_tarval(left);
597                 operand = right;
598         } else if (is_Const(right)) {
599                 tv = get_Const_tarval(right);
600                 operand = left;
601         }
602
603         if (tv != NULL) {
604                 res = do_decomposition(irn, operand, tv);
605
606                 if (res != irn) {
607                         hook_arch_dep_replace_mul_with_shifts(irn);
608                         exchange(irn, res);
609                 }
610         }
611
612         return res;
613 }
614
615 /**
616  * calculated the ld2 of a tarval if tarval is 2^n, else returns -1.
617  */
618 static int tv_ld2(ir_tarval *tv, int bits)
619 {
620         int i, k = 0, num;
621
622         for (num = i = 0; i < bits; ++i) {
623                 unsigned char v = get_tarval_sub_bits(tv, i);
624
625                 if (v) {
626                         int j;
627
628                         for (j = 0; j < 8; ++j)
629                                 if ((1 << j) & v) {
630                                         ++num;
631                                         k = 8 * i + j;
632                                 }
633                 }
634         }
635         if (num == 1)
636                 return k;
637         return -1;
638 }
639
640
641 /* for shorter lines */
642 #define ABS(a)    tarval_abs(a)
643 #define NEG(a)    tarval_neg(a)
644 #define NOT(a)    tarval_not(a)
645 #define SHL(a, b) tarval_shl(a, b)
646 #define SHR(a, b) tarval_shr(a, b)
647 #define ADD(a, b) tarval_add(a, b)
648 #define SUB(a, b) tarval_sub(a, b, NULL)
649 #define MUL(a, b) tarval_mul(a, b)
650 #define DIV(a, b) tarval_div(a, b)
651 #define MOD(a, b) tarval_mod(a, b)
652 #define CMP(a, b) tarval_cmp(a, b)
653 #define CNV(a, m) tarval_convert_to(a, m)
654 #define ONE(m)    get_mode_one(m)
655 #define ZERO(m)   get_mode_null(m)
656
657 /** The result of a the magic() function. */
658 struct ms {
659         ir_tarval *M;     /**< magic number */
660         int s;            /**< shift amount */
661         int need_add;     /**< an additional add is needed */
662         int need_sub;     /**< an additional sub is needed */
663 };
664
665 /**
666  * Signed division by constant d: calculate the Magic multiplier M and the shift amount s
667  *
668  * see Hacker's Delight: 10-6 Integer Division by Constants: Incorporation into a Compiler
669  */
670 static struct ms magic(ir_tarval *d)
671 {
672         ir_mode *mode   = get_tarval_mode(d);
673         ir_mode *u_mode = find_unsigned_mode(mode);
674         int bits        = get_mode_size_bits(u_mode);
675         int p;
676         ir_tarval *ad, *anc, *delta, *q1, *r1, *q2, *r2, *t;     /* unsigned */
677         ir_relation d_cmp, M_cmp;
678
679         ir_tarval *bits_minus_1, *two_bits_1;
680
681         struct ms mag;
682
683         tarval_int_overflow_mode_t rem = tarval_get_integer_overflow_mode();
684
685         /* we need overflow mode to work correctly */
686         tarval_set_integer_overflow_mode(TV_OVERFLOW_WRAP);
687
688         /* 2^(bits-1) */
689         bits_minus_1 = new_tarval_from_long(bits - 1, u_mode);
690         two_bits_1   = SHL(get_mode_one(u_mode), bits_minus_1);
691
692         ad  = CNV(ABS(d), u_mode);
693         t   = ADD(two_bits_1, SHR(CNV(d, u_mode), bits_minus_1));
694         anc = SUB(SUB(t, ONE(u_mode)), MOD(t, ad));   /* Absolute value of nc */
695         p   = bits - 1;                               /* Init: p */
696         q1  = DIV(two_bits_1, anc);                   /* Init: q1 = 2^p/|nc| */
697         r1  = SUB(two_bits_1, MUL(q1, anc));          /* Init: r1 = rem(2^p, |nc|) */
698         q2  = DIV(two_bits_1, ad);                    /* Init: q2 = 2^p/|d| */
699         r2  = SUB(two_bits_1, MUL(q2, ad));           /* Init: r2 = rem(2^p, |d|) */
700
701         do {
702                 ++p;
703                 q1 = ADD(q1, q1);                           /* Update q1 = 2^p/|nc| */
704                 r1 = ADD(r1, r1);                           /* Update r1 = rem(2^p, |nc|) */
705
706                 if (CMP(r1, anc) & ir_relation_greater_equal) {
707                         q1 = ADD(q1, ONE(u_mode));
708                         r1 = SUB(r1, anc);
709                 }
710
711                 q2 = ADD(q2, q2);                           /* Update q2 = 2^p/|d| */
712                 r2 = ADD(r2, r2);                           /* Update r2 = rem(2^p, |d|) */
713
714                 if (CMP(r2, ad) & ir_relation_greater_equal) {
715                         q2 = ADD(q2, ONE(u_mode));
716                         r2 = SUB(r2, ad);
717                 }
718
719                 delta = SUB(ad, r2);
720         } while (CMP(q1, delta) & ir_relation_less || (CMP(q1, delta) & ir_relation_equal && CMP(r1, ZERO(u_mode)) & ir_relation_equal));
721
722         d_cmp = CMP(d, ZERO(mode));
723
724         if (d_cmp & ir_relation_greater_equal)
725                 mag.M = ADD(CNV(q2, mode), ONE(mode));
726         else
727                 mag.M = SUB(ZERO(mode), ADD(CNV(q2, mode), ONE(mode)));
728
729         M_cmp = CMP(mag.M, ZERO(mode));
730
731         mag.s = p - bits;
732
733         /* need an add if d > 0 && M < 0 */
734         mag.need_add = d_cmp & ir_relation_greater && M_cmp & ir_relation_less;
735
736         /* need a sub if d < 0 && M > 0 */
737         mag.need_sub = d_cmp & ir_relation_less && M_cmp & ir_relation_greater;
738
739         tarval_set_integer_overflow_mode(rem);
740
741         return mag;
742 }
743
744 /** The result of the magicu() function. */
745 struct mu {
746         ir_tarval *M;     /**< magic add constant */
747         int s;            /**< shift amount */
748         int need_add;     /**< add indicator */
749 };
750
751 /**
752  * Unsigned division by constant d: calculate the Magic multiplier M and the shift amount s
753  *
754  * see Hacker's Delight: 10-10 Integer Division by Constants: Incorporation into a Compiler (Unsigned)
755  */
756 static struct mu magicu(ir_tarval *d)
757 {
758         ir_mode *mode   = get_tarval_mode(d);
759         int bits        = get_mode_size_bits(mode);
760         int p;
761         ir_tarval *nc, *delta, *q1, *r1, *q2, *r2;
762         ir_tarval *bits_minus_1, *two_bits_1, *seven_ff;
763
764         struct mu magu;
765
766         tarval_int_overflow_mode_t rem = tarval_get_integer_overflow_mode();
767
768         /* we need overflow mode to work correctly */
769         tarval_set_integer_overflow_mode(TV_OVERFLOW_WRAP);
770
771         bits_minus_1 = new_tarval_from_long(bits - 1, mode);
772         two_bits_1   = SHL(get_mode_one(mode), bits_minus_1);
773         seven_ff     = SUB(two_bits_1, ONE(mode));
774
775         magu.need_add = 0;                            /* initialize the add indicator */
776         nc = SUB(NEG(ONE(mode)), MOD(NEG(d), d));
777         p  = bits - 1;                                /* Init: p */
778         q1 = DIV(two_bits_1, nc);                     /* Init: q1 = 2^p/nc */
779         r1 = SUB(two_bits_1, MUL(q1, nc));            /* Init: r1 = rem(2^p, nc) */
780         q2 = DIV(seven_ff, d);                        /* Init: q2 = (2^p - 1)/d */
781         r2 = SUB(seven_ff, MUL(q2, d));               /* Init: r2 = rem(2^p - 1, d) */
782
783         do {
784                 ++p;
785                 if (CMP(r1, SUB(nc, r1)) & ir_relation_greater_equal) {
786                         q1 = ADD(ADD(q1, q1), ONE(mode));
787                         r1 = SUB(ADD(r1, r1), nc);
788                 }
789                 else {
790                         q1 = ADD(q1, q1);
791                         r1 = ADD(r1, r1);
792                 }
793
794                 if (CMP(ADD(r2, ONE(mode)), SUB(d, r2)) & ir_relation_greater_equal) {
795                         if (CMP(q2, seven_ff) & ir_relation_greater_equal)
796                                 magu.need_add = 1;
797
798                         q2 = ADD(ADD(q2, q2), ONE(mode));
799                         r2 = SUB(ADD(ADD(r2, r2), ONE(mode)), d);
800                 }
801                 else {
802                         if (CMP(q2, two_bits_1) & ir_relation_greater_equal)
803                                 magu.need_add = 1;
804
805                         q2 = ADD(q2, q2);
806                         r2 = ADD(ADD(r2, r2), ONE(mode));
807                 }
808                 delta = SUB(SUB(d, ONE(mode)), r2);
809         } while (p < 2*bits &&
810                 (CMP(q1, delta) & ir_relation_less || (CMP(q1, delta) & ir_relation_equal && CMP(r1, ZERO(mode)) & ir_relation_equal)));
811
812         magu.M = ADD(q2, ONE(mode));                       /* Magic number */
813         magu.s = p - bits;                                 /* and shift amount */
814
815         tarval_set_integer_overflow_mode(rem);
816
817         return magu;
818 }
819
820 /**
821  * Build the Mulh replacement code for n / tv.
822  *
823  * Note that 'div' might be a Mod operation as well
824  */
825 static ir_node *replace_div_by_mulh(ir_node *div, ir_tarval *tv)
826 {
827         dbg_info *dbg  = get_irn_dbg_info(div);
828         ir_node *n     = get_binop_left(div);
829         ir_node *block = get_irn_n(div, -1);
830         ir_mode *mode  = get_irn_mode(n);
831         int bits       = get_mode_size_bits(mode);
832         ir_node *q;
833
834         /* Beware: do not transform bad code */
835         if (is_Bad(n) || is_Bad(block))
836                 return div;
837
838         if (mode_is_signed(mode)) {
839                 ir_graph *irg = get_irn_irg(div);
840                 struct ms mag = magic(tv);
841
842                 /* generate the Mulh instruction */
843                 ir_node *c = new_r_Const(irg, mag.M);
844                 ir_node *t;
845                 q = new_rd_Mulh(dbg, block, n, c, mode);
846
847                 /* do we need an Add or Sub */
848                 if (mag.need_add)
849                         q = new_rd_Add(dbg, block, q, n, mode);
850                 else if (mag.need_sub)
851                         q = new_rd_Sub(dbg, block, q, n, mode);
852
853                 /* Do we need the shift */
854                 if (mag.s > 0) {
855                         c = new_r_Const_long(irg, mode_Iu, mag.s);
856                         q = new_rd_Shrs(dbg, block, q, c, mode);
857                 }
858
859                 /* final */
860                 c = new_r_Const_long(irg, mode_Iu, bits - 1);
861                 t = new_rd_Shr(dbg, block, q, c, mode);
862
863                 q = new_rd_Add(dbg, block, q, t, mode);
864         } else {
865                 struct mu mag = magicu(tv);
866                 ir_graph *irg = get_irn_irg(div);
867
868                 /* generate the Mulh instruction */
869                 ir_node *c = new_r_Const(irg, mag.M);
870                 q = new_rd_Mulh(dbg, block, n, c, mode);
871
872                 if (mag.need_add) {
873                         if (mag.s > 0) {
874                                 /* use the GM scheme */
875                                 ir_node *t = new_rd_Sub(dbg, block, n, q, mode);
876
877                                 c = new_r_Const(irg, get_mode_one(mode_Iu));
878                                 t = new_rd_Shr(dbg, block, t, c, mode);
879
880                                 t = new_rd_Add(dbg, block, t, q, mode);
881
882                                 c = new_r_Const_long(irg, mode_Iu, mag.s - 1);
883                                 q = new_rd_Shr(dbg, block, t, c, mode);
884                         } else {
885                                 /* use the default scheme */
886                                 q = new_rd_Add(dbg, block, q, n, mode);
887                         }
888                 } else if (mag.s > 0) { /* default scheme, shift needed */
889                         c = new_r_Const_long(irg, mode_Iu, mag.s);
890                         q = new_rd_Shr(dbg, block, q, c, mode);
891                 }
892         }
893         return q;
894 }
895
896 /* Replace Divs with Shifts and Add/Subs and Mulh. */
897 ir_node *arch_dep_replace_div_by_const(ir_node *irn)
898 {
899         const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
900         ir_node *res  = irn;
901
902         /* If the architecture dependent optimizations were not initialized
903                 or this optimization was not enabled. */
904         if (params == NULL || (opts & arch_dep_div_by_const) == 0)
905                 return irn;
906
907         if (!is_Div(irn))
908                 return irn;
909
910         ir_node *c = get_Div_right(irn);
911         ir_node *block, *left;
912         ir_mode *mode;
913         ir_tarval *tv, *ntv;
914         dbg_info *dbg;
915         int n, bits;
916         int k;
917         int n_flag = 0;
918
919         if (! is_Const(c))
920                 return irn;
921
922         tv = get_Const_tarval(c);
923
924         /* check for division by zero */
925         if (tarval_is_null(tv))
926                 return irn;
927
928         left  = get_Div_left(irn);
929         mode  = get_irn_mode(left);
930
931         /* can only handle integer Div's */
932         if (!mode_is_int(mode))
933                 return irn;
934
935         block = get_irn_n(irn, -1);
936         dbg   = get_irn_dbg_info(irn);
937
938         bits = get_mode_size_bits(mode);
939         n    = (bits + 7) / 8;
940
941         k = -1;
942         if (mode_is_signed(mode)) {
943                 /* for signed divisions, the algorithm works for a / -2^k by negating the result */
944                 ntv = tarval_neg(tv);
945                 n_flag = 1;
946                 k = tv_ld2(ntv, n);
947         }
948
949         if (k < 0) {
950                 n_flag = 0;
951                 k = tv_ld2(tv, n);
952         }
953
954         if (k > 0) { /* division by 2^k or -2^k */
955                 ir_graph *irg = get_irn_irg(irn);
956                 if (mode_is_signed(mode)) {
957                         ir_node *k_node;
958                         ir_node *curr = left;
959
960                         /* create the correction code for signed values only if there might be a remainder */
961                         if (! get_Div_no_remainder(irn)) {
962                                 if (k != 1) {
963                                         k_node = new_r_Const_long(irg, mode_Iu, k - 1);
964                                         curr   = new_rd_Shrs(dbg, block, left, k_node, mode);
965                                 }
966
967                                 k_node = new_r_Const_long(irg, mode_Iu, bits - k);
968                                 curr   = new_rd_Shr(dbg, block, curr, k_node, mode);
969                                 /* curr is now 2^(k-1) in case left <  0
970                                  *          or       0 in case left >= 0
971                                  *
972                                  * For an example, where this fixup is necessary consider -3 / 2,
973                                  * which should compute to -1,
974                                  * but simply shifting right by one computes -2.
975                                  */
976
977                                 curr   = new_rd_Add(dbg, block, left, curr, mode);
978                         }
979
980                         k_node = new_r_Const_long(irg, mode_Iu, k);
981                         res    = new_rd_Shrs(dbg, block, curr, k_node, mode);
982
983                         if (n_flag) { /* negate the result */
984                                 k_node = new_r_Const(irg, get_mode_null(mode));
985                                 res = new_rd_Sub(dbg, block, k_node, res, mode);
986                         }
987                 } else {      /* unsigned case */
988                         ir_node *k_node;
989
990                         k_node = new_r_Const_long(irg, mode_Iu, k);
991                         res    = new_rd_Shr(dbg, block, left, k_node, mode);
992                 }
993         } else if (k != 0) {
994                 /* other constant */
995                 if (allow_Mulh(params, mode))
996                         res = replace_div_by_mulh(irn, tv);
997         } else { /* k == 0  i.e. division by 1 */
998                 res = left;
999         }
1000
1001         if (res != irn)
1002                 hook_arch_dep_replace_division_by_const(irn);
1003
1004         return res;
1005 }
1006
1007 /* Replace Mods with Shifts and Add/Subs and Mulh. */
1008 ir_node *arch_dep_replace_mod_by_const(ir_node *irn)
1009 {
1010         const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
1011         ir_node *res  = irn;
1012
1013         /* If the architecture dependent optimizations were not initialized
1014            or this optimization was not enabled. */
1015         if (params == NULL || (opts & arch_dep_mod_by_const) == 0)
1016                 return irn;
1017
1018         if (is_Mod(irn)) {
1019                 ir_node *c = get_Mod_right(irn);
1020                 ir_node *block, *left;
1021                 ir_mode *mode;
1022                 ir_tarval *tv, *ntv;
1023                 dbg_info *dbg;
1024                 int n, bits;
1025                 int k;
1026
1027                 if (! is_Const(c))
1028                         return irn;
1029
1030                 tv = get_Const_tarval(c);
1031
1032                 /* check for division by zero */
1033                 if (tarval_is_null(tv))
1034                         return irn;
1035
1036                 left  = get_Mod_left(irn);
1037                 mode  = get_irn_mode(left);
1038                 block = get_irn_n(irn, -1);
1039                 dbg   = get_irn_dbg_info(irn);
1040                 bits = get_mode_size_bits(mode);
1041                 n    = (bits + 7) / 8;
1042
1043                 k = -1;
1044                 if (mode_is_signed(mode)) {
1045                         /* for signed divisions, the algorithm works for a / -2^k by negating the result */
1046                         ntv = tarval_neg(tv);
1047                         k = tv_ld2(ntv, n);
1048                 }
1049
1050                 if (k < 0) {
1051                         k = tv_ld2(tv, n);
1052                 }
1053
1054                 /* k == 0  i.e. modulo by 1 */
1055                 if (k == 0) {
1056                         ir_graph *irg = get_irn_irg(irn);
1057
1058                         res = new_r_Const(irg, get_mode_null(mode));
1059                 }
1060                 else if (k > 0) {
1061                         ir_graph *irg = get_irn_irg(irn);
1062                         /* division by 2^k or -2^k:
1063                          * we use "modulus" here, so x % y == x % -y that's why is no difference between the case 2^k and -2^k
1064                          */
1065                         if (mode_is_signed(mode)) {
1066                                 ir_node *k_node;
1067                                 ir_node *curr = left;
1068
1069                                 if (k != 1) {
1070                                         k_node = new_r_Const_long(irg, mode_Iu, k - 1);
1071                                         curr   = new_rd_Shrs(dbg, block, left, k_node, mode);
1072                                 }
1073
1074                                 k_node = new_r_Const_long(irg, mode_Iu, bits - k);
1075                                 curr   = new_rd_Shr(dbg, block, curr, k_node, mode);
1076
1077                                 curr   = new_rd_Add(dbg, block, left, curr, mode);
1078
1079                                 k_node = new_r_Const_long(irg, mode, (-1) << k);
1080                                 curr   = new_rd_And(dbg, block, curr, k_node, mode);
1081
1082                                 res    = new_rd_Sub(dbg, block, left, curr, mode);
1083                         } else {      /* unsigned case */
1084                                 ir_node *k_node;
1085
1086                                 k_node = new_r_Const_long(irg, mode, (1 << k) - 1);
1087                                 res    = new_rd_And(dbg, block, left, k_node, mode);
1088                         }
1089                 } else {
1090                         /* other constant */
1091                         if (allow_Mulh(params, mode)) {
1092                                 res = replace_div_by_mulh(irn, tv);
1093
1094                                 res = new_rd_Mul(dbg, block, res, c, mode);
1095
1096                                 /* res = arch_dep_mul_to_shift(res); */
1097
1098                                 res = new_rd_Sub(dbg, block, left, res, mode);
1099                         }
1100                 }
1101         }
1102
1103         if (res != irn)
1104                 hook_arch_dep_replace_division_by_const(irn);
1105
1106         return res;
1107 }