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