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