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