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