Added option to prevent creation of misaligned loads/stores during CopyB lowering.
[libfirm] / ir / be / ia32 / bearch_ia32.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       This is the main ia32 firm backend driver.
23  * @author      Christian Wuerdig
24  * @version     $Id$
25  */
26 #include "config.h"
27
28 #include "lc_opts.h"
29 #include "lc_opts_enum.h"
30
31 #include <math.h>
32
33 #include "irarch.h"
34 #include "irgwalk.h"
35 #include "irprog.h"
36 #include "irprintf.h"
37 #include "iredges_t.h"
38 #include "ircons.h"
39 #include "irflag.h"
40 #include "irgmod.h"
41 #include "irgopt.h"
42 #include "irbitset.h"
43 #include "irgopt.h"
44 #include "irdump.h"
45 #include "pdeq.h"
46 #include "pset.h"
47 #include "debug.h"
48 #include "error.h"
49 #include "xmalloc.h"
50 #include "irtools.h"
51 #include "iroptimize.h"
52 #include "instrument.h"
53 #include "iropt_t.h"
54 #include "lower_dw.h"
55 #include "lower_calls.h"
56 #include "lower_mode_b.h"
57 #include "lower_softfloat.h"
58
59 #include "../beabi.h"
60 #include "../beirg.h"
61 #include "../benode.h"
62 #include "../belower.h"
63 #include "../besched.h"
64 #include "be.h"
65 #include "../be_t.h"
66 #include "../beirgmod.h"
67 #include "../be_dbgout.h"
68 #include "../beblocksched.h"
69 #include "../bemachine.h"
70 #include "../bespillutil.h"
71 #include "../bespillslots.h"
72 #include "../bemodule.h"
73 #include "../begnuas.h"
74 #include "../bestate.h"
75 #include "../beflags.h"
76 #include "../betranshlp.h"
77 #include "../belistsched.h"
78 #include "../beabihelper.h"
79 #include "../bestack.h"
80
81 #include "bearch_ia32_t.h"
82
83 #include "ia32_new_nodes.h"
84 #include "gen_ia32_regalloc_if.h"
85 #include "gen_ia32_machine.h"
86 #include "ia32_common_transform.h"
87 #include "ia32_transform.h"
88 #include "ia32_emitter.h"
89 #include "ia32_optimize.h"
90 #include "ia32_x87.h"
91 #include "ia32_dbg_stat.h"
92 #include "ia32_finish.h"
93 #include "ia32_fpu.h"
94 #include "ia32_architecture.h"
95
96 #ifdef FIRM_GRGEN_BE
97 #include "ia32_pbqp_transform.h"
98
99 transformer_t be_transformer = TRANSFORMER_DEFAULT;
100 #endif
101
102 ir_mode *ia32_mode_fpcw = NULL;
103
104 /** The current omit-fp state */
105 static ir_type *omit_fp_between_type   = NULL;
106 static ir_type *between_type           = NULL;
107 static ir_entity *old_bp_ent           = NULL;
108 static ir_entity *ret_addr_ent         = NULL;
109 static ir_entity *omit_fp_ret_addr_ent = NULL;
110
111 /**
112  * The environment for the intrinsic mapping.
113  */
114 static ia32_intrinsic_env_t intrinsic_env = {
115         NULL,    /* the isa */
116         NULL,    /* the irg, these entities belong to */
117         NULL,    /* entity for __divdi3 library call */
118         NULL,    /* entity for __moddi3 library call */
119         NULL,    /* entity for __udivdi3 library call */
120         NULL,    /* entity for __umoddi3 library call */
121 };
122
123
124 typedef ir_node *(*create_const_node_func) (dbg_info *dbgi, ir_node *block);
125
126 /**
127  * Used to create per-graph unique pseudo nodes.
128  */
129 static inline ir_node *create_const(ir_graph *irg, ir_node **place,
130                                     create_const_node_func func,
131                                     const arch_register_t* reg)
132 {
133         ir_node *block, *res;
134
135         if (*place != NULL)
136                 return *place;
137
138         block = get_irg_start_block(irg);
139         res = func(NULL, block);
140         arch_set_irn_register(res, reg);
141         *place = res;
142
143         return res;
144 }
145
146 /* Creates the unique per irg GP NoReg node. */
147 ir_node *ia32_new_NoReg_gp(ir_graph *irg)
148 {
149         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
150         return create_const(irg, &irg_data->noreg_gp, new_bd_ia32_NoReg_GP,
151                             &ia32_registers[REG_GP_NOREG]);
152 }
153
154 ir_node *ia32_new_NoReg_vfp(ir_graph *irg)
155 {
156         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
157         return create_const(irg, &irg_data->noreg_vfp, new_bd_ia32_NoReg_VFP,
158                             &ia32_registers[REG_VFP_NOREG]);
159 }
160
161 ir_node *ia32_new_NoReg_xmm(ir_graph *irg)
162 {
163         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
164         return create_const(irg, &irg_data->noreg_xmm, new_bd_ia32_NoReg_XMM,
165                             &ia32_registers[REG_XMM_NOREG]);
166 }
167
168 ir_node *ia32_new_Fpu_truncate(ir_graph *irg)
169 {
170         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
171         return create_const(irg, &irg_data->fpu_trunc_mode, new_bd_ia32_ChangeCW,
172                         &ia32_registers[REG_FPCW]);
173 }
174
175
176 /**
177  * Returns the admissible noreg register node for input register pos of node irn.
178  */
179 static ir_node *ia32_get_admissible_noreg(ir_node *irn, int pos)
180 {
181         ir_graph                  *irg = get_irn_irg(irn);
182         const arch_register_req_t *req = arch_get_irn_register_req_in(irn, pos);
183
184         assert(req != NULL && "Missing register requirements");
185         if (req->cls == &ia32_reg_classes[CLASS_ia32_gp])
186                 return ia32_new_NoReg_gp(irg);
187
188         if (ia32_cg_config.use_sse2) {
189                 return ia32_new_NoReg_xmm(irg);
190         } else {
191                 return ia32_new_NoReg_vfp(irg);
192         }
193 }
194
195 static arch_irn_class_t ia32_classify(const ir_node *irn)
196 {
197         arch_irn_class_t classification = arch_irn_class_none;
198
199         assert(is_ia32_irn(irn));
200
201         if (is_ia32_is_reload(irn))
202                 classification |= arch_irn_class_reload;
203
204         if (is_ia32_is_spill(irn))
205                 classification |= arch_irn_class_spill;
206
207         if (is_ia32_is_remat(irn))
208                 classification |= arch_irn_class_remat;
209
210         return classification;
211 }
212
213 /**
214  * The IA32 ABI callback object.
215  */
216 typedef struct {
217         be_abi_call_flags_bits_t flags;  /**< The call flags. */
218         ir_graph *irg;                   /**< The associated graph. */
219 } ia32_abi_env_t;
220
221 static ir_entity *ia32_get_frame_entity(const ir_node *irn)
222 {
223         return is_ia32_irn(irn) ? get_ia32_frame_ent(irn) : NULL;
224 }
225
226 static void ia32_set_frame_entity(ir_node *node, ir_entity *entity)
227 {
228         if (is_be_node(node))
229                 be_node_set_frame_entity(node, entity);
230         else
231                 set_ia32_frame_ent(node, entity);
232 }
233
234 static void ia32_set_frame_offset(ir_node *irn, int bias)
235 {
236         if (get_ia32_frame_ent(irn) == NULL)
237                 return;
238
239         if (is_ia32_Pop(irn) || is_ia32_PopMem(irn)) {
240                 ir_graph          *irg     = get_irn_irg(irn);
241                 be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
242                 if (layout->sp_relative) {
243                         /* Pop nodes modify the stack pointer before calculating the
244                          * destination address, so fix this here
245                          */
246                         bias -= 4;
247                 }
248         }
249         add_ia32_am_offs_int(irn, bias);
250 }
251
252 static int ia32_get_sp_bias(const ir_node *node)
253 {
254         if (is_ia32_Call(node))
255                 return -(int)get_ia32_call_attr_const(node)->pop;
256
257         if (is_ia32_Push(node))
258                 return 4;
259
260         if (is_ia32_Pop(node) || is_ia32_PopMem(node))
261                 return -4;
262
263         if (is_ia32_Leave(node) || is_ia32_CopyEbpEsp(node)) {
264                 return SP_BIAS_RESET;
265         }
266
267         return 0;
268 }
269
270 /**
271  * Build the between type and entities if not already build.
272  */
273 static void ia32_build_between_type(void)
274 {
275 #define IDENT(s) new_id_from_chars(s, sizeof(s)-1)
276         if (! between_type) {
277                 ir_type *old_bp_type   = new_type_primitive(mode_Iu);
278                 ir_type *ret_addr_type = new_type_primitive(mode_Iu);
279
280                 between_type           = new_type_struct(IDENT("ia32_between_type"));
281                 old_bp_ent             = new_entity(between_type, IDENT("old_bp"), old_bp_type);
282                 ret_addr_ent           = new_entity(between_type, IDENT("ret_addr"), ret_addr_type);
283
284                 set_entity_offset(old_bp_ent, 0);
285                 set_entity_offset(ret_addr_ent, get_type_size_bytes(old_bp_type));
286                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
287                 set_type_state(between_type, layout_fixed);
288
289                 omit_fp_between_type = new_type_struct(IDENT("ia32_between_type_omit_fp"));
290                 omit_fp_ret_addr_ent = new_entity(omit_fp_between_type, IDENT("ret_addr"), ret_addr_type);
291
292                 set_entity_offset(omit_fp_ret_addr_ent, 0);
293                 set_type_size_bytes(omit_fp_between_type, get_type_size_bytes(ret_addr_type));
294                 set_type_state(omit_fp_between_type, layout_fixed);
295         }
296 #undef IDENT
297 }
298
299 /**
300  * Produces the type which sits between the stack args and the locals on the stack.
301  * it will contain the return address and space to store the old base pointer.
302  * @return The Firm type modeling the ABI between type.
303  */
304 static ir_type *ia32_abi_get_between_type(ir_graph *irg)
305 {
306         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
307         ia32_build_between_type();
308         return layout->sp_relative ? omit_fp_between_type : between_type;
309 }
310
311 /**
312  * Return the stack entity that contains the return address.
313  */
314 ir_entity *ia32_get_return_address_entity(ir_graph *irg)
315 {
316         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
317         ia32_build_between_type();
318         return layout->sp_relative ? omit_fp_ret_addr_ent : ret_addr_ent;
319 }
320
321 /**
322  * Return the stack entity that contains the frame address.
323  */
324 ir_entity *ia32_get_frame_address_entity(ir_graph *irg)
325 {
326         const be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
327         ia32_build_between_type();
328         return layout->sp_relative ? NULL : old_bp_ent;
329 }
330
331 /**
332  * Get the estimated cycle count for @p irn.
333  *
334  * @param self The this pointer.
335  * @param irn  The node.
336  *
337  * @return     The estimated cycle count for this operation
338  */
339 static int ia32_get_op_estimated_cost(const ir_node *irn)
340 {
341         int            cost;
342         ia32_op_type_t op_tp;
343
344         if (is_Proj(irn))
345                 return 0;
346         if (!is_ia32_irn(irn))
347                 return 0;
348
349         assert(is_ia32_irn(irn));
350
351         cost  = get_ia32_latency(irn);
352         op_tp = get_ia32_op_type(irn);
353
354         if (is_ia32_CopyB(irn)) {
355                 cost = 250;
356         }
357         else if (is_ia32_CopyB_i(irn)) {
358                 int size = get_ia32_copyb_size(irn);
359                 cost     = 20 + (int)ceil((4/3) * size);
360         }
361         /* in case of address mode operations add additional cycles */
362         else if (op_tp == ia32_AddrModeD || op_tp == ia32_AddrModeS) {
363                 /*
364                         In case of stack access and access to fixed addresses add 5 cycles
365                         (we assume they are in cache), other memory operations cost 20
366                         cycles.
367                 */
368                 if (is_ia32_use_frame(irn) || (
369                     is_ia32_NoReg_GP(get_irn_n(irn, n_ia32_base)) &&
370                     is_ia32_NoReg_GP(get_irn_n(irn, n_ia32_index))
371                     )) {
372                         cost += 5;
373                 } else {
374                         cost += 20;
375                 }
376         }
377
378         return cost;
379 }
380
381 /**
382  * Returns the inverse operation if @p irn, recalculating the argument at position @p i.
383  *
384  * @param irn       The original operation
385  * @param i         Index of the argument we want the inverse operation to yield
386  * @param inverse   struct to be filled with the resulting inverse op
387  * @param obstack   The obstack to use for allocation of the returned nodes array
388  * @return          The inverse operation or NULL if operation invertible
389  */
390 static arch_inverse_t *ia32_get_inverse(const ir_node *irn, int i, arch_inverse_t *inverse, struct obstack *obst)
391 {
392         (void) irn;
393         (void) i;
394         (void) inverse;
395         (void) obst;
396         return NULL;
397
398 #if 0
399         ir_mode  *mode;
400         ir_mode  *irn_mode;
401         ir_node  *block, *noreg, *nomem;
402         dbg_info *dbgi;
403
404         /* we cannot invert non-ia32 irns */
405         if (! is_ia32_irn(irn))
406                 return NULL;
407
408         /* operand must always be a real operand (not base, index or mem) */
409         if (i != n_ia32_binary_left && i != n_ia32_binary_right)
410                 return NULL;
411
412         /* we don't invert address mode operations */
413         if (get_ia32_op_type(irn) != ia32_Normal)
414                 return NULL;
415
416         /* TODO: adjust for new immediates... */
417         ir_fprintf(stderr, "TODO: fix get_inverse for new immediates (%+F)\n",
418                    irn);
419         return NULL;
420
421         block    = get_nodes_block(irn);
422         mode     = get_irn_mode(irn);
423         irn_mode = get_irn_mode(irn);
424         noreg    = get_irn_n(irn, 0);
425         nomem    = get_irg_no_mem(irg);
426         dbgi     = get_irn_dbg_info(irn);
427
428         /* initialize structure */
429         inverse->nodes = obstack_alloc(obst, 2 * sizeof(inverse->nodes[0]));
430         inverse->costs = 0;
431         inverse->n     = 1;
432
433         switch (get_ia32_irn_opcode(irn)) {
434                 case iro_ia32_Add:
435                         if (get_ia32_immop_type(irn) == ia32_ImmConst) {
436                                 /* we have an add with a const here */
437                                 /* invers == add with negated const */
438                                 inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
439                                 inverse->costs   += 1;
440                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
441                                 set_ia32_Immop_tarval(inverse->nodes[0], tarval_neg(get_ia32_Immop_tarval(irn)));
442                                 set_ia32_commutative(inverse->nodes[0]);
443                         }
444                         else if (get_ia32_immop_type(irn) == ia32_ImmSymConst) {
445                                 /* we have an add with a symconst here */
446                                 /* invers == sub with const */
447                                 inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
448                                 inverse->costs   += 2;
449                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
450                         }
451                         else {
452                                 /* normal add: inverse == sub */
453                                 inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, i ^ 1));
454                                 inverse->costs   += 2;
455                         }
456                         break;
457                 case iro_ia32_Sub:
458                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
459                                 /* we have a sub with a const/symconst here */
460                                 /* invers == add with this const */
461                                 inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
462                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
463                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
464                         }
465                         else {
466                                 /* normal sub */
467                                 if (i == n_ia32_binary_left) {
468                                         inverse->nodes[0] = new_bd_ia32_Add(dbgi, block, noreg, noreg, nomem, (ir_node*) irn, get_irn_n(irn, 3));
469                                 }
470                                 else {
471                                         inverse->nodes[0] = new_bd_ia32_Sub(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, n_ia32_binary_left), (ir_node*) irn);
472                                 }
473                                 inverse->costs += 1;
474                         }
475                         break;
476                 case iro_ia32_Xor:
477                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
478                                 /* xor with const: inverse = xor */
479                                 inverse->nodes[0] = new_bd_ia32_Xor(dbgi, block, noreg, noreg, nomem, get_irn_n(irn, i), noreg);
480                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
481                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
482                         }
483                         else {
484                                 /* normal xor */
485                                 inverse->nodes[0] = new_bd_ia32_Xor(dbgi, block, noreg, noreg, nomem, (ir_node *) irn, get_irn_n(irn, i));
486                                 inverse->costs   += 1;
487                         }
488                         break;
489                 case iro_ia32_Not: {
490                         inverse->nodes[0] = new_bd_ia32_Not(dbgi, block, (ir_node*) irn);
491                         inverse->costs   += 1;
492                         break;
493                 }
494                 case iro_ia32_Neg: {
495                         inverse->nodes[0] = new_bd_ia32_Neg(dbgi, block, (ir_node*) irn);
496                         inverse->costs   += 1;
497                         break;
498                 }
499                 default:
500                         /* inverse operation not supported */
501                         return NULL;
502         }
503
504         return inverse;
505 #endif
506 }
507
508 static ir_mode *get_spill_mode_mode(const ir_mode *mode)
509 {
510         if (mode_is_float(mode))
511                 return mode_D;
512
513         return mode_Iu;
514 }
515
516 /**
517  * Get the mode that should be used for spilling value node
518  */
519 static ir_mode *get_spill_mode(const ir_node *node)
520 {
521         ir_mode *mode = get_irn_mode(node);
522         return get_spill_mode_mode(mode);
523 }
524
525 /**
526  * Checks whether an addressmode reload for a node with mode mode is compatible
527  * with a spillslot of mode spill_mode
528  */
529 static int ia32_is_spillmode_compatible(const ir_mode *mode, const ir_mode *spillmode)
530 {
531         return !mode_is_float(mode) || mode == spillmode;
532 }
533
534 /**
535  * Check if irn can load its operand at position i from memory (source addressmode).
536  * @param irn    The irn to be checked
537  * @param i      The operands position
538  * @return Non-Zero if operand can be loaded
539  */
540 static int ia32_possible_memory_operand(const ir_node *irn, unsigned int i)
541 {
542         ir_node       *op        = get_irn_n(irn, i);
543         const ir_mode *mode      = get_irn_mode(op);
544         const ir_mode *spillmode = get_spill_mode(op);
545
546         if (!is_ia32_irn(irn)                              ||  /* must be an ia32 irn */
547             get_ia32_op_type(irn) != ia32_Normal           ||  /* must not already be a addressmode irn */
548             !ia32_is_spillmode_compatible(mode, spillmode) ||
549             is_ia32_use_frame(irn))                            /* must not already use frame */
550                 return 0;
551
552         switch (get_ia32_am_support(irn)) {
553                 case ia32_am_none:
554                         return 0;
555
556                 case ia32_am_unary:
557                         if (i != n_ia32_unary_op)
558                                 return 0;
559                         break;
560
561                 case ia32_am_binary:
562                         switch (i) {
563                                 case n_ia32_binary_left: {
564                                         const arch_register_req_t *req;
565                                         if (!is_ia32_commutative(irn))
566                                                 return 0;
567
568                                         /* we can't swap left/right for limited registers
569                                          * (As this (currently) breaks constraint handling copies)
570                                          */
571                                         req = arch_get_irn_register_req_in(irn, n_ia32_binary_left);
572                                         if (req->type & arch_register_req_type_limited)
573                                                 return 0;
574                                         break;
575                                 }
576
577                                 case n_ia32_binary_right:
578                                         break;
579
580                                 default:
581                                         return 0;
582                         }
583                         break;
584
585                 default:
586                         panic("Unknown AM type");
587         }
588
589         /* HACK: must not already use "real" memory.
590          * This can happen for Call and Div */
591         if (!is_NoMem(get_irn_n(irn, n_ia32_mem)))
592                 return 0;
593
594         return 1;
595 }
596
597 static void ia32_perform_memory_operand(ir_node *irn, ir_node *spill,
598                                         unsigned int i)
599 {
600         ir_mode *load_mode;
601         ir_mode *dest_op_mode;
602
603         assert(ia32_possible_memory_operand(irn, i) && "Cannot perform memory operand change");
604
605         set_ia32_op_type(irn, ia32_AddrModeS);
606
607         load_mode    = get_irn_mode(get_irn_n(irn, i));
608         dest_op_mode = get_ia32_ls_mode(irn);
609         if (get_mode_size_bits(load_mode) <= get_mode_size_bits(dest_op_mode)) {
610                 set_ia32_ls_mode(irn, load_mode);
611         }
612         set_ia32_use_frame(irn);
613         set_ia32_need_stackent(irn);
614
615         if (i == n_ia32_binary_left                    &&
616             get_ia32_am_support(irn) == ia32_am_binary &&
617             /* immediates are only allowed on the right side */
618             !is_ia32_Immediate(get_irn_n(irn, n_ia32_binary_right))) {
619                 ia32_swap_left_right(irn);
620                 i = n_ia32_binary_right;
621         }
622
623         assert(is_NoMem(get_irn_n(irn, n_ia32_mem)));
624
625         set_irn_n(irn, n_ia32_base, get_irg_frame(get_irn_irg(irn)));
626         set_irn_n(irn, n_ia32_mem,  spill);
627         set_irn_n(irn, i,           ia32_get_admissible_noreg(irn, i));
628         set_ia32_is_reload(irn);
629 }
630
631 static const be_abi_callbacks_t ia32_abi_callbacks = {
632         ia32_abi_get_between_type,
633 };
634
635 /* register allocator interface */
636 static const arch_irn_ops_t ia32_irn_ops = {
637         ia32_classify,
638         ia32_get_frame_entity,
639         ia32_set_frame_offset,
640         ia32_get_sp_bias,
641         ia32_get_inverse,
642         ia32_get_op_estimated_cost,
643         ia32_possible_memory_operand,
644         ia32_perform_memory_operand,
645 };
646
647 static ir_entity *mcount = NULL;
648 static int gprof = 0;
649
650 static void ia32_before_abi(ir_graph *irg)
651 {
652         if (gprof) {
653                 if (mcount == NULL) {
654                         ir_type *tp = new_type_method(0, 0);
655                         ident   *id = new_id_from_str("mcount");
656                         mcount = new_entity(get_glob_type(), id, tp);
657                         /* FIXME: enter the right ld_ident here */
658                         set_entity_ld_ident(mcount, get_entity_ident(mcount));
659                         set_entity_visibility(mcount, ir_visibility_external);
660                 }
661                 instrument_initcall(irg, mcount);
662         }
663 }
664
665 /**
666  * Transforms the standard firm graph into
667  * an ia32 firm graph
668  */
669 static void ia32_prepare_graph(ir_graph *irg)
670 {
671         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
672
673 #ifdef FIRM_GRGEN_BE
674         switch (be_transformer) {
675         case TRANSFORMER_DEFAULT:
676                 /* transform remaining nodes into assembler instructions */
677                 ia32_transform_graph(irg);
678                 break;
679
680         case TRANSFORMER_PBQP:
681         case TRANSFORMER_RAND:
682                 /* transform nodes into assembler instructions by PBQP magic */
683                 ia32_transform_graph_by_pbqp(irg);
684                 break;
685
686         default:
687                 panic("invalid transformer");
688         }
689 #else
690         ia32_transform_graph(irg);
691 #endif
692
693         /* do local optimizations (mainly CSE) */
694         optimize_graph_df(irg);
695         /* backend code expects that outedges are always enabled */
696         edges_assure(irg);
697
698         if (irg_data->dump)
699                 dump_ir_graph(irg, "transformed");
700
701         /* optimize address mode */
702         ia32_optimize_graph(irg);
703
704         /* do code placement, to optimize the position of constants */
705         place_code(irg);
706         /* backend code expects that outedges are always enabled */
707         edges_assure(irg);
708
709         if (irg_data->dump)
710                 dump_ir_graph(irg, "place");
711 }
712
713 ir_node *ia32_turn_back_am(ir_node *node)
714 {
715         dbg_info *dbgi  = get_irn_dbg_info(node);
716         ir_graph *irg   = get_irn_irg(node);
717         ir_node  *block = get_nodes_block(node);
718         ir_node  *base  = get_irn_n(node, n_ia32_base);
719         ir_node  *idx   = get_irn_n(node, n_ia32_index);
720         ir_node  *mem   = get_irn_n(node, n_ia32_mem);
721         ir_node  *noreg;
722
723         ir_node  *load     = new_bd_ia32_Load(dbgi, block, base, idx, mem);
724         ir_node  *load_res = new_rd_Proj(dbgi, load, mode_Iu, pn_ia32_Load_res);
725
726         ia32_copy_am_attrs(load, node);
727         if (is_ia32_is_reload(node))
728                 set_ia32_is_reload(load);
729         set_irn_n(node, n_ia32_mem, get_irg_no_mem(irg));
730
731         switch (get_ia32_am_support(node)) {
732                 case ia32_am_unary:
733                         set_irn_n(node, n_ia32_unary_op, load_res);
734                         break;
735
736                 case ia32_am_binary:
737                         if (is_ia32_Immediate(get_irn_n(node, n_ia32_binary_right))) {
738                                 set_irn_n(node, n_ia32_binary_left, load_res);
739                         } else {
740                                 set_irn_n(node, n_ia32_binary_right, load_res);
741                         }
742                         break;
743
744                 default:
745                         panic("Unknown AM type");
746         }
747         noreg = ia32_new_NoReg_gp(current_ir_graph);
748         set_irn_n(node, n_ia32_base,  noreg);
749         set_irn_n(node, n_ia32_index, noreg);
750         set_ia32_am_offs_int(node, 0);
751         set_ia32_am_sc(node, NULL);
752         set_ia32_am_scale(node, 0);
753         clear_ia32_am_sc_sign(node);
754
755         /* rewire mem-proj */
756         if (get_irn_mode(node) == mode_T) {
757                 const ir_edge_t *edge;
758                 foreach_out_edge(node, edge) {
759                         ir_node *out = get_edge_src_irn(edge);
760                         if (get_irn_mode(out) == mode_M) {
761                                 set_Proj_pred(out, load);
762                                 set_Proj_proj(out, pn_ia32_Load_M);
763                                 break;
764                         }
765                 }
766         }
767
768         set_ia32_op_type(node, ia32_Normal);
769         if (sched_is_scheduled(node))
770                 sched_add_before(node, load);
771
772         return load_res;
773 }
774
775 static ir_node *flags_remat(ir_node *node, ir_node *after)
776 {
777         /* we should turn back source address mode when rematerializing nodes */
778         ia32_op_type_t type;
779         ir_node        *block;
780         ir_node        *copy;
781
782         if (is_Block(after)) {
783                 block = after;
784         } else {
785                 block = get_nodes_block(after);
786         }
787
788         type = get_ia32_op_type(node);
789         switch (type) {
790                 case ia32_AddrModeS:
791                         ia32_turn_back_am(node);
792                         break;
793
794                 case ia32_AddrModeD:
795                         /* TODO implement this later... */
796                         panic("found DestAM with flag user %+F this should not happen", node);
797
798                 default: assert(type == ia32_Normal); break;
799         }
800
801         copy = exact_copy(node);
802         set_nodes_block(copy, block);
803         sched_add_after(after, copy);
804
805         return copy;
806 }
807
808 /**
809  * Called before the register allocator.
810  */
811 static void ia32_before_ra(ir_graph *irg)
812 {
813         /* setup fpu rounding modes */
814         ia32_setup_fpu_mode(irg);
815
816         /* fixup flags */
817         be_sched_fix_flags(irg, &ia32_reg_classes[CLASS_ia32_flags],
818                            &flags_remat, NULL);
819
820         be_add_missing_keeps(irg);
821 }
822
823
824 /**
825  * Transforms a be_Reload into a ia32 Load.
826  */
827 static void transform_to_Load(ir_node *node)
828 {
829         ir_graph *irg        = get_irn_irg(node);
830         dbg_info *dbgi       = get_irn_dbg_info(node);
831         ir_node *block       = get_nodes_block(node);
832         ir_entity *ent       = be_get_frame_entity(node);
833         ir_mode *mode        = get_irn_mode(node);
834         ir_mode *spillmode   = get_spill_mode(node);
835         ir_node *noreg       = ia32_new_NoReg_gp(irg);
836         ir_node *sched_point = NULL;
837         ir_node *ptr         = get_irg_frame(irg);
838         ir_node *mem         = get_irn_n(node, n_be_Reload_mem);
839         ir_node *new_op, *proj;
840         const arch_register_t *reg;
841
842         if (sched_is_scheduled(node)) {
843                 sched_point = sched_prev(node);
844         }
845
846         if (mode_is_float(spillmode)) {
847                 if (ia32_cg_config.use_sse2)
848                         new_op = new_bd_ia32_xLoad(dbgi, block, ptr, noreg, mem, spillmode);
849                 else
850                         new_op = new_bd_ia32_vfld(dbgi, block, ptr, noreg, mem, spillmode);
851         }
852         else if (get_mode_size_bits(spillmode) == 128) {
853                 /* Reload 128 bit SSE registers */
854                 new_op = new_bd_ia32_xxLoad(dbgi, block, ptr, noreg, mem);
855         }
856         else
857                 new_op = new_bd_ia32_Load(dbgi, block, ptr, noreg, mem);
858
859         set_ia32_op_type(new_op, ia32_AddrModeS);
860         set_ia32_ls_mode(new_op, spillmode);
861         set_ia32_frame_ent(new_op, ent);
862         set_ia32_use_frame(new_op);
863         set_ia32_is_reload(new_op);
864
865         DBG_OPT_RELOAD2LD(node, new_op);
866
867         proj = new_rd_Proj(dbgi, new_op, mode, pn_ia32_Load_res);
868
869         if (sched_point) {
870                 sched_add_after(sched_point, new_op);
871                 sched_remove(node);
872         }
873
874         /* copy the register from the old node to the new Load */
875         reg = arch_get_irn_register(node);
876         arch_set_irn_register(proj, reg);
877
878         SET_IA32_ORIG_NODE(new_op, node);
879
880         exchange(node, proj);
881 }
882
883 /**
884  * Transforms a be_Spill node into a ia32 Store.
885  */
886 static void transform_to_Store(ir_node *node)
887 {
888         ir_graph *irg  = get_irn_irg(node);
889         dbg_info *dbgi = get_irn_dbg_info(node);
890         ir_node *block = get_nodes_block(node);
891         ir_entity *ent = be_get_frame_entity(node);
892         const ir_node *spillval = get_irn_n(node, n_be_Spill_val);
893         ir_mode *mode  = get_spill_mode(spillval);
894         ir_node *noreg = ia32_new_NoReg_gp(irg);
895         ir_node *nomem = get_irg_no_mem(irg);
896         ir_node *ptr   = get_irg_frame(irg);
897         ir_node *val   = get_irn_n(node, n_be_Spill_val);
898         ir_node *res;
899         ir_node *store;
900         ir_node *sched_point = NULL;
901
902         if (sched_is_scheduled(node)) {
903                 sched_point = sched_prev(node);
904         }
905
906         if (mode_is_float(mode)) {
907                 if (ia32_cg_config.use_sse2) {
908                         store = new_bd_ia32_xStore(dbgi, block, ptr, noreg, nomem, val);
909                         res   = new_r_Proj(store, mode_M, pn_ia32_xStore_M);
910                 } else {
911                         store = new_bd_ia32_vfst(dbgi, block, ptr, noreg, nomem, val, mode);
912                         res   = new_r_Proj(store, mode_M, pn_ia32_vfst_M);
913                 }
914         } else if (get_mode_size_bits(mode) == 128) {
915                 /* Spill 128 bit SSE registers */
916                 store = new_bd_ia32_xxStore(dbgi, block, ptr, noreg, nomem, val);
917                 res   = new_r_Proj(store, mode_M, pn_ia32_xxStore_M);
918         } else if (get_mode_size_bits(mode) == 8) {
919                 store = new_bd_ia32_Store8Bit(dbgi, block, ptr, noreg, nomem, val);
920                 res   = new_r_Proj(store, mode_M, pn_ia32_Store8Bit_M);
921         } else {
922                 store = new_bd_ia32_Store(dbgi, block, ptr, noreg, nomem, val);
923                 res   = new_r_Proj(store, mode_M, pn_ia32_Store_M);
924         }
925
926         set_ia32_op_type(store, ia32_AddrModeD);
927         set_ia32_ls_mode(store, mode);
928         set_ia32_frame_ent(store, ent);
929         set_ia32_use_frame(store);
930         set_ia32_is_spill(store);
931         SET_IA32_ORIG_NODE(store, node);
932         DBG_OPT_SPILL2ST(node, store);
933
934         if (sched_point) {
935                 sched_add_after(sched_point, store);
936                 sched_remove(node);
937         }
938
939         exchange(node, res);
940 }
941
942 static ir_node *create_push(ir_node *node, ir_node *schedpoint, ir_node *sp, ir_node *mem, ir_entity *ent)
943 {
944         dbg_info *dbgi  = get_irn_dbg_info(node);
945         ir_node  *block = get_nodes_block(node);
946         ir_graph *irg   = get_irn_irg(node);
947         ir_node  *noreg = ia32_new_NoReg_gp(irg);
948         ir_node  *frame = get_irg_frame(irg);
949
950         ir_node *push = new_bd_ia32_Push(dbgi, block, frame, noreg, mem, noreg, sp);
951
952         set_ia32_frame_ent(push, ent);
953         set_ia32_use_frame(push);
954         set_ia32_op_type(push, ia32_AddrModeS);
955         set_ia32_ls_mode(push, mode_Is);
956         set_ia32_is_spill(push);
957
958         sched_add_before(schedpoint, push);
959         return push;
960 }
961
962 static ir_node *create_pop(ir_node *node, ir_node *schedpoint, ir_node *sp, ir_entity *ent)
963 {
964         dbg_info *dbgi  = get_irn_dbg_info(node);
965         ir_node  *block = get_nodes_block(node);
966         ir_graph *irg   = get_irn_irg(node);
967         ir_node  *noreg = ia32_new_NoReg_gp(irg);
968         ir_node  *frame = get_irg_frame(irg);
969
970         ir_node *pop = new_bd_ia32_PopMem(dbgi, block, frame, noreg,
971                                           get_irg_no_mem(irg), sp);
972
973         set_ia32_frame_ent(pop, ent);
974         set_ia32_use_frame(pop);
975         set_ia32_op_type(pop, ia32_AddrModeD);
976         set_ia32_ls_mode(pop, mode_Is);
977         set_ia32_is_reload(pop);
978
979         sched_add_before(schedpoint, pop);
980
981         return pop;
982 }
983
984 static ir_node* create_spproj(ir_node *node, ir_node *pred, int pos)
985 {
986         dbg_info *dbgi   = get_irn_dbg_info(node);
987         ir_mode  *spmode = mode_Iu;
988         const arch_register_t *spreg = &ia32_registers[REG_ESP];
989         ir_node *sp;
990
991         sp = new_rd_Proj(dbgi, pred, spmode, pos);
992         arch_set_irn_register(sp, spreg);
993
994         return sp;
995 }
996
997 /**
998  * Transform MemPerm, currently we do this the ugly way and produce
999  * push/pop into/from memory cascades. This is possible without using
1000  * any registers.
1001  */
1002 static void transform_MemPerm(ir_node *node)
1003 {
1004         ir_node         *block = get_nodes_block(node);
1005         ir_graph        *irg   = get_irn_irg(node);
1006         ir_node         *sp    = be_get_initial_reg_value(irg, &ia32_registers[REG_ESP]);
1007         int              arity = be_get_MemPerm_entity_arity(node);
1008         ir_node        **pops  = ALLOCAN(ir_node*, arity);
1009         ir_node         *in[1];
1010         ir_node         *keep;
1011         int              i;
1012         const ir_edge_t *edge;
1013         const ir_edge_t *next;
1014
1015         /* create Pushs */
1016         for (i = 0; i < arity; ++i) {
1017                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1018                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1019                 ir_type *enttype = get_entity_type(inent);
1020                 unsigned entsize = get_type_size_bytes(enttype);
1021                 unsigned entsize2 = get_type_size_bytes(get_entity_type(outent));
1022                 ir_node *mem = get_irn_n(node, i + 1);
1023                 ir_node *push;
1024
1025                 /* work around cases where entities have different sizes */
1026                 if (entsize2 < entsize)
1027                         entsize = entsize2;
1028                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1029
1030                 push = create_push(node, node, sp, mem, inent);
1031                 sp = create_spproj(node, push, pn_ia32_Push_stack);
1032                 if (entsize == 8) {
1033                         /* add another push after the first one */
1034                         push = create_push(node, node, sp, mem, inent);
1035                         add_ia32_am_offs_int(push, 4);
1036                         sp = create_spproj(node, push, pn_ia32_Push_stack);
1037                 }
1038
1039                 set_irn_n(node, i, new_r_Bad(irg, mode_X));
1040         }
1041
1042         /* create pops */
1043         for (i = arity - 1; i >= 0; --i) {
1044                 ir_entity *inent = be_get_MemPerm_in_entity(node, i);
1045                 ir_entity *outent = be_get_MemPerm_out_entity(node, i);
1046                 ir_type *enttype = get_entity_type(outent);
1047                 unsigned entsize = get_type_size_bytes(enttype);
1048                 unsigned entsize2 = get_type_size_bytes(get_entity_type(inent));
1049                 ir_node *pop;
1050
1051                 /* work around cases where entities have different sizes */
1052                 if (entsize2 < entsize)
1053                         entsize = entsize2;
1054                 assert( (entsize == 4 || entsize == 8) && "spillslot on x86 should be 32 or 64 bit");
1055
1056                 pop = create_pop(node, node, sp, outent);
1057                 sp = create_spproj(node, pop, pn_ia32_Pop_stack);
1058                 if (entsize == 8) {
1059                         add_ia32_am_offs_int(pop, 4);
1060
1061                         /* add another pop after the first one */
1062                         pop = create_pop(node, node, sp, outent);
1063                         sp = create_spproj(node, pop, pn_ia32_Pop_stack);
1064                 }
1065
1066                 pops[i] = pop;
1067         }
1068
1069         in[0] = sp;
1070         keep  = be_new_Keep(block, 1, in);
1071         sched_add_before(node, keep);
1072
1073         /* exchange memprojs */
1074         foreach_out_edge_safe(node, edge, next) {
1075                 ir_node *proj = get_edge_src_irn(edge);
1076                 int p = get_Proj_proj(proj);
1077
1078                 assert(p < arity);
1079
1080                 set_Proj_pred(proj, pops[p]);
1081                 set_Proj_proj(proj, pn_ia32_Pop_M);
1082         }
1083
1084         /* remove memperm */
1085         sched_remove(node);
1086         kill_node(node);
1087 }
1088
1089 /**
1090  * Block-Walker: Calls the transform functions Spill and Reload.
1091  */
1092 static void ia32_after_ra_walker(ir_node *block, void *env)
1093 {
1094         ir_node *node, *prev;
1095         (void) env;
1096
1097         /* beware: the schedule is changed here */
1098         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
1099                 prev = sched_prev(node);
1100
1101                 if (be_is_Reload(node)) {
1102                         transform_to_Load(node);
1103                 } else if (be_is_Spill(node)) {
1104                         transform_to_Store(node);
1105                 } else if (be_is_MemPerm(node)) {
1106                         transform_MemPerm(node);
1107                 }
1108         }
1109 }
1110
1111 /**
1112  * Collects nodes that need frame entities assigned.
1113  */
1114 static void ia32_collect_frame_entity_nodes(ir_node *node, void *data)
1115 {
1116         be_fec_env_t  *env = (be_fec_env_t*)data;
1117         const ir_mode *mode;
1118         int            align;
1119
1120         if (be_is_Reload(node) && be_get_frame_entity(node) == NULL) {
1121                 mode  = get_spill_mode_mode(get_irn_mode(node));
1122                 align = get_mode_size_bytes(mode);
1123         } else if (is_ia32_irn(node)         &&
1124                         get_ia32_frame_ent(node) == NULL &&
1125                         is_ia32_use_frame(node)) {
1126                 if (is_ia32_need_stackent(node))
1127                         goto need_stackent;
1128
1129                 switch (get_ia32_irn_opcode(node)) {
1130 need_stackent:
1131                         case iro_ia32_Load: {
1132                                 const ia32_attr_t *attr = get_ia32_attr_const(node);
1133
1134                                 if (attr->data.need_32bit_stackent) {
1135                                         mode = mode_Is;
1136                                 } else if (attr->data.need_64bit_stackent) {
1137                                         mode = mode_Ls;
1138                                 } else {
1139                                         mode = get_ia32_ls_mode(node);
1140                                         if (is_ia32_is_reload(node))
1141                                                 mode = get_spill_mode_mode(mode);
1142                                 }
1143                                 align = get_mode_size_bytes(mode);
1144                                 break;
1145                         }
1146
1147                         case iro_ia32_vfild:
1148                         case iro_ia32_vfld:
1149                         case iro_ia32_xLoad: {
1150                                 mode  = get_ia32_ls_mode(node);
1151                                 align = 4;
1152                                 break;
1153                         }
1154
1155                         case iro_ia32_FldCW: {
1156                                 /* although 2 byte would be enough 4 byte performs best */
1157                                 mode  = mode_Iu;
1158                                 align = 4;
1159                                 break;
1160                         }
1161
1162                         default:
1163 #ifndef NDEBUG
1164                                 panic("unexpected frame user while collection frame entity nodes");
1165
1166                         case iro_ia32_FnstCW:
1167                         case iro_ia32_Store8Bit:
1168                         case iro_ia32_Store:
1169                         case iro_ia32_fst:
1170                         case iro_ia32_fstp:
1171                         case iro_ia32_vfist:
1172                         case iro_ia32_vfisttp:
1173                         case iro_ia32_vfst:
1174                         case iro_ia32_xStore:
1175                         case iro_ia32_xStoreSimple:
1176 #endif
1177                                 return;
1178                 }
1179         } else {
1180                 return;
1181         }
1182         be_node_needs_frame_entity(env, node, mode, align);
1183 }
1184
1185 static int determine_ebp_input(ir_node *ret)
1186 {
1187         const arch_register_t *bp = &ia32_registers[REG_EBP];
1188         int   arity               = get_irn_arity(ret);
1189         int   i;
1190
1191         for (i = 0; i < arity; ++i) {
1192                 ir_node *input = get_irn_n(ret, i);
1193                 if (arch_get_irn_register(input) == bp)
1194                         return i;
1195         }
1196         panic("no ebp input found at %+F", ret);
1197 }
1198
1199 static void introduce_epilog(ir_node *ret)
1200 {
1201         const arch_register_t *sp         = &ia32_registers[REG_ESP];
1202         const arch_register_t *bp         = &ia32_registers[REG_EBP];
1203         ir_graph              *irg        = get_irn_irg(ret);
1204         ir_type               *frame_type = get_irg_frame_type(irg);
1205         unsigned               frame_size = get_type_size_bytes(frame_type);
1206         be_stack_layout_t     *layout     = be_get_irg_stack_layout(irg);
1207         ir_node               *block      = get_nodes_block(ret);
1208         ir_node               *first_sp   = get_irn_n(ret, n_be_Return_sp);
1209         ir_node               *curr_sp    = first_sp;
1210         ir_mode               *mode_gp    = mode_Iu;
1211
1212         if (!layout->sp_relative) {
1213                 int      n_ebp   = determine_ebp_input(ret);
1214                 ir_node *curr_bp = get_irn_n(ret, n_ebp);
1215                 if (ia32_cg_config.use_leave) {
1216                         ir_node *leave = new_bd_ia32_Leave(NULL, block, curr_bp);
1217                         curr_bp        = new_r_Proj(leave, mode_gp, pn_ia32_Leave_frame);
1218                         curr_sp        = new_r_Proj(leave, mode_gp, pn_ia32_Leave_stack);
1219                         arch_set_irn_register(curr_bp, bp);
1220                         arch_set_irn_register(curr_sp, sp);
1221                         sched_add_before(ret, leave);
1222                 } else {
1223                         ir_node *pop;
1224                         ir_node *curr_mem = get_irn_n(ret, n_be_Return_mem);
1225                         /* copy ebp to esp */
1226                         curr_sp = new_bd_ia32_CopyEbpEsp(NULL, block, curr_bp);
1227                         arch_set_irn_register(curr_sp, sp);
1228                         sched_add_before(ret, curr_sp);
1229
1230                         /* pop ebp */
1231                         pop      = new_bd_ia32_PopEbp(NULL, block, curr_mem, curr_sp);
1232                         curr_bp  = new_r_Proj(pop, mode_gp, pn_ia32_PopEbp_res);
1233                         curr_sp  = new_r_Proj(pop, mode_gp, pn_ia32_PopEbp_stack);
1234                         curr_mem = new_r_Proj(pop, mode_M, pn_ia32_Pop_M);
1235                         arch_set_irn_register(curr_bp, bp);
1236                         arch_set_irn_register(curr_sp, sp);
1237                         sched_add_before(ret, pop);
1238
1239                         set_irn_n(ret, n_be_Return_mem, curr_mem);
1240                 }
1241                 set_irn_n(ret, n_ebp, curr_bp);
1242         } else {
1243                 ir_node *incsp = be_new_IncSP(sp, block, curr_sp, -(int)frame_size, 0);
1244                 sched_add_before(ret, incsp);
1245                 curr_sp = incsp;
1246         }
1247         set_irn_n(ret, n_be_Return_sp, curr_sp);
1248
1249         /* keep verifier happy... */
1250         if (get_irn_n_edges(first_sp) == 0 && is_Proj(first_sp)) {
1251                 kill_node(first_sp);
1252         }
1253 }
1254
1255 /**
1256  * put the Prolog code at the beginning, epilog code before each return
1257  */
1258 static void introduce_prolog_epilog(ir_graph *irg)
1259 {
1260         const arch_register_t *sp         = &ia32_registers[REG_ESP];
1261         const arch_register_t *bp         = &ia32_registers[REG_EBP];
1262         ir_node               *start      = get_irg_start(irg);
1263         ir_node               *block      = get_nodes_block(start);
1264         ir_type               *frame_type = get_irg_frame_type(irg);
1265         unsigned               frame_size = get_type_size_bytes(frame_type);
1266         be_stack_layout_t     *layout     = be_get_irg_stack_layout(irg);
1267         ir_node               *initial_sp = be_get_initial_reg_value(irg, sp);
1268         ir_node               *curr_sp    = initial_sp;
1269         ir_mode               *mode_gp    = mode_Iu;
1270
1271         if (!layout->sp_relative) {
1272                 /* push ebp */
1273                 ir_node *mem        = get_irg_initial_mem(irg);
1274                 ir_node *noreg      = ia32_new_NoReg_gp(irg);
1275                 ir_node *initial_bp = be_get_initial_reg_value(irg, bp);
1276                 ir_node *curr_bp    = initial_bp;
1277                 ir_node *push       = new_bd_ia32_Push(NULL, block, noreg, noreg, mem, curr_bp, curr_sp);
1278                 ir_node *incsp;
1279
1280                 curr_sp = new_r_Proj(push, mode_gp, pn_ia32_Push_stack);
1281                 mem     = new_r_Proj(push, mode_M, pn_ia32_Push_M);
1282                 arch_set_irn_register(curr_sp, sp);
1283                 sched_add_after(start, push);
1284
1285                 /* move esp to ebp */
1286                 curr_bp = be_new_Copy(block, curr_sp);
1287                 sched_add_after(push, curr_bp);
1288                 be_set_constr_single_reg_out(curr_bp, 0, bp, arch_register_req_type_ignore);
1289                 curr_sp = be_new_CopyKeep_single(block, curr_sp, curr_bp);
1290                 sched_add_after(curr_bp, curr_sp);
1291                 be_set_constr_single_reg_out(curr_sp, 0, sp, arch_register_req_type_produces_sp);
1292                 edges_reroute(initial_bp, curr_bp);
1293                 set_irn_n(push, n_ia32_Push_val, initial_bp);
1294
1295                 incsp = be_new_IncSP(sp, block, curr_sp, frame_size, 0);
1296                 edges_reroute(initial_sp, incsp);
1297                 set_irn_n(push, n_ia32_Push_stack, initial_sp);
1298                 sched_add_after(curr_sp, incsp);
1299
1300                 /* make sure the initial IncSP is really used by someone */
1301                 if (get_irn_n_edges(incsp) <= 1) {
1302                         ir_node *in[] = { incsp };
1303                         ir_node *keep = be_new_Keep(block, 1, in);
1304                         sched_add_after(incsp, keep);
1305                 }
1306
1307                 layout->initial_bias = -4;
1308         } else {
1309                 ir_node *incsp = be_new_IncSP(sp, block, curr_sp, frame_size, 0);
1310                 edges_reroute(initial_sp, incsp);
1311                 be_set_IncSP_pred(incsp, curr_sp);
1312                 sched_add_after(start, incsp);
1313         }
1314
1315         /* introduce epilog for every return node */
1316         {
1317                 ir_node *end_block = get_irg_end_block(irg);
1318                 int      arity     = get_irn_arity(end_block);
1319                 int      i;
1320
1321                 for (i = 0; i < arity; ++i) {
1322                         ir_node *ret = get_irn_n(end_block, i);
1323                         assert(be_is_Return(ret));
1324                         introduce_epilog(ret);
1325                 }
1326         }
1327 }
1328
1329 /**
1330  * Last touchups for the graph before emit: x87 simulation to replace the
1331  * virtual with real x87 instructions, creating a block schedule and peephole
1332  * optimisations.
1333  */
1334 static void ia32_finish(ir_graph *irg)
1335 {
1336         ia32_irg_data_t   *irg_data     = ia32_get_irg_data(irg);
1337         be_stack_layout_t *stack_layout = be_get_irg_stack_layout(irg);
1338         bool               at_begin     = stack_layout->sp_relative ? true : false;
1339         be_fec_env_t      *fec_env      = be_new_frame_entity_coalescer(irg);
1340
1341         /* create and coalesce frame entities */
1342         irg_walk_graph(irg, NULL, ia32_collect_frame_entity_nodes, fec_env);
1343         be_assign_entities(fec_env, ia32_set_frame_entity, at_begin);
1344         be_free_frame_entity_coalescer(fec_env);
1345
1346         irg_block_walk_graph(irg, NULL, ia32_after_ra_walker, NULL);
1347
1348         introduce_prolog_epilog(irg);
1349
1350         /* fix stack entity offsets */
1351         be_abi_fix_stack_nodes(irg);
1352         be_abi_fix_stack_bias(irg);
1353
1354         /* fix 2-address code constraints */
1355         ia32_finish_irg(irg);
1356
1357         /* we might have to rewrite x87 virtual registers */
1358         if (irg_data->do_x87_sim) {
1359                 ia32_x87_simulate_graph(irg);
1360         }
1361
1362         /* do peephole optimisations */
1363         ia32_peephole_optimization(irg);
1364
1365         be_remove_dead_nodes_from_schedule(irg);
1366
1367         /* create block schedule, this also removes empty blocks which might
1368          * produce critical edges */
1369         irg_data->blk_sched = be_create_block_schedule(irg);
1370 }
1371
1372 /**
1373  * Emits the code, closes the output file and frees
1374  * the code generator interface.
1375  */
1376 static void ia32_emit(ir_graph *irg)
1377 {
1378         if (ia32_cg_config.emit_machcode) {
1379                 ia32_gen_binary_routine(irg);
1380         } else {
1381                 ia32_gen_routine(irg);
1382         }
1383 }
1384
1385 /**
1386  * Returns the node representing the PIC base.
1387  */
1388 static ir_node *ia32_get_pic_base(ir_graph *irg)
1389 {
1390         ia32_irg_data_t *irg_data = ia32_get_irg_data(irg);
1391         ir_node         *block;
1392         ir_node         *get_eip = irg_data->get_eip;
1393         if (get_eip != NULL)
1394                 return get_eip;
1395
1396         block             = get_irg_start_block(irg);
1397         get_eip           = new_bd_ia32_GetEIP(NULL, block);
1398         irg_data->get_eip = get_eip;
1399
1400         return get_eip;
1401 }
1402
1403 /**
1404  * Initializes a IA32 code generator.
1405  */
1406 static void ia32_init_graph(ir_graph *irg)
1407 {
1408         struct obstack  *obst     = be_get_be_obst(irg);
1409         ia32_irg_data_t *irg_data = OALLOCZ(obst, ia32_irg_data_t);
1410
1411         irg_data->dump = (be_get_irg_options(irg)->dump_flags & DUMP_BE) ? 1 : 0;
1412
1413         if (gprof) {
1414                 /* Linux gprof implementation needs base pointer */
1415                 be_get_irg_options(irg)->omit_fp = 0;
1416         }
1417
1418         be_birg_from_irg(irg)->isa_link = irg_data;
1419 }
1420
1421
1422 /**
1423  * Set output modes for GCC
1424  */
1425 static const tarval_mode_info mo_integer = {
1426         TVO_HEX,
1427         "0x",
1428         NULL,
1429 };
1430
1431 /*
1432  * set the tarval output mode of all integer modes to decimal
1433  */
1434 static void set_tarval_output_modes(void)
1435 {
1436         size_t i;
1437
1438         for (i = get_irp_n_modes(); i > 0;) {
1439                 ir_mode *mode = get_irp_mode(--i);
1440
1441                 if (mode_is_int(mode))
1442                         set_tarval_mode_output_option(mode, &mo_integer);
1443         }
1444 }
1445
1446 extern const arch_isa_if_t ia32_isa_if;
1447
1448 /**
1449  * The template that generates a new ISA object.
1450  * Note that this template can be changed by command line
1451  * arguments.
1452  */
1453 static ia32_isa_t ia32_isa_template = {
1454         {
1455                 &ia32_isa_if,            /* isa interface implementation */
1456                 N_IA32_REGISTERS,
1457                 ia32_registers,
1458                 N_IA32_CLASSES,
1459                 ia32_reg_classes,
1460                 &ia32_registers[REG_ESP],  /* stack pointer register */
1461                 &ia32_registers[REG_EBP],  /* base pointer register */
1462                 &ia32_reg_classes[CLASS_ia32_gp],  /* static link pointer register class */
1463                 2,                       /* power of two stack alignment, 2^2 == 4 */
1464                 NULL,                    /* main environment */
1465                 7,                       /* costs for a spill instruction */
1466                 5,                       /* costs for a reload instruction */
1467                 false,                   /* no custom abi handling */
1468         },
1469         NULL,                    /* types */
1470         NULL,                    /* tv_ents */
1471         NULL,                    /* abstract machine */
1472         IA32_FPU_ARCH_X87,       /* FPU architecture */
1473 };
1474
1475 static void init_asm_constraints(void)
1476 {
1477         be_init_default_asm_constraint_flags();
1478
1479         asm_constraint_flags['a'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1480         asm_constraint_flags['b'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1481         asm_constraint_flags['c'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1482         asm_constraint_flags['d'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1483         asm_constraint_flags['D'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1484         asm_constraint_flags['S'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1485         asm_constraint_flags['Q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1486         asm_constraint_flags['q'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1487         asm_constraint_flags['A'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1488         asm_constraint_flags['l'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1489         asm_constraint_flags['R'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1490         asm_constraint_flags['r'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1491         asm_constraint_flags['p'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1492         asm_constraint_flags['f'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1493         asm_constraint_flags['t'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1494         asm_constraint_flags['u'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1495         asm_constraint_flags['Y'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1496         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER;
1497         asm_constraint_flags['n'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1498         asm_constraint_flags['g'] = ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE;
1499
1500         /* no support for autodecrement/autoincrement */
1501         asm_constraint_flags['<'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1502         asm_constraint_flags['>'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1503         /* no float consts */
1504         asm_constraint_flags['E'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1505         asm_constraint_flags['F'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1506         /* makes no sense on x86 */
1507         asm_constraint_flags['s'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1508         /* no support for sse consts yet */
1509         asm_constraint_flags['C'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1510         /* no support for x87 consts yet */
1511         asm_constraint_flags['G'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1512         /* no support for mmx registers yet */
1513         asm_constraint_flags['y'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1514         /* not available in 32bit mode */
1515         asm_constraint_flags['Z'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1516         asm_constraint_flags['e'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1517
1518         /* no code yet to determine register class needed... */
1519         asm_constraint_flags['X'] = ASM_CONSTRAINT_FLAG_NO_SUPPORT;
1520 }
1521
1522 /**
1523  * Initializes the backend ISA.
1524  */
1525 static arch_env_t *ia32_init(FILE *file_handle)
1526 {
1527         ia32_isa_t *isa = XMALLOC(ia32_isa_t);
1528
1529         set_tarval_output_modes();
1530
1531         *isa = ia32_isa_template;
1532
1533         if (ia32_mode_fpcw == NULL) {
1534                 ia32_mode_fpcw = new_ir_mode("Fpcw", irms_int_number, 16, 0, irma_none, 0);
1535         }
1536
1537         ia32_register_init();
1538         ia32_create_opcodes(&ia32_irn_ops);
1539
1540         be_emit_init(file_handle);
1541         isa->types          = pmap_create();
1542         isa->tv_ent         = pmap_create();
1543         isa->cpu            = ia32_init_machine_description();
1544
1545         /* enter the ISA object into the intrinsic environment */
1546         intrinsic_env.isa = isa;
1547
1548         return &isa->base;
1549 }
1550
1551
1552
1553 /**
1554  * Closes the output file and frees the ISA structure.
1555  */
1556 static void ia32_done(void *self)
1557 {
1558         ia32_isa_t *isa = (ia32_isa_t*)self;
1559
1560         /* emit now all global declarations */
1561         be_gas_emit_decls(isa->base.main_env);
1562
1563         pmap_destroy(isa->tv_ent);
1564         pmap_destroy(isa->types);
1565
1566         be_emit_exit();
1567
1568         free(self);
1569 }
1570
1571
1572 /**
1573  * Get the register class which shall be used to store a value of a given mode.
1574  * @param self The this pointer.
1575  * @param mode The mode in question.
1576  * @return A register class which can hold values of the given mode.
1577  */
1578 static const arch_register_class_t *ia32_get_reg_class_for_mode(const ir_mode *mode)
1579 {
1580         if (mode_is_float(mode)) {
1581                 return ia32_cg_config.use_sse2 ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
1582         }
1583         else
1584                 return &ia32_reg_classes[CLASS_ia32_gp];
1585 }
1586
1587 /**
1588  * Returns the register for parameter nr.
1589  */
1590 static const arch_register_t *ia32_get_RegParam_reg(unsigned cc, unsigned nr,
1591                                                     const ir_mode *mode)
1592 {
1593         static const arch_register_t *gpreg_param_reg_fastcall[] = {
1594                 &ia32_registers[REG_ECX],
1595                 &ia32_registers[REG_EDX],
1596                 NULL
1597         };
1598         static const unsigned MAXNUM_GPREG_ARGS = 3;
1599
1600         static const arch_register_t *gpreg_param_reg_regparam[] = {
1601                 &ia32_registers[REG_EAX],
1602                 &ia32_registers[REG_EDX],
1603                 &ia32_registers[REG_ECX]
1604         };
1605
1606         static const arch_register_t *gpreg_param_reg_this[] = {
1607                 &ia32_registers[REG_ECX],
1608                 NULL,
1609                 NULL
1610         };
1611
1612         static const arch_register_t *fpreg_sse_param_reg_std[] = {
1613                 &ia32_registers[REG_XMM0],
1614                 &ia32_registers[REG_XMM1],
1615                 &ia32_registers[REG_XMM2],
1616                 &ia32_registers[REG_XMM3],
1617                 &ia32_registers[REG_XMM4],
1618                 &ia32_registers[REG_XMM5],
1619                 &ia32_registers[REG_XMM6],
1620                 &ia32_registers[REG_XMM7]
1621         };
1622
1623         static const arch_register_t *fpreg_sse_param_reg_this[] = {
1624                 NULL,  /* in case of a "this" pointer, the first parameter must not be a float */
1625         };
1626         static const unsigned MAXNUM_SSE_ARGS = 8;
1627
1628         if ((cc & cc_this_call) && nr == 0)
1629                 return gpreg_param_reg_this[0];
1630
1631         if (! (cc & cc_reg_param))
1632                 return NULL;
1633
1634         if (mode_is_float(mode)) {
1635                 if (!ia32_cg_config.use_sse2 || (cc & cc_fpreg_param) == 0)
1636                         return NULL;
1637                 if (nr >= MAXNUM_SSE_ARGS)
1638                         return NULL;
1639
1640                 if (cc & cc_this_call) {
1641                         return fpreg_sse_param_reg_this[nr];
1642                 }
1643                 return fpreg_sse_param_reg_std[nr];
1644         } else if (mode_is_int(mode) || mode_is_reference(mode)) {
1645                 unsigned num_regparam;
1646
1647                 if (get_mode_size_bits(mode) > 32)
1648                         return NULL;
1649
1650                 if (nr >= MAXNUM_GPREG_ARGS)
1651                         return NULL;
1652
1653                 if (cc & cc_this_call) {
1654                         return gpreg_param_reg_this[nr];
1655                 }
1656                 num_regparam = cc & ~cc_bits;
1657                 if (num_regparam == 0) {
1658                         /* default fastcall */
1659                         return gpreg_param_reg_fastcall[nr];
1660                 }
1661                 if (nr < num_regparam)
1662                         return gpreg_param_reg_regparam[nr];
1663                 return NULL;
1664         }
1665
1666         panic("unknown argument mode");
1667 }
1668
1669 /**
1670  * Get the ABI restrictions for procedure calls.
1671  * @param self        The this pointer.
1672  * @param method_type The type of the method (procedure) in question.
1673  * @param abi         The abi object to be modified
1674  */
1675 static void ia32_get_call_abi(const void *self, ir_type *method_type,
1676                               be_abi_call_t *abi)
1677 {
1678         unsigned  cc;
1679         int       n, i, regnum;
1680         int                 pop_amount = 0;
1681         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
1682
1683         (void) self;
1684
1685         /* set abi flags for calls */
1686         call_flags.bits.store_args_sequential = 0;
1687         /* call_flags.bits.try_omit_fp                 not changed: can handle both settings */
1688         call_flags.bits.fp_free               = 0;  /* the frame pointer is fixed in IA32 */
1689         call_flags.bits.call_has_imm          = 0;  /* No call immediate, we handle this by ourselves */
1690
1691         /* set parameter passing style */
1692         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
1693
1694         cc = get_method_calling_convention(method_type);
1695         if (get_method_variadicity(method_type) == variadicity_variadic) {
1696                 /* pass all parameters of a variadic function on the stack */
1697                 cc = cc_cdecl_set | (cc & cc_this_call);
1698         } else {
1699                 if (get_method_additional_properties(method_type) & mtp_property_private &&
1700                     ia32_cg_config.optimize_cc) {
1701                         /* set the fast calling conventions (allowing up to 3) */
1702                         cc = SET_FASTCALL(cc) | 3;
1703                 }
1704         }
1705
1706         /* we have to pop the shadow parameter ourself for compound calls */
1707         if ( (get_method_calling_convention(method_type) & cc_compound_ret)
1708                         && !(cc & cc_reg_param)) {
1709                 pop_amount += get_mode_size_bytes(mode_P_data);
1710         }
1711
1712         n = get_method_n_params(method_type);
1713         for (i = regnum = 0; i < n; i++) {
1714                 const arch_register_t *reg  = NULL;
1715                 ir_type               *tp   = get_method_param_type(method_type, i);
1716                 ir_mode               *mode = get_type_mode(tp);
1717
1718                 if (mode != NULL) {
1719                         reg  = ia32_get_RegParam_reg(cc, regnum, mode);
1720                 }
1721                 if (reg != NULL) {
1722                         be_abi_call_param_reg(abi, i, reg, ABI_CONTEXT_BOTH);
1723                         ++regnum;
1724                 } else {
1725                         /* Micro optimisation: if the mode is shorter than 4 bytes, load 4 bytes.
1726                          * movl has a shorter opcode than mov[sz][bw]l */
1727                         ir_mode *load_mode = mode;
1728
1729                         if (mode != NULL) {
1730                                 unsigned size = get_mode_size_bytes(mode);
1731
1732                                 if (cc & cc_callee_clear_stk) {
1733                                         pop_amount += (size + 3U) & ~3U;
1734                                 }
1735
1736                                 if (size < 4) load_mode = mode_Iu;
1737                         }
1738
1739                         be_abi_call_param_stack(abi, i, load_mode, 4, 0, 0, ABI_CONTEXT_BOTH);
1740                 }
1741         }
1742
1743         be_abi_call_set_pop(abi, pop_amount);
1744
1745         /* set return registers */
1746         n = get_method_n_ress(method_type);
1747
1748         assert(n <= 2 && "more than two results not supported");
1749
1750         /* In case of 64bit returns, we will have two 32bit values */
1751         if (n == 2) {
1752                 ir_type *tp   = get_method_res_type(method_type, 0);
1753                 ir_mode *mode = get_type_mode(tp);
1754
1755                 assert(!mode_is_float(mode) && "two FP results not supported");
1756
1757                 tp   = get_method_res_type(method_type, 1);
1758                 mode = get_type_mode(tp);
1759
1760                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
1761
1762                 be_abi_call_res_reg(abi, 0, &ia32_registers[REG_EAX], ABI_CONTEXT_BOTH);
1763                 be_abi_call_res_reg(abi, 1, &ia32_registers[REG_EDX], ABI_CONTEXT_BOTH);
1764         }
1765         else if (n == 1) {
1766                 ir_type *tp   = get_method_res_type(method_type, 0);
1767                 ir_mode *mode = get_type_mode(tp);
1768                 const arch_register_t *reg;
1769                 assert(is_atomic_type(tp));
1770
1771                 reg = mode_is_float(mode) ? &ia32_registers[REG_VF0] : &ia32_registers[REG_EAX];
1772
1773                 be_abi_call_res_reg(abi, 0, reg, ABI_CONTEXT_BOTH);
1774         }
1775 }
1776
1777 /**
1778  * Returns the necessary byte alignment for storing a register of given class.
1779  */
1780 static int ia32_get_reg_class_alignment(const arch_register_class_t *cls)
1781 {
1782         ir_mode *mode = arch_register_class_mode(cls);
1783         int bytes     = get_mode_size_bytes(mode);
1784
1785         if (mode_is_float(mode) && bytes > 8)
1786                 return 16;
1787         return bytes;
1788 }
1789
1790 /**
1791  * Return irp irgs in the desired order.
1792  */
1793 static ir_graph **ia32_get_irg_list(const void *self, ir_graph ***irg_list)
1794 {
1795         (void) self;
1796         (void) irg_list;
1797         return NULL;
1798 }
1799
1800 static void ia32_mark_remat(ir_node *node)
1801 {
1802         if (is_ia32_irn(node)) {
1803                 set_ia32_is_remat(node);
1804         }
1805 }
1806
1807 /**
1808  * Check if Mux(sel, mux_true, mux_false) would represent a Max or Min operation
1809  */
1810 static bool mux_is_float_min_max(ir_node *sel, ir_node *mux_true,
1811                                  ir_node *mux_false)
1812 {
1813         ir_node    *cmp_l;
1814         ir_node    *cmp_r;
1815         ir_relation relation;
1816
1817         if (!is_Cmp(sel))
1818                 return false;
1819
1820         cmp_l = get_Cmp_left(sel);
1821         cmp_r = get_Cmp_right(sel);
1822         if (!mode_is_float(get_irn_mode(cmp_l)))
1823                 return false;
1824
1825         /* check for min/max. They're defined as (C-Semantik):
1826          *  min(a, b) = a < b ? a : b
1827          *  or min(a, b) = a <= b ? a : b
1828          *  max(a, b) = a > b ? a : b
1829          *  or max(a, b) = a >= b ? a : b
1830          * (Note we only handle float min/max here)
1831          */
1832         relation = get_Cmp_relation(sel);
1833         switch (relation) {
1834         case ir_relation_greater_equal:
1835         case ir_relation_greater:
1836                 /* this is a max */
1837                 if (cmp_l == mux_true && cmp_r == mux_false)
1838                         return true;
1839                 break;
1840         case ir_relation_less_equal:
1841         case ir_relation_less:
1842                 /* this is a min */
1843                 if (cmp_l == mux_true && cmp_r == mux_false)
1844                         return true;
1845                 break;
1846         case ir_relation_unordered_greater_equal:
1847         case ir_relation_unordered_greater:
1848                 /* this is a min */
1849                 if (cmp_l == mux_false && cmp_r == mux_true)
1850                         return true;
1851                 break;
1852         case ir_relation_unordered_less_equal:
1853         case ir_relation_unordered_less:
1854                 /* this is a max */
1855                 if (cmp_l == mux_false && cmp_r == mux_true)
1856                         return true;
1857                 break;
1858
1859         default:
1860                 break;
1861         }
1862
1863         return false;
1864 }
1865
1866 static bool mux_is_set(ir_node *sel, ir_node *mux_true, ir_node *mux_false)
1867 {
1868         ir_mode *mode = get_irn_mode(mux_true);
1869         (void) sel;
1870
1871         if (!mode_is_int(mode) && !mode_is_reference(mode)
1872                         && mode != mode_b)
1873                 return false;
1874
1875         if (is_Const(mux_true) && is_Const(mux_false)) {
1876                 /* we can create a set plus up two 3 instructions for any combination
1877                  * of constants */
1878                 return true;
1879         }
1880
1881         return false;
1882 }
1883
1884 static bool mux_is_float_const_const(ir_node *sel, ir_node *mux_true,
1885                                      ir_node *mux_false)
1886 {
1887         (void) sel;
1888
1889         if (!mode_is_float(get_irn_mode(mux_true)))
1890                 return false;
1891
1892         return is_Const(mux_true) && is_Const(mux_false);
1893 }
1894
1895 static bool mux_is_doz(ir_node *sel, ir_node *mux_true, ir_node *mux_false)
1896 {
1897         ir_node    *cmp_left;
1898         ir_node    *cmp_right;
1899         ir_node    *sub_left;
1900         ir_node    *sub_right;
1901         ir_mode    *mode;
1902         ir_relation relation;
1903
1904         if (!is_Cmp(sel))
1905                 return false;
1906
1907         mode = get_irn_mode(mux_true);
1908         if (mode_is_signed(mode) || mode_is_float(mode))
1909                 return false;
1910
1911         relation  = get_Cmp_relation(sel);
1912         cmp_left  = get_Cmp_left(sel);
1913         cmp_right = get_Cmp_right(sel);
1914
1915         /* "move" zero constant to false input */
1916         if (is_Const(mux_true) && is_Const_null(mux_true)) {
1917                 ir_node *tmp = mux_false;
1918                 mux_false = mux_true;
1919                 mux_true  = tmp;
1920                 relation = get_negated_relation(relation);
1921         }
1922         if (!is_Const(mux_false) || !is_Const_null(mux_false))
1923                 return false;
1924         if (!is_Sub(mux_true))
1925                 return false;
1926         sub_left  = get_Sub_left(mux_true);
1927         sub_right = get_Sub_right(mux_true);
1928
1929         /* Mux(a >=u b, 0, a-b) */
1930         if ((relation & ir_relation_greater)
1931                         && sub_left == cmp_left && sub_right == cmp_right)
1932                 return true;
1933         /* Mux(a <=u b, 0, b-a) */
1934         if ((relation & ir_relation_less)
1935                         && sub_left == cmp_right && sub_right == cmp_left)
1936                 return true;
1937
1938         return false;
1939 }
1940
1941 static int ia32_is_mux_allowed(ir_node *sel, ir_node *mux_false,
1942                                ir_node *mux_true)
1943 {
1944         ir_mode *mode;
1945
1946         /* middleend can handle some things */
1947         if (ir_is_optimizable_mux(sel, mux_false, mux_true))
1948                 return true;
1949         /* we can handle Set for all modes and compares */
1950         if (mux_is_set(sel, mux_true, mux_false))
1951                 return true;
1952         /* SSE has own min/max operations */
1953         if (ia32_cg_config.use_sse2
1954                         && mux_is_float_min_max(sel, mux_true, mux_false))
1955                 return true;
1956         /* we can handle Mux(?, Const[f], Const[f]) */
1957         if (mux_is_float_const_const(sel, mux_true, mux_false)) {
1958 #ifdef FIRM_GRGEN_BE
1959                 /* well, some code selectors can't handle it */
1960                 if (be_transformer != TRANSFORMER_PBQP
1961                                 || be_transformer != TRANSFORMER_RAND)
1962                         return true;
1963 #else
1964                 return true;
1965 #endif
1966         }
1967
1968         /* no support for 64bit inputs to cmov */
1969         mode = get_irn_mode(mux_true);
1970         if (get_mode_size_bits(mode) > 32)
1971                 return false;
1972         /* we can handle Abs for all modes and compares (except 64bit) */
1973         if (ir_mux_is_abs(sel, mux_false, mux_true) != 0)
1974                 return true;
1975         /* we can't handle MuxF yet */
1976         if (mode_is_float(mode))
1977                 return false;
1978
1979         if (mux_is_doz(sel, mux_true, mux_false))
1980                 return true;
1981
1982         /* Check Cmp before the node */
1983         if (is_Cmp(sel)) {
1984                 ir_mode *cmp_mode = get_irn_mode(get_Cmp_left(sel));
1985
1986                 /* we can't handle 64bit compares */
1987                 if (get_mode_size_bits(cmp_mode) > 32)
1988                         return false;
1989
1990                 /* we can't handle float compares */
1991                 if (mode_is_float(cmp_mode))
1992                         return false;
1993         }
1994
1995         /* did we disable cmov generation? */
1996         if (!ia32_cg_config.use_cmov)
1997                 return false;
1998
1999         /* we can use a cmov */
2000         return true;
2001 }
2002
2003 static asm_constraint_flags_t ia32_parse_asm_constraint(const char **c)
2004 {
2005         (void) c;
2006
2007         /* we already added all our simple flags to the flags modifier list in
2008          * init, so this flag we don't know. */
2009         return ASM_CONSTRAINT_FLAG_INVALID;
2010 }
2011
2012 static int ia32_is_valid_clobber(const char *clobber)
2013 {
2014         return ia32_get_clobber_register(clobber) != NULL;
2015 }
2016
2017 static ir_node *ia32_create_set(ir_node *cond)
2018 {
2019         ir_node  *block = get_nodes_block(cond);
2020         ir_node  *set   = new_bd_ia32_l_Setcc(NULL, block, cond);
2021         ir_node  *conv  = new_r_Conv(block, set, mode_Iu);
2022         return conv;
2023 }
2024
2025 static void ia32_lower_for_target(void)
2026 {
2027         size_t i, n_irgs = get_irp_n_irgs();
2028         lower_mode_b_config_t lower_mode_b_config = {
2029                 mode_Iu,  /* lowered mode */
2030                 ia32_create_set,
2031         };
2032
2033         /* perform doubleword lowering */
2034         lwrdw_param_t lower_dw_params = {
2035                 1,  /* little endian */
2036                 64, /* doubleword size */
2037                 ia32_create_intrinsic_fkt,
2038                 &intrinsic_env,
2039         };
2040
2041         ia32_create_opcodes(&ia32_irn_ops);
2042
2043         /* lower compound param handling
2044          * Note: we lower compound arguments ourself, since on ia32 we don't
2045          * have hidden parameters but know where to find the structs on the stack.
2046          * (This also forces us to always allocate space for the compound arguments
2047          *  on the callframe and we can't just use an arbitrary position on the
2048          *  stackframe)
2049          */
2050         lower_calls_with_compounds(LF_RETURN_HIDDEN | LF_DONT_LOWER_ARGUMENTS);
2051
2052         /* replace floating point operations by function calls */
2053         if (ia32_cg_config.use_softfloat) {
2054                 lower_floating_point();
2055         }
2056
2057         ir_prepare_dw_lowering(&lower_dw_params);
2058         ir_lower_dw_ops();
2059
2060         for (i = 0; i < n_irgs; ++i) {
2061                 ir_graph *irg = get_irp_irg(i);
2062                 /* lower for mode_b stuff */
2063                 ir_lower_mode_b(irg, &lower_mode_b_config);
2064                 /* break up switches with wide ranges */
2065                 lower_switch(irg, 4, 256, false);
2066         }
2067
2068         for (i = 0; i < n_irgs; ++i) {
2069                 ir_graph *irg = get_irp_irg(i);
2070                 /* Turn all small CopyBs into loads/stores, keep medium-sized CopyBs,
2071                  * so we can generate rep movs later, and turn all big CopyBs into
2072                  * memcpy calls. */
2073                 lower_CopyB(irg, 64, 8193, true);
2074         }
2075 }
2076
2077 /**
2078  * Create the trampoline code.
2079  */
2080 static ir_node *ia32_create_trampoline_fkt(ir_node *block, ir_node *mem, ir_node *trampoline, ir_node *env, ir_node *callee)
2081 {
2082         ir_graph *const irg  = get_irn_irg(block);
2083         ir_node  *      p    = trampoline;
2084         ir_mode  *const mode = get_irn_mode(p);
2085         ir_node  *const one  = new_r_Const(irg, get_mode_one(mode_Iu));
2086         ir_node  *const four = new_r_Const_long(irg, mode_Iu, 4);
2087         ir_node  *      st;
2088
2089         /* mov  ecx,<env> */
2090         st  = new_r_Store(block, mem, p, new_r_Const_long(irg, mode_Bu, 0xb9), cons_none);
2091         mem = new_r_Proj(st, mode_M, pn_Store_M);
2092         p   = new_r_Add(block, p, one, mode);
2093         st  = new_r_Store(block, mem, p, env, cons_none);
2094         mem = new_r_Proj(st, mode_M, pn_Store_M);
2095         p   = new_r_Add(block, p, four, mode);
2096         /* jmp  <callee> */
2097         st  = new_r_Store(block, mem, p, new_r_Const_long(irg, mode_Bu, 0xe9), cons_none);
2098         mem = new_r_Proj(st, mode_M, pn_Store_M);
2099         p   = new_r_Add(block, p, one, mode);
2100         st  = new_r_Store(block, mem, p, callee, cons_none);
2101         mem = new_r_Proj(st, mode_M, pn_Store_M);
2102         p   = new_r_Add(block, p, four, mode);
2103
2104         return mem;
2105 }
2106
2107 /**
2108  * Returns the libFirm configuration parameter for this backend.
2109  */
2110 static const backend_params *ia32_get_libfirm_params(void)
2111 {
2112         static const ir_settings_arch_dep_t ad = {
2113                 1,                   /* also use subs */
2114                 4,                   /* maximum shifts */
2115                 63,                  /* maximum shift amount */
2116                 ia32_evaluate_insn,  /* evaluate the instruction sequence */
2117
2118                 1,  /* allow Mulhs */
2119                 1,  /* allow Mulus */
2120                 32, /* Mulh allowed up to 32 bit */
2121         };
2122         static backend_params p = {
2123                 1,     /* support inline assembly */
2124                 1,     /* support Rotl nodes */
2125                 0,     /* little endian */
2126                 1,     /* modulo shift efficient */
2127                 0,     /* non-modulo shift not efficient */
2128                 &ad,   /* will be set later */
2129                 ia32_is_mux_allowed,
2130                 32,    /* machine_size */
2131                 NULL,  /* float arithmetic mode, will be set below */
2132                 NULL,  /* long long type */
2133                 NULL,  /* unsigned long long type */
2134                 NULL,  /* long double type */
2135                 12,    /* size of trampoline code */
2136                 4,     /* alignment of trampoline code */
2137                 ia32_create_trampoline_fkt,
2138                 4      /* alignment of stack parameter */
2139         };
2140         ir_mode *mode_long_long
2141                 = new_ir_mode("long long", irms_int_number, 64, 1, irma_twos_complement,
2142                               64);
2143         ir_type *type_long_long = new_type_primitive(mode_long_long);
2144         ir_mode *mode_unsigned_long_long
2145                 = new_ir_mode("unsigned long long", irms_int_number, 64, 0,
2146                               irma_twos_complement, 64);
2147         ir_type *type_unsigned_long_long
2148                 = new_type_primitive(mode_unsigned_long_long);
2149
2150         ia32_setup_cg_config();
2151
2152         /* doesn't really belong here, but this is the earliest place the backend
2153          * is called... */
2154         init_asm_constraints();
2155
2156         p.type_long_long          = type_long_long;
2157         p.type_unsigned_long_long = type_unsigned_long_long;
2158
2159         if (ia32_cg_config.use_sse2 || ia32_cg_config.use_softfloat) {
2160                 p.mode_float_arithmetic = NULL;
2161                 p.type_long_double = NULL;
2162         } else {
2163                 p.mode_float_arithmetic = mode_E;
2164                 ir_mode *mode = new_ir_mode("long double", irms_float_number, 80, 1,
2165                                             irma_ieee754, 0);
2166                 ir_type *type = new_type_primitive(mode);
2167                 set_type_size_bytes(type, 12);
2168                 set_type_alignment_bytes(type, 4);
2169                 p.type_long_double = type;
2170         }
2171         return &p;
2172 }
2173
2174 /**
2175  * Check if the given register is callee or caller save.
2176  */
2177 static int ia32_register_saved_by(const arch_register_t *reg, int callee)
2178 {
2179         if (callee) {
2180                 /* check for callee saved */
2181                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_gp]) {
2182                         switch (reg->index) {
2183                         case REG_GP_EBX:
2184                         case REG_GP_ESI:
2185                         case REG_GP_EDI:
2186                         case REG_GP_EBP:
2187                                 return 1;
2188                         default:
2189                                 return 0;
2190                         }
2191                 }
2192         } else {
2193                 /* check for caller saved */
2194                 if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_gp]) {
2195                         switch (reg->index) {
2196                         case REG_GP_EDX:
2197                         case REG_GP_ECX:
2198                         case REG_GP_EAX:
2199                                 return 1;
2200                         default:
2201                                 return 0;
2202                         }
2203                 } else if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_xmm]) {
2204                         /* all XMM registers are caller save */
2205                         return reg->index != REG_XMM_NOREG;
2206                 } else if (reg->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]) {
2207                         /* all VFP registers are caller save */
2208                         return reg->index != REG_VFP_NOREG;
2209                 }
2210         }
2211         return 0;
2212 }
2213
2214 static const lc_opt_enum_int_items_t gas_items[] = {
2215         { "elf",   OBJECT_FILE_FORMAT_ELF    },
2216         { "mingw", OBJECT_FILE_FORMAT_COFF   },
2217         { "macho", OBJECT_FILE_FORMAT_MACH_O },
2218         { NULL,    0 }
2219 };
2220
2221 static lc_opt_enum_int_var_t gas_var = {
2222         (int*) &be_gas_object_file_format, gas_items
2223 };
2224
2225 #ifdef FIRM_GRGEN_BE
2226 static const lc_opt_enum_int_items_t transformer_items[] = {
2227         { "default", TRANSFORMER_DEFAULT },
2228         { "pbqp",    TRANSFORMER_PBQP    },
2229         { "random",  TRANSFORMER_RAND    },
2230         { NULL,      0                   }
2231 };
2232
2233 static lc_opt_enum_int_var_t transformer_var = {
2234         (int*)&be_transformer, transformer_items
2235 };
2236 #endif
2237
2238 static const lc_opt_table_entry_t ia32_options[] = {
2239         LC_OPT_ENT_ENUM_INT("gasmode", "set the GAS compatibility mode", &gas_var),
2240 #ifdef FIRM_GRGEN_BE
2241         LC_OPT_ENT_ENUM_INT("transformer", "the transformer used for code selection", &transformer_var),
2242 #endif
2243         LC_OPT_ENT_INT ("stackalign", "set power of two stack alignment for calls",
2244                         &ia32_isa_template.base.stack_alignment),
2245         LC_OPT_ENT_BOOL("gprof",      "create gprof profiling code",                                    &gprof),
2246         LC_OPT_LAST
2247 };
2248
2249 const arch_isa_if_t ia32_isa_if = {
2250         ia32_init,
2251         ia32_lower_for_target,
2252         ia32_done,
2253         ia32_handle_intrinsics,
2254         ia32_get_reg_class_for_mode,
2255         ia32_get_call_abi,
2256         ia32_get_reg_class_alignment,
2257         ia32_get_libfirm_params,
2258         ia32_get_irg_list,
2259         ia32_mark_remat,
2260         ia32_parse_asm_constraint,
2261         ia32_is_valid_clobber,
2262
2263         ia32_init_graph,
2264         ia32_get_pic_base,   /* return node used as base in pic code addresses */
2265         ia32_before_abi,     /* before abi introduce hook */
2266         ia32_prepare_graph,
2267         ia32_before_ra,      /* before register allocation hook */
2268         ia32_finish,         /* called before codegen */
2269         ia32_emit,           /* emit && done */
2270         ia32_register_saved_by,
2271         be_new_spill,
2272         be_new_reload
2273 };
2274
2275 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_ia32)
2276 void be_init_arch_ia32(void)
2277 {
2278         lc_opt_entry_t *be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2279         lc_opt_entry_t *ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2280
2281         lc_opt_add_table(ia32_grp, ia32_options);
2282         be_register_isa_if("ia32", &ia32_isa_if);
2283
2284         ia32_init_emitter();
2285         ia32_init_finish();
2286         ia32_init_optimize();
2287         ia32_init_transform();
2288         ia32_init_x87();
2289         ia32_init_architecture();
2290 }