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