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