make testapp deterministic
[libfirm] / ir / be / ia32 / bearch_ia32.c
1 /**
2  * This is the main ia32 firm backend driver.
3  * @author Christian Wuerdig
4  * $Id$
5  */
6
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #ifdef HAVE_MALLOC_H
12 #include <malloc.h>
13 #endif
14
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18
19 #ifdef WITH_LIBCORE
20 #include <libcore/lc_opts.h>
21 #include <libcore/lc_opts_enum.h>
22 #endif /* WITH_LIBCORE */
23
24 #include <math.h>
25
26 #include "pseudo_irg.h"
27 #include "irgwalk.h"
28 #include "irprog.h"
29 #include "irprintf.h"
30 #include "iredges_t.h"
31 #include "ircons.h"
32 #include "irgmod.h"
33 #include "irgopt.h"
34 #include "irbitset.h"
35 #include "pdeq.h"
36 #include "pset.h"
37 #include "debug.h"
38
39 #include "../beabi.h"                 /* the general register allocator interface */
40 #include "../benode_t.h"
41 #include "../belower.h"
42 #include "../besched_t.h"
43 #include "../be.h"
44 #include "../be_t.h"
45 #include "../beirgmod.h"
46 #include "../be_dbgout.h"
47 #include "../beblocksched.h"
48 #include "../bemachine.h"
49 #include "../beilpsched.h"
50 #include "../bespillslots.h"
51 #include "../bemodule.h"
52
53 #include "bearch_ia32_t.h"
54
55 #include "ia32_new_nodes.h"           /* ia32 nodes interface */
56 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
57 #include "gen_ia32_machine.h"
58 #include "ia32_gen_decls.h"           /* interface declaration emitter */
59 #include "ia32_transform.h"
60 #include "ia32_emitter.h"
61 #include "ia32_map_regs.h"
62 #include "ia32_optimize.h"
63 #include "ia32_x87.h"
64 #include "ia32_dbg_stat.h"
65 #include "ia32_finish.h"
66 #include "ia32_util.h"
67
68 #define DEBUG_MODULE "firm.be.ia32.isa"
69
70 /* TODO: ugly */
71 static set *cur_reg_set = NULL;
72
73 typedef ir_node *(*create_const_node_func) (dbg_info *dbg, ir_graph *irg, ir_node *block);
74
75 static INLINE ir_node *create_const(ia32_code_gen_t *cg, ir_node **place,
76                                     create_const_node_func func, arch_register_t* reg)
77 {
78         ir_node *block, *res;
79         ir_node *startnode;
80
81         if(*place != NULL)
82                 return *place;
83
84         block = get_irg_start_block(cg->irg);
85         res = func(NULL, cg->irg, block);
86         arch_set_irn_register(cg->arch_env, res, reg);
87         *place = res;
88
89         startnode = get_irg_start(cg->irg);
90         if(sched_is_scheduled(startnode)) {
91                 sched_add_before(startnode, res);
92         }
93
94         return res;
95 }
96
97 /* Creates the unique per irg GP NoReg node. */
98 ir_node *ia32_new_NoReg_gp(ia32_code_gen_t *cg) {
99         return create_const(cg, &cg->noreg_gp, new_rd_ia32_NoReg_GP,
100                             &ia32_gp_regs[REG_GP_NOREG]);
101 }
102
103 ir_node *ia32_new_NoReg_vfp(ia32_code_gen_t *cg) {
104         return create_const(cg, &cg->noreg_vfp, new_rd_ia32_NoReg_VFP,
105                             &ia32_vfp_regs[REG_VFP_NOREG]);
106 }
107
108 ir_node *ia32_new_NoReg_xmm(ia32_code_gen_t *cg) {
109         return create_const(cg, &cg->noreg_xmm, new_rd_ia32_NoReg_XMM,
110                             &ia32_xmm_regs[REG_XMM_NOREG]);
111 }
112
113 /* Creates the unique per irg FP NoReg node. */
114 ir_node *ia32_new_NoReg_fp(ia32_code_gen_t *cg) {
115         return USE_SSE2(cg) ? ia32_new_NoReg_xmm(cg) : ia32_new_NoReg_vfp(cg);
116 }
117
118 ir_node *ia32_new_Unknown_gp(ia32_code_gen_t *cg) {
119         return create_const(cg, &cg->unknown_gp, new_rd_ia32_Unknown_GP,
120                             &ia32_gp_regs[REG_GP_UKNWN]);
121 }
122
123 ir_node *ia32_new_Unknown_vfp(ia32_code_gen_t *cg) {
124         return create_const(cg, &cg->unknown_vfp, new_rd_ia32_Unknown_VFP,
125                             &ia32_vfp_regs[REG_VFP_UKNWN]);
126 }
127
128 ir_node *ia32_new_Unknown_xmm(ia32_code_gen_t *cg) {
129         return create_const(cg, &cg->unknown_xmm, new_rd_ia32_Unknown_XMM,
130                             &ia32_xmm_regs[REG_XMM_UKNWN]);
131 }
132
133
134 /**
135  * Returns gp_noreg or fp_noreg, depending in input requirements.
136  */
137 ir_node *ia32_get_admissible_noreg(ia32_code_gen_t *cg, ir_node *irn, int pos) {
138         arch_register_req_t       req;
139         const arch_register_req_t *p_req;
140
141         p_req = arch_get_register_req(cg->arch_env, &req, irn, pos);
142         assert(p_req && "Missing register requirements");
143         if (p_req->cls == &ia32_reg_classes[CLASS_ia32_gp])
144                 return ia32_new_NoReg_gp(cg);
145         else
146                 return ia32_new_NoReg_fp(cg);
147 }
148
149 /**************************************************
150  *                         _ _              _  __
151  *                        | | |            (_)/ _|
152  *  _ __ ___  __ _    __ _| | | ___   ___   _| |_
153  * | '__/ _ \/ _` |  / _` | | |/ _ \ / __| | |  _|
154  * | | |  __/ (_| | | (_| | | | (_) | (__  | | |
155  * |_|  \___|\__, |  \__,_|_|_|\___/ \___| |_|_|
156  *            __/ |
157  *           |___/
158  **************************************************/
159
160 /**
161  * Return register requirements for an ia32 node.
162  * If the node returns a tuple (mode_T) then the proj's
163  * will be asked for this information.
164  */
165 static const arch_register_req_t *ia32_get_irn_reg_req(const void *self, arch_register_req_t *req, const ir_node *irn, int pos) {
166         const ia32_irn_ops_t      *ops = self;
167         const ia32_register_req_t *irn_req;
168         long                       node_pos = pos == -1 ? 0 : pos;
169         ir_mode                   *mode     = is_Block(irn) ? NULL : get_irn_mode(irn);
170         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, DEBUG_MODULE);
171
172         if (is_Block(irn) || mode == mode_X) {
173                 DBG((mod, LEVEL_1, "ignoring Block, mode_M, mode_X node %+F\n", irn));
174                 return NULL;
175         }
176
177         if (mode == mode_T && pos < 0) {
178                 DBG((mod, LEVEL_1, "ignoring request OUT requirements for node %+F\n", irn));
179                 return NULL;
180         }
181
182         DBG((mod, LEVEL_1, "get requirements at pos %d for %+F ... ", pos, irn));
183
184         if (is_Proj(irn)) {
185                 if(mode == mode_M)
186                         return NULL;
187
188                 if(pos >= 0) {
189                         DBG((mod, LEVEL_1, "ignoring request IN requirements for node %+F\n", irn));
190                         return NULL;
191                 }
192
193                 node_pos = (pos == -1) ? get_Proj_proj(irn) : pos;
194                 irn      = skip_Proj_const(irn);
195
196                 DB((mod, LEVEL_1, "skipping Proj, going to %+F at pos %d ... ", irn, node_pos));
197         }
198
199         if (is_ia32_irn(irn)) {
200                 irn_req = (pos >= 0) ? get_ia32_in_req(irn, pos) : get_ia32_out_req(irn, node_pos);
201                 if (irn_req == NULL) {
202                         /* no requirements */
203                         return NULL;
204                 }
205
206                 DB((mod, LEVEL_1, "returning reqs for %+F at pos %d\n", irn, pos));
207
208                 memcpy(req, &(irn_req->req), sizeof(*req));
209
210                 if (arch_register_req_is(&(irn_req->req), should_be_same)) {
211                         assert(irn_req->same_pos >= 0 && "should be same constraint for in -> out NYI");
212                         req->other_same = get_irn_n(irn, irn_req->same_pos);
213                 }
214
215                 if (arch_register_req_is(&(irn_req->req), should_be_different)) {
216                         assert(irn_req->different_pos >= 0 && "should be different constraint for in -> out NYI");
217                         req->other_different = get_irn_n(irn, irn_req->different_pos);
218                 }
219         }
220         else {
221                 /* treat Unknowns like Const with default requirements */
222                 if (is_Unknown(irn)) {
223                         DB((mod, LEVEL_1, "returning UKNWN reqs for %+F\n", irn));
224                         if (mode_is_float(mode)) {
225                                 if (USE_SSE2(ops->cg))
226                                         memcpy(req, &(ia32_default_req_ia32_xmm_xmm_UKNWN), sizeof(*req));
227                                 else
228                                         memcpy(req, &(ia32_default_req_ia32_vfp_vfp_UKNWN), sizeof(*req));
229                         }
230                         else if (mode_is_int(mode) || mode_is_reference(mode))
231                                 memcpy(req, &(ia32_default_req_ia32_gp_gp_UKNWN), sizeof(*req));
232                         else if (mode == mode_T || mode == mode_M) {
233                                 DBG((mod, LEVEL_1, "ignoring Unknown node %+F\n", irn));
234                                 return NULL;
235                         }
236                         else
237                                 assert(0 && "unsupported Unknown-Mode");
238                 }
239                 else {
240                         DB((mod, LEVEL_1, "returning NULL for %+F (not ia32)\n", irn));
241                         req = NULL;
242                 }
243         }
244
245         return req;
246 }
247
248 static void ia32_set_irn_reg(const void *self, ir_node *irn, const arch_register_t *reg) {
249         int                   pos = 0;
250         const ia32_irn_ops_t *ops = self;
251
252         if (get_irn_mode(irn) == mode_X) {
253                 return;
254         }
255
256         DBG((ops->cg->mod, LEVEL_1, "ia32 assigned register %s to node %+F\n", reg->name, irn));
257
258         if (is_Proj(irn)) {
259                 pos = get_Proj_proj(irn);
260                 irn = skip_Proj(irn);
261         }
262
263         if (is_ia32_irn(irn)) {
264                 const arch_register_t **slots;
265
266                 slots      = get_ia32_slots(irn);
267                 slots[pos] = reg;
268         }
269         else {
270                 ia32_set_firm_reg(irn, reg, cur_reg_set);
271         }
272 }
273
274 static const arch_register_t *ia32_get_irn_reg(const void *self, const ir_node *irn) {
275         int pos = 0;
276         const arch_register_t *reg = NULL;
277
278         if (is_Proj(irn)) {
279
280                 if (get_irn_mode(irn) == mode_X) {
281                         return NULL;
282                 }
283
284                 pos = get_Proj_proj(irn);
285                 irn = skip_Proj_const(irn);
286         }
287
288         if (is_ia32_irn(irn)) {
289                 const arch_register_t **slots;
290                 slots = get_ia32_slots(irn);
291                 reg   = slots[pos];
292         }
293         else {
294                 reg = ia32_get_firm_reg(irn, cur_reg_set);
295         }
296
297         return reg;
298 }
299
300 static arch_irn_class_t ia32_classify(const void *self, const ir_node *irn) {
301         arch_irn_class_t classification = arch_irn_class_normal;
302
303         irn = skip_Proj_const(irn);
304
305         if (is_cfop(irn))
306                 classification |= arch_irn_class_branch;
307
308         if (! is_ia32_irn(irn))
309                 return classification & ~arch_irn_class_normal;
310
311         if (is_ia32_Cnst(irn))
312                 classification |= arch_irn_class_const;
313
314         if (is_ia32_Ld(irn))
315                 classification |= arch_irn_class_load;
316
317         if (is_ia32_St(irn) || is_ia32_Store8Bit(irn))
318                 classification |= arch_irn_class_store;
319
320         if (is_ia32_got_reload(irn))
321                 classification |= arch_irn_class_reload;
322
323         return classification;
324 }
325
326 static arch_irn_flags_t ia32_get_flags(const void *self, const ir_node *irn) {
327         arch_irn_flags_t flags = arch_irn_flags_none;
328
329         if (is_Unknown(irn))
330                 return arch_irn_flags_ignore;
331
332         if(is_Proj(irn) && mode_is_datab(get_irn_mode(irn))) {
333                 ir_node *pred = get_Proj_pred(irn);
334
335                 if(is_ia32_irn(pred)) {
336                         flags = get_ia32_out_flags(pred, get_Proj_proj(irn));
337                 }
338
339                 irn = pred;
340         }
341
342         if (is_ia32_irn(irn)) {
343                 flags |= get_ia32_flags(irn);
344         }
345
346         return flags;
347 }
348
349 /**
350  * The IA32 ABI callback object.
351  */
352 typedef struct {
353         be_abi_call_flags_bits_t flags;  /**< The call flags. */
354         const arch_isa_t *isa;           /**< The ISA handle. */
355         const arch_env_t *aenv;          /**< The architecture environment. */
356         ir_graph *irg;                   /**< The associated graph. */
357 } ia32_abi_env_t;
358
359 static ir_entity *ia32_get_frame_entity(const void *self, const ir_node *irn) {
360         return is_ia32_irn(irn) ? get_ia32_frame_ent(irn) : NULL;
361 }
362
363 static void ia32_set_frame_entity(const void *self, ir_node *irn, ir_entity *ent) {
364         set_ia32_frame_ent(irn, ent);
365 }
366
367 static void ia32_set_frame_offset(const void *self, ir_node *irn, int bias) {
368         const ia32_irn_ops_t *ops = self;
369
370         if (get_ia32_frame_ent(irn)) {
371                 if(is_ia32_Pop(irn)) {
372                         int omit_fp = be_abi_omit_fp(ops->cg->birg->abi);
373                         if (omit_fp) {
374                                 /* Pop nodes modify the stack pointer before calculating the destination
375                                  * address, so fix this here
376                                  */
377                                 bias -= 4;
378                         }
379                 }
380
381                 DBG((ops->cg->mod, LEVEL_1, "stack biased %+F with %d\n", irn, bias));
382
383                 ia32_am_flavour_t am_flav = get_ia32_am_flavour(irn);
384                 am_flav |= ia32_O;
385                 set_ia32_am_flavour(irn, am_flav);
386
387                 add_ia32_am_offs_int(irn, bias);
388         }
389 }
390
391 static int ia32_get_sp_bias(const void *self, const ir_node *irn) {
392         if(is_Proj(irn)) {
393                 long proj = get_Proj_proj(irn);
394                 ir_node *pred = get_Proj_pred(irn);
395
396                 if (is_ia32_Push(pred) && proj == pn_ia32_Push_stack)
397                         return 4;
398                 if (is_ia32_Pop(pred) && proj == pn_ia32_Pop_stack)
399                         return -4;
400         }
401
402         return 0;
403 }
404
405 /**
406  * Put all registers which are saved by the prologue/epilogue in a set.
407  *
408  * @param self  The callback object.
409  * @param s     The result set.
410  */
411 static void ia32_abi_dont_save_regs(void *self, pset *s)
412 {
413         ia32_abi_env_t *env = self;
414         if(env->flags.try_omit_fp)
415                 pset_insert_ptr(s, env->isa->bp);
416 }
417
418 /**
419  * Generate the routine prologue.
420  *
421  * @param self    The callback object.
422  * @param mem     A pointer to the mem node. Update this if you define new memory.
423  * @param reg_map A map mapping all callee_save/ignore/parameter registers to their defining nodes.
424  *
425  * @return        The register which shall be used as a stack frame base.
426  *
427  * All nodes which define registers in @p reg_map must keep @p reg_map current.
428  */
429 static const arch_register_t *ia32_abi_prologue(void *self, ir_node **mem, pmap *reg_map)
430 {
431         ia32_abi_env_t *env = self;
432         const ia32_isa_t *isa     = (ia32_isa_t *)env->isa;
433         ia32_code_gen_t *cg = isa->cg;
434
435         if (! env->flags.try_omit_fp) {
436                 ir_node *bl      = get_irg_start_block(env->irg);
437                 ir_node *curr_sp = be_abi_reg_map_get(reg_map, env->isa->sp);
438                 ir_node *curr_bp = be_abi_reg_map_get(reg_map, env->isa->bp);
439                 ir_node *noreg = ia32_new_NoReg_gp(cg);
440                 ir_node *push;
441
442                 /* push ebp */
443                 push    = new_rd_ia32_Push(NULL, env->irg, bl, noreg, noreg, curr_bp, curr_sp, *mem);
444                 curr_sp = new_r_Proj(env->irg, bl, push, get_irn_mode(curr_sp), pn_ia32_Push_stack);
445                 *mem    = new_r_Proj(env->irg, bl, push, mode_M, pn_ia32_Push_M);
446
447                 /* the push must have SP out register */
448                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
449                 set_ia32_flags(push, arch_irn_flags_ignore);
450
451                 /* move esp to ebp */
452                 curr_bp  = be_new_Copy(env->isa->bp->reg_class, env->irg, bl, curr_sp);
453                 be_set_constr_single_reg(curr_bp, BE_OUT_POS(0), env->isa->bp);
454                 arch_set_irn_register(env->aenv, curr_bp, env->isa->bp);
455                 be_node_set_flags(curr_bp, BE_OUT_POS(0), arch_irn_flags_ignore);
456
457                 /* beware: the copy must be done before any other sp use */
458                 curr_sp = be_new_CopyKeep_single(env->isa->sp->reg_class, env->irg, bl, curr_sp, curr_bp, get_irn_mode(curr_sp));
459                 be_set_constr_single_reg(curr_sp, BE_OUT_POS(0), env->isa->sp);
460                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
461                 be_node_set_flags(curr_sp, BE_OUT_POS(0), arch_irn_flags_ignore);
462
463                 be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
464                 be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
465
466                 return env->isa->bp;
467         }
468
469         return env->isa->sp;
470 }
471
472 /**
473  * Generate the routine epilogue.
474  * @param self    The callback object.
475  * @param bl      The block for the epilog
476  * @param mem     A pointer to the mem node. Update this if you define new memory.
477  * @param reg_map A map mapping all callee_save/ignore/parameter registers to their defining nodes.
478  * @return        The register which shall be used as a stack frame base.
479  *
480  * All nodes which define registers in @p reg_map must keep @p reg_map current.
481  */
482 static void ia32_abi_epilogue(void *self, ir_node *bl, ir_node **mem, pmap *reg_map)
483 {
484         ia32_abi_env_t *env     = self;
485         ir_node        *curr_sp = be_abi_reg_map_get(reg_map, env->isa->sp);
486         ir_node        *curr_bp = be_abi_reg_map_get(reg_map, env->isa->bp);
487
488         if (env->flags.try_omit_fp) {
489                 /* simply remove the stack frame here */
490                 curr_sp = be_new_IncSP(env->isa->sp, env->irg, bl, curr_sp, BE_STACK_FRAME_SIZE_SHRINK);
491                 add_irn_dep(curr_sp, *mem);
492         } else {
493                 const ia32_isa_t *isa     = (ia32_isa_t *)env->isa;
494                 ia32_code_gen_t *cg = isa->cg;
495                 ir_mode          *mode_bp = env->isa->bp->reg_class->mode;
496
497                 /* gcc always emits a leave at the end of a routine */
498                 if (1 || ARCH_AMD(isa->opt_arch)) {
499                         ir_node *leave;
500
501                         /* leave */
502                         leave   = new_rd_ia32_Leave(NULL, env->irg, bl, curr_sp, curr_bp);
503                         set_ia32_flags(leave, arch_irn_flags_ignore);
504                         curr_bp = new_r_Proj(current_ir_graph, bl, leave, mode_bp, pn_ia32_Leave_frame);
505                         curr_sp = new_r_Proj(current_ir_graph, bl, leave, get_irn_mode(curr_sp), pn_ia32_Leave_stack);
506                 } else {
507                         ir_node *noreg = ia32_new_NoReg_gp(cg);
508                         ir_node *pop;
509
510                         /* copy ebp to esp */
511                         curr_sp = be_new_SetSP(env->isa->sp, env->irg, bl, curr_sp, curr_bp, *mem);
512
513                         /* pop ebp */
514                         pop     = new_rd_ia32_Pop(NULL, env->irg, bl, noreg, noreg, curr_sp, *mem);
515                         set_ia32_flags(pop, arch_irn_flags_ignore);
516                         curr_bp = new_r_Proj(current_ir_graph, bl, pop, mode_bp, pn_ia32_Pop_res);
517                         curr_sp = new_r_Proj(current_ir_graph, bl, pop, get_irn_mode(curr_sp), pn_ia32_Pop_stack);
518
519                         *mem = new_r_Proj(current_ir_graph, bl, pop, mode_M, pn_ia32_Pop_M);
520                 }
521                 arch_set_irn_register(env->aenv, curr_sp, env->isa->sp);
522                 arch_set_irn_register(env->aenv, curr_bp, env->isa->bp);
523         }
524
525         be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
526         be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
527 }
528
529 /**
530  * Initialize the callback object.
531  * @param call The call object.
532  * @param aenv The architecture environment.
533  * @param irg  The graph with the method.
534  * @return     Some pointer. This pointer is passed to all other callback functions as self object.
535  */
536 static void *ia32_abi_init(const be_abi_call_t *call, const arch_env_t *aenv, ir_graph *irg)
537 {
538         ia32_abi_env_t *env    = xmalloc(sizeof(env[0]));
539         be_abi_call_flags_t fl = be_abi_call_get_flags(call);
540         env->flags = fl.bits;
541         env->irg   = irg;
542         env->aenv  = aenv;
543         env->isa   = aenv->isa;
544         return env;
545 }
546
547 /**
548  * Destroy the callback object.
549  * @param self The callback object.
550  */
551 static void ia32_abi_done(void *self) {
552         free(self);
553 }
554
555 /**
556  * Produces the type which sits between the stack args and the locals on the stack.
557  * it will contain the return address and space to store the old base pointer.
558  * @return The Firm type modeling the ABI between type.
559  */
560 static ir_type *ia32_abi_get_between_type(void *self)
561 {
562 #define IDENT(s) new_id_from_chars(s, sizeof(s)-1)
563         static ir_type *omit_fp_between_type = NULL;
564         static ir_type *between_type         = NULL;
565
566         ia32_abi_env_t *env = self;
567
568         if (! between_type) {
569                 ir_entity *old_bp_ent;
570                 ir_entity *ret_addr_ent;
571                 ir_entity *omit_fp_ret_addr_ent;
572
573                 ir_type *old_bp_type   = new_type_primitive(IDENT("bp"), mode_Iu);
574                 ir_type *ret_addr_type = new_type_primitive(IDENT("return_addr"), mode_Iu);
575
576                 between_type           = new_type_struct(IDENT("ia32_between_type"));
577                 old_bp_ent             = new_entity(between_type, IDENT("old_bp"), old_bp_type);
578                 ret_addr_ent           = new_entity(between_type, IDENT("ret_addr"), ret_addr_type);
579
580                 set_entity_offset(old_bp_ent, 0);
581                 set_entity_offset(ret_addr_ent, get_type_size_bytes(old_bp_type));
582                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
583                 set_type_state(between_type, layout_fixed);
584
585                 omit_fp_between_type = new_type_struct(IDENT("ia32_between_type_omit_fp"));
586                 omit_fp_ret_addr_ent = new_entity(omit_fp_between_type, IDENT("ret_addr"), ret_addr_type);
587
588                 set_entity_offset(omit_fp_ret_addr_ent, 0);
589                 set_type_size_bytes(omit_fp_between_type, get_type_size_bytes(ret_addr_type));
590                 set_type_state(omit_fp_between_type, layout_fixed);
591         }
592
593         return env->flags.try_omit_fp ? omit_fp_between_type : between_type;
594 #undef IDENT
595 }
596
597 /**
598  * Get the estimated cycle count for @p irn.
599  *
600  * @param self The this pointer.
601  * @param irn  The node.
602  *
603  * @return     The estimated cycle count for this operation
604  */
605 static int ia32_get_op_estimated_cost(const void *self, const ir_node *irn)
606 {
607         int cost;
608         ia32_op_type_t op_tp;
609         const ia32_irn_ops_t *ops = self;
610
611         if (is_Proj(irn))
612                 return 0;
613         if (!is_ia32_irn(irn))
614                 return 0;
615
616         assert(is_ia32_irn(irn));
617
618         cost  = get_ia32_latency(irn);
619         op_tp = get_ia32_op_type(irn);
620
621         if (is_ia32_CopyB(irn)) {
622                 cost = 250;
623                 if (ARCH_INTEL(ops->cg->arch))
624                         cost += 150;
625         }
626         else if (is_ia32_CopyB_i(irn)) {
627                 int size = get_tarval_long(get_ia32_Immop_tarval(irn));
628                 cost     = 20 + (int)ceil((4/3) * size);
629                 if (ARCH_INTEL(ops->cg->arch))
630                         cost += 150;
631         }
632         /* in case of address mode operations add additional cycles */
633         else if (op_tp == ia32_AddrModeD || op_tp == ia32_AddrModeS) {
634                 /*
635                         In case of stack access add 5 cycles (we assume stack is in cache),
636                         other memory operations cost 20 cycles.
637                 */
638                 cost += is_ia32_use_frame(irn) ? 5 : 20;
639         }
640
641         return cost;
642 }
643
644 /**
645  * Returns the inverse operation if @p irn, recalculating the argument at position @p i.
646  *
647  * @param irn       The original operation
648  * @param i         Index of the argument we want the inverse operation to yield
649  * @param inverse   struct to be filled with the resulting inverse op
650  * @param obstack   The obstack to use for allocation of the returned nodes array
651  * @return          The inverse operation or NULL if operation invertible
652  */
653 static arch_inverse_t *ia32_get_inverse(const void *self, const ir_node *irn, int i, arch_inverse_t *inverse, struct obstack *obst) {
654         ir_graph *irg;
655         ir_mode  *mode;
656         ir_mode  *irn_mode;
657         ir_node  *block, *noreg, *nomem;
658         dbg_info *dbg;
659
660         /* we cannot invert non-ia32 irns */
661         if (! is_ia32_irn(irn))
662                 return NULL;
663
664         /* operand must always be a real operand (not base, index or mem) */
665         if (i != 2 && i != 3)
666                 return NULL;
667
668         /* we don't invert address mode operations */
669         if (get_ia32_op_type(irn) != ia32_Normal)
670                 return NULL;
671
672         irg      = get_irn_irg(irn);
673         block    = get_nodes_block(irn);
674         mode     = get_irn_mode(irn);
675         irn_mode = get_irn_mode(irn);
676         noreg    = get_irn_n(irn, 0);
677         nomem    = new_r_NoMem(irg);
678         dbg      = get_irn_dbg_info(irn);
679
680         /* initialize structure */
681         inverse->nodes = obstack_alloc(obst, 2 * sizeof(inverse->nodes[0]));
682         inverse->costs = 0;
683         inverse->n     = 1;
684
685         switch (get_ia32_irn_opcode(irn)) {
686                 case iro_ia32_Add:
687                         if (get_ia32_immop_type(irn) == ia32_ImmConst) {
688                                 /* we have an add with a const here */
689                                 /* invers == add with negated const */
690                                 inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, get_irn_n(irn, i), noreg, nomem);
691                                 inverse->costs   += 1;
692                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
693                                 set_ia32_Immop_tarval(inverse->nodes[0], tarval_neg(get_ia32_Immop_tarval(irn)));
694                                 set_ia32_commutative(inverse->nodes[0]);
695                         }
696                         else if (get_ia32_immop_type(irn) == ia32_ImmSymConst) {
697                                 /* we have an add with a symconst here */
698                                 /* invers == sub with const */
699                                 inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, get_irn_n(irn, i), noreg, nomem);
700                                 inverse->costs   += 2;
701                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
702                         }
703                         else {
704                                 /* normal add: inverse == sub */
705                                 inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, (ir_node*) irn, get_irn_n(irn, i ^ 1), nomem);
706                                 inverse->costs   += 2;
707                         }
708                         break;
709                 case iro_ia32_Sub:
710                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
711                                 /* we have a sub with a const/symconst here */
712                                 /* invers == add with this const */
713                                 inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, get_irn_n(irn, i), noreg, nomem);
714                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
715                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
716                         }
717                         else {
718                                 /* normal sub */
719                                 if (i == 2) {
720                                         inverse->nodes[0] = new_rd_ia32_Add(dbg, irg, block, noreg, noreg, (ir_node*) irn, get_irn_n(irn, 3), nomem);
721                                 }
722                                 else {
723                                         inverse->nodes[0] = new_rd_ia32_Sub(dbg, irg, block, noreg, noreg, get_irn_n(irn, 2), (ir_node*) irn, nomem);
724                                 }
725                                 inverse->costs += 1;
726                         }
727                         break;
728                 case iro_ia32_Eor:
729                         if (get_ia32_immop_type(irn) != ia32_ImmNone) {
730                                 /* xor with const: inverse = xor */
731                                 inverse->nodes[0] = new_rd_ia32_Eor(dbg, irg, block, noreg, noreg, get_irn_n(irn, i), noreg, nomem);
732                                 inverse->costs   += (get_ia32_immop_type(irn) == ia32_ImmSymConst) ? 5 : 1;
733                                 copy_ia32_Immop_attr(inverse->nodes[0], (ir_node *)irn);
734                         }
735                         else {
736                                 /* normal xor */
737                                 inverse->nodes[0] = new_rd_ia32_Eor(dbg, irg, block, noreg, noreg, (ir_node *) irn, get_irn_n(irn, i), nomem);
738                                 inverse->costs   += 1;
739                         }
740                         break;
741                 case iro_ia32_Not: {
742                         inverse->nodes[0] = new_rd_ia32_Not(dbg, irg, block, noreg, noreg, (ir_node*) irn, nomem);
743                         inverse->costs   += 1;
744                         break;
745                 }
746                 case iro_ia32_Minus: {
747                         inverse->nodes[0] = new_rd_ia32_Minus(dbg, irg, block, noreg, noreg, (ir_node*) irn, nomem);
748                         inverse->costs   += 1;
749                         break;
750                 }
751                 default:
752                         /* inverse operation not supported */
753                         return NULL;
754         }
755
756         return inverse;
757 }
758
759 /**
760  * Get the mode that should be used for spilling value node
761  */
762 static ir_mode *get_spill_mode(ia32_code_gen_t *cg, const ir_node *node)
763 {
764         ir_mode *mode = get_irn_mode(node);
765         if (mode_is_float(mode)) {
766 #if 0
767                 // super exact spilling...
768                 if (USE_SSE2(cg))
769                         return mode_D;
770                 else
771                         return mode_E;
772 #else
773                 return mode_D;
774 #endif
775         }
776         else
777                 return mode_Is;
778
779         assert(0);
780         return mode;
781 }
782
783 /**
784  * Checks wether an addressmode reload for a node with mode mode is compatible
785  * with a spillslot of mode spill_mode
786  */
787 static int ia32_is_spillmode_compatible(const ir_mode *mode, const ir_mode *spillmode)
788 {
789         if(mode_is_float(mode)) {
790                 return mode == spillmode;
791         } else {
792                 return 1;
793         }
794 }
795
796 /**
797  * Check if irn can load it's operand at position i from memory (source addressmode).
798  * @param self   Pointer to irn ops itself
799  * @param irn    The irn to be checked
800  * @param i      The operands position
801  * @return Non-Zero if operand can be loaded
802  */
803 static int ia32_possible_memory_operand(const void *self, const ir_node *irn, unsigned int i) {
804         const ia32_irn_ops_t *ops = self;
805         ia32_code_gen_t      *cg  = ops->cg;
806         ir_node *op = get_irn_n(irn, i);
807         const ir_mode *mode = get_irn_mode(op);
808         const ir_mode *spillmode = get_spill_mode(cg, op);
809
810         if (! is_ia32_irn(irn)                            ||  /* must be an ia32 irn */
811                 get_irn_arity(irn) != 5                       ||  /* must be a binary operation */
812                 get_ia32_op_type(irn) != ia32_Normal          ||  /* must not already be a addressmode irn */
813                 ! (get_ia32_am_support(irn) & ia32_am_Source) ||  /* must be capable of source addressmode */
814                 ! ia32_is_spillmode_compatible(mode, spillmode) ||
815                 (i != 2 && i != 3)                            ||  /* a "real" operand position must be requested */
816                 (i == 2 && ! is_ia32_commutative(irn))        ||  /* if first operand requested irn must be commutative */
817                 is_ia32_use_frame(irn))                           /* must not already use frame */
818                 return 0;
819
820         return 1;
821 }
822
823 static void ia32_perform_memory_operand(const void *self, ir_node *irn, ir_node *spill, unsigned int i) {
824         const ia32_irn_ops_t *ops = self;
825         ia32_code_gen_t      *cg  = ops->cg;
826
827         assert(ia32_possible_memory_operand(self, irn, i) && "Cannot perform memory operand change");
828
829         if (i == 2) {
830                 ir_node *tmp = get_irn_n(irn, 3);
831                 set_irn_n(irn, 3, get_irn_n(irn, 2));
832                 set_irn_n(irn, 2, tmp);
833         }
834
835         set_ia32_am_support(irn, ia32_am_Source);
836         set_ia32_op_type(irn, ia32_AddrModeS);
837         set_ia32_am_flavour(irn, ia32_B);
838         set_ia32_ls_mode(irn, get_irn_mode(get_irn_n(irn, i)));
839         set_ia32_use_frame(irn);
840         set_ia32_got_reload(irn);
841
842         set_irn_n(irn, 0, get_irg_frame(get_irn_irg(irn)));
843         set_irn_n(irn, 3, ia32_get_admissible_noreg(cg, irn, 3));
844         set_irn_n(irn, 4, spill);
845
846         //FIXME DBG_OPT_AM_S(reload, irn);
847 }
848
849 static const be_abi_callbacks_t ia32_abi_callbacks = {
850         ia32_abi_init,
851         ia32_abi_done,
852         ia32_abi_get_between_type,
853         ia32_abi_dont_save_regs,
854         ia32_abi_prologue,
855         ia32_abi_epilogue,
856 };
857
858 /* fill register allocator interface */
859
860 static const arch_irn_ops_if_t ia32_irn_ops_if = {
861         ia32_get_irn_reg_req,
862         ia32_set_irn_reg,
863         ia32_get_irn_reg,
864         ia32_classify,
865         ia32_get_flags,
866         ia32_get_frame_entity,
867         ia32_set_frame_entity,
868         ia32_set_frame_offset,
869         ia32_get_sp_bias,
870         ia32_get_inverse,
871         ia32_get_op_estimated_cost,
872         ia32_possible_memory_operand,
873         ia32_perform_memory_operand,
874 };
875
876 ia32_irn_ops_t ia32_irn_ops = {
877         &ia32_irn_ops_if,
878         NULL
879 };
880
881
882
883 /**************************************************
884  *                _                         _  __
885  *               | |                       (_)/ _|
886  *   ___ ___   __| | ___  __ _  ___ _ __    _| |_
887  *  / __/ _ \ / _` |/ _ \/ _` |/ _ \ '_ \  | |  _|
888  * | (_| (_) | (_| |  __/ (_| |  __/ | | | | | |
889  *  \___\___/ \__,_|\___|\__, |\___|_| |_| |_|_|
890  *                        __/ |
891  *                       |___/
892  **************************************************/
893
894 /**
895  * Transform the Thread Local Store base.
896  */
897 static void transform_tls(ir_graph *irg) {
898         ir_node *irn = get_irg_tls(irg);
899
900         if (irn) {
901                 dbg_info *dbg = get_irn_dbg_info(irn);
902                 ir_node  *blk = get_nodes_block(irn);
903                 ir_node  *newn;
904                 newn = new_rd_ia32_LdTls(dbg, irg, blk, get_irn_mode(irn));
905
906                 exchange(irn, newn);
907                 set_irg_tls(irg, newn);
908         }
909 }
910
911 /**
912  * Transforms the standard firm graph into
913  * an ia32 firm graph
914  */
915 static void ia32_prepare_graph(void *self) {
916         ia32_code_gen_t *cg = self;
917         DEBUG_ONLY(firm_dbg_module_t *old_mod = cg->mod;)
918
919         FIRM_DBG_REGISTER(cg->mod, "firm.be.ia32.transform");
920
921         /* 1st: transform constants and psi condition trees */
922         ia32_pre_transform_phase(cg);
923
924         /* 2nd: transform all remaining nodes */
925         transform_tls(cg->irg);
926         ia32_transform_graph(cg);
927         // Matze: disabled for now. Because after transformation start block has no
928         // self-loop anymore so it will probably melt with its successor block.
929         //
930         // This will bring several nodes to the startblock and we still can't
931         // handle spill before the initial IncSP nicely
932         //local_optimize_graph(cg->irg);
933
934         if (cg->dump)
935                 be_dump(cg->irg, "-transformed", dump_ir_block_graph_sched);
936
937         /* 3rd: optimize address mode */
938         FIRM_DBG_REGISTER(cg->mod, "firm.be.ia32.am");
939         ia32_optimize_addressmode(cg);
940
941         if (cg->dump)
942                 be_dump(cg->irg, "-am", dump_ir_block_graph_sched);
943
944         DEBUG_ONLY(cg->mod = old_mod;)
945 }
946
947 /**
948  * Dummy functions for hooks we don't need but which must be filled.
949  */
950 static void ia32_before_sched(void *self) {
951 }
952
953 static void remove_unused_nodes(ir_node *irn, bitset_t *already_visited) {
954         int i, arity;
955         ir_mode *mode;
956         ir_node *mem_proj = NULL;
957
958         if (is_Block(irn))
959                 return;
960
961         mode = get_irn_mode(irn);
962
963         /* check if we already saw this node or the node has more than one user */
964         if (bitset_contains_irn(already_visited, irn) || get_irn_n_edges(irn) > 1) {
965                 return;
966         };
967
968         /* mark irn visited */
969         bitset_add_irn(already_visited, irn);
970
971         /* non-Tuple nodes with one user: ok, return */
972         if (get_irn_n_edges(irn) >= 1 && mode != mode_T) {
973                 return;
974         }
975
976         /* tuple node has one user which is not the mem proj-> ok */
977         if (mode == mode_T && get_irn_n_edges(irn) == 1) {
978                 mem_proj = ia32_get_proj_for_mode(irn, mode_M);
979                 if (mem_proj == NULL) {
980                         return;
981                 }
982         }
983
984         arity = get_irn_arity(irn);
985         for (i = 0; i < arity; ++i) {
986                 ir_node *pred = get_irn_n(irn, i);
987
988                 /* do not follow memory edges or we will accidentally remove stores */
989                 if (get_irn_mode(pred) == mode_M) {
990                         if(mem_proj != NULL) {
991                                 edges_reroute(mem_proj, pred, get_irn_irg(mem_proj));
992                                 mem_proj = NULL;
993                         }
994                         continue;
995                 }
996
997                 set_irn_n(irn, i, new_Bad());
998
999                 /*
1000                         The current node is about to be removed: if the predecessor
1001                         has only this node as user, it need to be removed as well.
1002                 */
1003                 if (get_irn_n_edges(pred) <= 1)
1004                         remove_unused_nodes(pred, already_visited);
1005         }
1006
1007         // we need to set the presd to Bad again to also get the memory edges
1008         arity = get_irn_arity(irn);
1009         for (i = 0; i < arity; ++i) {
1010                 set_irn_n(irn, i, new_Bad());
1011         }
1012
1013         if (sched_is_scheduled(irn)) {
1014                 sched_remove(irn);
1015         }
1016 }
1017
1018 static void remove_unused_loads_walker(ir_node *irn, void *env) {
1019         bitset_t *already_visited = env;
1020         if (is_ia32_Ld(irn) && ! bitset_contains_irn(already_visited, irn))
1021                 remove_unused_nodes(irn, env);
1022 }
1023
1024 /**
1025  * Called before the register allocator.
1026  * Calculate a block schedule here. We need it for the x87
1027  * simulator and the emitter.
1028  */
1029 static void ia32_before_ra(void *self) {
1030         ia32_code_gen_t *cg              = self;
1031         bitset_t        *already_visited = bitset_irg_alloca(cg->irg);
1032
1033         /*
1034                 Handle special case:
1035                 There are sometimes unused loads, only pinned by memory.
1036                 We need to remove those Loads and all other nodes which won't be used
1037                 after removing the Load from schedule.
1038         */
1039         irg_walk_graph(cg->irg, NULL, remove_unused_loads_walker, already_visited);
1040 }
1041
1042
1043 /**
1044  * Transforms a be_Reload into a ia32 Load.
1045  */
1046 static void transform_to_Load(ia32_code_gen_t *cg, ir_node *node) {
1047         ir_graph *irg        = get_irn_irg(node);
1048         dbg_info *dbg        = get_irn_dbg_info(node);
1049         ir_node *block       = get_nodes_block(node);
1050         ir_entity *ent       = be_get_frame_entity(node);
1051         ir_mode *mode        = get_irn_mode(node);
1052         ir_mode *spillmode   = get_spill_mode(cg, node);
1053         ir_node *noreg       = ia32_new_NoReg_gp(cg);
1054         ir_node *sched_point = NULL;
1055         ir_node *ptr         = get_irg_frame(irg);
1056         ir_node *mem         = get_irn_n(node, be_pos_Reload_mem);
1057         ir_node *new_op, *proj;
1058         const arch_register_t *reg;
1059
1060         if (sched_is_scheduled(node)) {
1061                 sched_point = sched_prev(node);
1062         }
1063
1064         if (mode_is_float(spillmode)) {
1065                 if (USE_SSE2(cg))
1066                         new_op = new_rd_ia32_xLoad(dbg, irg, block, ptr, noreg, mem);
1067                 else
1068                         new_op = new_rd_ia32_vfld(dbg, irg, block, ptr, noreg, mem);
1069         }
1070         else
1071                 new_op = new_rd_ia32_Load(dbg, irg, block, ptr, noreg, mem);
1072
1073         set_ia32_am_support(new_op, ia32_am_Source);
1074         set_ia32_op_type(new_op, ia32_AddrModeS);
1075         set_ia32_am_flavour(new_op, ia32_B);
1076         set_ia32_ls_mode(new_op, spillmode);
1077         set_ia32_frame_ent(new_op, ent);
1078         set_ia32_use_frame(new_op);
1079
1080         DBG_OPT_RELOAD2LD(node, new_op);
1081
1082         proj = new_rd_Proj(dbg, irg, block, new_op, mode, pn_ia32_Load_res);
1083
1084         if (sched_point) {
1085                 sched_add_after(sched_point, new_op);
1086                 sched_add_after(new_op, proj);
1087
1088                 sched_remove(node);
1089         }
1090
1091         /* copy the register from the old node to the new Load */
1092         reg = arch_get_irn_register(cg->arch_env, node);
1093         arch_set_irn_register(cg->arch_env, new_op, reg);
1094
1095         SET_IA32_ORIG_NODE(new_op, ia32_get_old_node_name(cg, node));
1096
1097         exchange(node, proj);
1098 }
1099
1100 /**
1101  * Transforms a be_Spill node into a ia32 Store.
1102  */
1103 static void transform_to_Store(ia32_code_gen_t *cg, ir_node *node) {
1104         ir_graph *irg  = get_irn_irg(node);
1105         dbg_info *dbg  = get_irn_dbg_info(node);
1106         ir_node *block = get_nodes_block(node);
1107         ir_entity *ent = be_get_frame_entity(node);
1108         const ir_node *spillval = get_irn_n(node, be_pos_Spill_val);
1109         ir_mode *mode  = get_spill_mode(cg, spillval);
1110         ir_node *noreg = ia32_new_NoReg_gp(cg);
1111         ir_node *nomem = new_rd_NoMem(irg);
1112         ir_node *ptr   = get_irg_frame(irg);
1113         ir_node *val   = get_irn_n(node, be_pos_Spill_val);
1114         ir_node *store;
1115         ir_node *sched_point = NULL;
1116
1117         if (sched_is_scheduled(node)) {
1118                 sched_point = sched_prev(node);
1119         }
1120
1121         if (mode_is_float(mode)) {
1122                 if (USE_SSE2(cg))
1123                         store = new_rd_ia32_xStore(dbg, irg, block, ptr, noreg, val, nomem);
1124                 else
1125                         store = new_rd_ia32_vfst(dbg, irg, block, ptr, noreg, val, nomem);
1126         }
1127         else if (get_mode_size_bits(mode) == 8) {
1128                 store = new_rd_ia32_Store8Bit(dbg, irg, block, ptr, noreg, val, nomem);
1129         }
1130         else {
1131                 store = new_rd_ia32_Store(dbg, irg, block, ptr, noreg, val, nomem);
1132         }
1133
1134         set_ia32_am_support(store, ia32_am_Dest);
1135         set_ia32_op_type(store, ia32_AddrModeD);
1136         set_ia32_am_flavour(store, ia32_B);
1137         set_ia32_ls_mode(store, mode);
1138         set_ia32_frame_ent(store, ent);
1139         set_ia32_use_frame(store);
1140
1141         DBG_OPT_SPILL2ST(node, store);
1142         SET_IA32_ORIG_NODE(store, ia32_get_old_node_name(cg, node));
1143
1144         if (sched_point) {
1145                 sched_add_after(sched_point, store);
1146                 sched_remove(node);
1147         }
1148
1149         exchange(node, store);
1150 }
1151
1152 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) {
1153         ir_graph *irg = get_irn_irg(node);
1154         dbg_info *dbg = get_irn_dbg_info(node);
1155         ir_node *block = get_nodes_block(node);
1156         ir_node *noreg = ia32_new_NoReg_gp(cg);
1157         ir_node *frame = get_irg_frame(irg);
1158
1159         ir_node *push = new_rd_ia32_Push(dbg, irg, block, frame, noreg, noreg, sp, mem);
1160
1161         set_ia32_frame_ent(push, ent);
1162         set_ia32_use_frame(push);
1163         set_ia32_op_type(push, ia32_AddrModeS);
1164         set_ia32_am_flavour(push, ia32_B);
1165         set_ia32_ls_mode(push, mode_Is);
1166
1167         sched_add_before(schedpoint, push);
1168         return push;
1169 }
1170
1171 static ir_node *create_pop(ia32_code_gen_t *cg, ir_node *node, ir_node *schedpoint, ir_node *sp, ir_entity *ent) {
1172         ir_graph *irg = get_irn_irg(node);
1173         dbg_info *dbg = get_irn_dbg_info(node);
1174         ir_node *block = get_nodes_block(node);
1175         ir_node *noreg = ia32_new_NoReg_gp(cg);
1176         ir_node *frame = get_irg_frame(irg);
1177
1178         ir_node *pop = new_rd_ia32_Pop(dbg, irg, block, frame, noreg, sp, new_NoMem());
1179
1180         set_ia32_frame_ent(pop, ent);
1181         set_ia32_use_frame(pop);
1182         set_ia32_op_type(pop, ia32_AddrModeD);
1183         set_ia32_am_flavour(pop, ia32_am_OB);
1184         set_ia32_ls_mode(pop, mode_Is);
1185
1186         sched_add_before(schedpoint, pop);
1187
1188         return pop;
1189 }
1190
1191 static ir_node* create_spproj(ia32_code_gen_t *cg, ir_node *node, ir_node *pred, int pos, ir_node *schedpoint) {
1192         ir_graph *irg = get_irn_irg(node);
1193         dbg_info *dbg = get_irn_dbg_info(node);
1194         ir_node *block = get_nodes_block(node);
1195         ir_mode *spmode = mode_Iu;
1196         const arch_register_t *spreg = &ia32_gp_regs[REG_ESP];
1197         ir_node *sp;
1198
1199         sp = new_rd_Proj(dbg, irg, block, pred, spmode, pos);
1200         arch_set_irn_register(cg->arch_env, sp, spreg);
1201         sched_add_before(schedpoint, sp);
1202
1203         return sp;
1204 }
1205
1206 /**
1207  * Transform memperm, currently we do this the ugly way and produce
1208  * push/pop into/from memory cascades. This is possible without using
1209  * any registers.
1210  */
1211 static void transform_MemPerm(ia32_code_gen_t *cg, ir_node *node) {
1212         ir_graph *irg = get_irn_irg(node);
1213         ir_node *block = get_nodes_block(node);
1214         ir_node *in[1];
1215         ir_node *keep;
1216         int i, arity;
1217         ir_node *sp = be_abi_get_ignore_irn(cg->birg->abi, &ia32_gp_regs[REG_ESP]);
1218         const ir_edge_t *edge;
1219         const ir_edge_t *next;
1220         ir_node **pops;
1221
1222         arity = be_get_MemPerm_entity_arity(node);
1223         pops = alloca(arity * sizeof(pops[0]));
1224
1225         // create pushs
1226         for(i = 0; i < arity; ++i) {
1227                 ir_entity *ent = be_get_MemPerm_in_entity(node, i);
1228                 ir_type *enttype = get_entity_type(ent);
1229                 int entbits = get_type_size_bits(enttype);
1230                 ir_node *mem = get_irn_n(node, i + 1);
1231                 ir_node *push;
1232
1233                 assert( (entbits == 32 || entbits == 64) && "spillslot on x86 should be 32 or 64 bit");
1234
1235                 push = create_push(cg, node, node, sp, mem, ent);
1236                 sp = create_spproj(cg, node, push, pn_ia32_Push_stack, node);
1237                 if(entbits == 64) {
1238                         // add another push after the first one
1239                         push = create_push(cg, node, node, sp, mem, ent);
1240                         add_ia32_am_offs_int(push, 4);
1241                         sp = create_spproj(cg, node, push, pn_ia32_Push_stack, node);
1242                 }
1243
1244                 set_irn_n(node, i, new_Bad());
1245         }
1246
1247         // create pops
1248         for(i = arity - 1; i >= 0; --i) {
1249                 ir_entity *ent = be_get_MemPerm_out_entity(node, i);
1250                 ir_type *enttype = get_entity_type(ent);
1251                 int entbits = get_type_size_bits(enttype);
1252
1253                 ir_node *pop;
1254
1255                 assert( (entbits == 32 || entbits == 64) && "spillslot on x86 should be 32 or 64 bit");
1256
1257                 pop = create_pop(cg, node, node, sp, ent);
1258                 sp = create_spproj(cg, node, pop, pn_ia32_Pop_stack, node);
1259                 if(entbits == 64) {
1260                         add_ia32_am_offs_int(pop, 4);
1261
1262                         // add another pop after the first one
1263                         pop = create_pop(cg, node, node, sp, ent);
1264                         sp = create_spproj(cg, node, pop, pn_ia32_Pop_stack, node);
1265                 }
1266
1267                 pops[i] = pop;
1268         }
1269
1270         in[0] = sp;
1271         keep = be_new_Keep(&ia32_reg_classes[CLASS_ia32_gp], irg, block, 1, in);
1272         sched_add_before(node, keep);
1273
1274         // exchange memprojs
1275         foreach_out_edge_safe(node, edge, next) {
1276                 ir_node *proj = get_edge_src_irn(edge);
1277                 int p = get_Proj_proj(proj);
1278
1279                 assert(p < arity);
1280
1281                 set_Proj_pred(proj, pops[p]);
1282                 set_Proj_proj(proj, 3);
1283         }
1284
1285         // remove memperm
1286         arity = get_irn_arity(node);
1287         for(i = 0; i < arity; ++i) {
1288                 set_irn_n(node, i, new_Bad());
1289         }
1290         sched_remove(node);
1291 }
1292
1293 /**
1294  * Block-Walker: Calls the transform functions Spill and Reload.
1295  */
1296 static void ia32_after_ra_walker(ir_node *block, void *env) {
1297         ir_node *node, *prev;
1298         ia32_code_gen_t *cg = env;
1299
1300         /* beware: the schedule is changed here */
1301         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
1302                 prev = sched_prev(node);
1303
1304                 if (be_is_Reload(node)) {
1305                         transform_to_Load(cg, node);
1306                 } else if (be_is_Spill(node)) {
1307                         transform_to_Store(cg, node);
1308                 } else if(be_is_MemPerm(node)) {
1309                         transform_MemPerm(cg, node);
1310                 }
1311         }
1312 }
1313
1314 /**
1315  * Collects nodes that need frame entities assigned.
1316  */
1317 static void ia32_collect_frame_entity_nodes(ir_node *node, void *data)
1318 {
1319         be_fec_env_t *env = data;
1320
1321         if (be_is_Reload(node) && be_get_frame_entity(node) == NULL) {
1322                 const ir_mode *mode = get_irn_mode(node);
1323                 int align = get_mode_size_bytes(mode);
1324                 be_node_needs_frame_entity(env, node, mode, align);
1325         } else if(is_ia32_irn(node) && get_ia32_frame_ent(node) == NULL
1326                   && is_ia32_use_frame(node)) {
1327                 if (is_ia32_Load(node)) {
1328                         const ir_mode *mode = get_ia32_ls_mode(node);
1329                         int align = get_mode_size_bytes(mode);
1330                         be_node_needs_frame_entity(env, node, mode, align);
1331                 } else if (is_ia32_vfild(node)) {
1332                         const ir_mode *mode = get_ia32_ls_mode(node);
1333                         int align = 4;
1334                         be_node_needs_frame_entity(env, node, mode, align);
1335                 } else if (is_ia32_SetST0(node)) {
1336                         const ir_mode *mode = get_ia32_ls_mode(node);
1337                         int align = 4;
1338                         be_node_needs_frame_entity(env, node, mode, align);
1339                 } else {
1340 #ifndef NDEBUG
1341                         if(!is_ia32_Store(node)
1342                                         && !is_ia32_xStore(node)
1343                                         && !is_ia32_xStoreSimple(node)
1344                                         && !is_ia32_vfist(node)) {
1345                                 assert(0);
1346                         }
1347 #endif
1348                 }
1349         }
1350 }
1351
1352 /**
1353  * We transform Spill and Reload here. This needs to be done before
1354  * stack biasing otherwise we would miss the corrected offset for these nodes.
1355  */
1356 static void ia32_after_ra(void *self) {
1357         ia32_code_gen_t *cg = self;
1358         ir_graph *irg = cg->irg;
1359         be_fec_env_t *fec_env = be_new_frame_entity_coalescer(cg->birg);
1360
1361         /* create and coalesce frame entities */
1362         irg_walk_graph(irg, NULL, ia32_collect_frame_entity_nodes, fec_env);
1363         be_assign_entities(fec_env);
1364         be_free_frame_entity_coalescer(fec_env);
1365
1366         irg_block_walk_graph(irg, NULL, ia32_after_ra_walker, cg);
1367
1368         ia32_finish_irg(irg, cg);
1369 }
1370
1371 /**
1372  * Last touchups for the graph before emit: x87 simulation to replace the
1373  * virtual with real x87 instructions, creating a block schedule and peephole
1374  * optimisations.
1375  */
1376 static void ia32_finish(void *self) {
1377         ia32_code_gen_t *cg = self;
1378         ir_graph        *irg = cg->irg;
1379
1380         /* if we do x87 code generation, rewrite all the virtual instructions and registers */
1381         if (cg->used_fp == fp_x87 || cg->force_sim) {
1382                 x87_simulate_graph(cg->arch_env, cg->birg);
1383         }
1384
1385         /* create block schedule, this also removes empty blocks which might
1386          * produce critical edges */
1387         cg->blk_sched = be_create_block_schedule(irg, cg->birg->exec_freq);
1388
1389         /* do peephole optimisations */
1390         ia32_peephole_optimization(irg, cg);
1391 }
1392
1393 /**
1394  * Emits the code, closes the output file and frees
1395  * the code generator interface.
1396  */
1397 static void ia32_codegen(void *self) {
1398         ia32_code_gen_t *cg = self;
1399         ir_graph        *irg = cg->irg;
1400
1401         ia32_gen_routine(cg->isa->out, irg, cg);
1402
1403         cur_reg_set = NULL;
1404
1405         /* remove it from the isa */
1406         cg->isa->cg = NULL;
1407
1408         /* de-allocate code generator */
1409         del_set(cg->reg_set);
1410         free(cg);
1411 }
1412
1413 static void *ia32_cg_init(be_irg_t *birg);
1414
1415 static const arch_code_generator_if_t ia32_code_gen_if = {
1416         ia32_cg_init,
1417         NULL,                /* before abi introduce hook */
1418         ia32_prepare_graph,
1419         NULL,                /* spill */
1420         ia32_before_sched,   /* before scheduling hook */
1421         ia32_before_ra,      /* before register allocation hook */
1422         ia32_after_ra,       /* after register allocation hook */
1423         ia32_finish,         /* called before codegen */
1424         ia32_codegen         /* emit && done */
1425 };
1426
1427 /**
1428  * Initializes a IA32 code generator.
1429  */
1430 static void *ia32_cg_init(be_irg_t *birg) {
1431         ia32_isa_t      *isa = (ia32_isa_t *)birg->main_env->arch_env->isa;
1432         ia32_code_gen_t *cg  = xcalloc(1, sizeof(*cg));
1433
1434         cg->impl      = &ia32_code_gen_if;
1435         cg->irg       = birg->irg;
1436         cg->reg_set   = new_set(ia32_cmp_irn_reg_assoc, 1024);
1437         cg->arch_env  = birg->main_env->arch_env;
1438         cg->isa       = isa;
1439         cg->birg      = birg;
1440         cg->blk_sched = NULL;
1441         cg->fp_kind   = isa->fp_kind;
1442         cg->used_fp   = fp_none;
1443         cg->dump      = (birg->main_env->options->dump_flags & DUMP_BE) ? 1 : 0;
1444
1445         FIRM_DBG_REGISTER(cg->mod, "firm.be.ia32.cg");
1446
1447         /* copy optimizations from isa for easier access */
1448         cg->opt      = isa->opt;
1449         cg->arch     = isa->arch;
1450         cg->opt_arch = isa->opt_arch;
1451
1452         /* enter it */
1453         isa->cg = cg;
1454
1455 #ifndef NDEBUG
1456         if (isa->name_obst) {
1457                 obstack_free(isa->name_obst, NULL);
1458                 obstack_init(isa->name_obst);
1459         }
1460 #endif /* NDEBUG */
1461
1462         cur_reg_set = cg->reg_set;
1463
1464         ia32_irn_ops.cg = cg;
1465
1466         return (arch_code_generator_t *)cg;
1467 }
1468
1469
1470
1471 /*****************************************************************
1472  *  ____             _                  _   _____  _____
1473  * |  _ \           | |                | | |_   _|/ ____|  /\
1474  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
1475  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
1476  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
1477  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
1478  *
1479  *****************************************************************/
1480
1481 /**
1482  * Set output modes for GCC
1483  */
1484 static const tarval_mode_info mo_integer = {
1485         TVO_DECIMAL,
1486         NULL,
1487         NULL,
1488 };
1489
1490 /*
1491  * set the tarval output mode of all integer modes to decimal
1492  */
1493 static void set_tarval_output_modes(void)
1494 {
1495         int i;
1496
1497         for (i = get_irp_n_modes() - 1; i >= 0; --i) {
1498                 ir_mode *mode = get_irp_mode(i);
1499
1500                 if (mode_is_int(mode))
1501                         set_tarval_mode_output_option(mode, &mo_integer);
1502         }
1503 }
1504
1505 const arch_isa_if_t ia32_isa_if;
1506
1507 /**
1508  * The template that generates a new ISA object.
1509  * Note that this template can be changed by command line
1510  * arguments.
1511  */
1512 static ia32_isa_t ia32_isa_template = {
1513         {
1514                 &ia32_isa_if,            /* isa interface implementation */
1515                 &ia32_gp_regs[REG_ESP],  /* stack pointer register */
1516                 &ia32_gp_regs[REG_EBP],  /* base pointer register */
1517                 -1,                      /* stack direction */
1518                 NULL,                    /* main environment */
1519         },
1520         NULL,                    /* 16bit register names */
1521         NULL,                    /* 8bit register names */
1522         NULL,                    /* types */
1523         NULL,                    /* tv_ents */
1524         (0                 |
1525         IA32_OPT_INCDEC    |     /* optimize add 1, sub 1 into inc/dec               default: on */
1526         IA32_OPT_DOAM      |     /* optimize address mode                            default: on */
1527         IA32_OPT_LEA       |     /* optimize for LEAs                                default: on */
1528         IA32_OPT_PLACECNST |     /* place constants immediately before instructions, default: on */
1529         IA32_OPT_IMMOPS    |     /* operations can use immediates,                   default: on */
1530         IA32_OPT_PUSHARGS),      /* create pushs for function argument passing,      default: on */
1531         arch_pentium_4,          /* instruction architecture */
1532         arch_pentium_4,          /* optimize for architecture */
1533         fp_sse2,                 /* use sse2 unit */
1534         NULL,                    /* current code generator */
1535         NULL,                    /* output file */
1536 #ifndef NDEBUG
1537         NULL,                    /* name obstack */
1538         0                        /* name obst size */
1539 #endif
1540 };
1541
1542 /**
1543  * Initializes the backend ISA.
1544  */
1545 static void *ia32_init(FILE *file_handle) {
1546         static int inited = 0;
1547         ia32_isa_t *isa;
1548
1549         if (inited)
1550                 return NULL;
1551
1552         set_tarval_output_modes();
1553
1554         isa = xmalloc(sizeof(*isa));
1555         memcpy(isa, &ia32_isa_template, sizeof(*isa));
1556
1557         ia32_register_init(isa);
1558         ia32_create_opcodes();
1559         ia32_register_copy_attr_func();
1560
1561         if ((ARCH_INTEL(isa->arch) && isa->arch < arch_pentium_4) ||
1562             (ARCH_AMD(isa->arch) && isa->arch < arch_athlon))
1563                 /* no SSE2 for these cpu's */
1564                 isa->fp_kind = fp_x87;
1565
1566         if (ARCH_INTEL(isa->opt_arch) && isa->opt_arch >= arch_pentium_4) {
1567                 /* Pentium 4 don't like inc and dec instructions */
1568                 isa->opt &= ~IA32_OPT_INCDEC;
1569         }
1570
1571         isa->regs_16bit = pmap_create();
1572         isa->regs_8bit  = pmap_create();
1573         isa->types      = pmap_create();
1574         isa->tv_ent     = pmap_create();
1575         isa->out        = file_handle;
1576         isa->cpu        = ia32_init_machine_description();
1577
1578         ia32_build_16bit_reg_map(isa->regs_16bit);
1579         ia32_build_8bit_reg_map(isa->regs_8bit);
1580
1581         /* patch register names of x87 registers */
1582         ia32_st_regs[0].name = "st";
1583         ia32_st_regs[1].name = "st(1)";
1584         ia32_st_regs[2].name = "st(2)";
1585         ia32_st_regs[3].name = "st(3)";
1586         ia32_st_regs[4].name = "st(4)";
1587         ia32_st_regs[5].name = "st(5)";
1588         ia32_st_regs[6].name = "st(6)";
1589         ia32_st_regs[7].name = "st(7)";
1590
1591 #ifndef NDEBUG
1592         isa->name_obst = xmalloc(sizeof(*isa->name_obst));
1593         obstack_init(isa->name_obst);
1594 #endif /* NDEBUG */
1595
1596         ia32_handle_intrinsics();
1597         ia32_switch_section(isa->out, NO_SECTION);
1598         fprintf(isa->out, "\t.intel_syntax\n");
1599
1600         /* needed for the debug support */
1601         ia32_switch_section(isa->out, SECTION_TEXT);
1602         fprintf(isa->out, ".Ltext0:\n");
1603
1604         inited = 1;
1605
1606         return isa;
1607 }
1608
1609
1610
1611 /**
1612  * Closes the output file and frees the ISA structure.
1613  */
1614 static void ia32_done(void *self) {
1615         ia32_isa_t *isa = self;
1616
1617         /* emit now all global declarations */
1618         ia32_gen_decls(isa->out, isa->arch_isa.main_env);
1619
1620         pmap_destroy(isa->regs_16bit);
1621         pmap_destroy(isa->regs_8bit);
1622         pmap_destroy(isa->tv_ent);
1623         pmap_destroy(isa->types);
1624
1625 #ifndef NDEBUG
1626         obstack_free(isa->name_obst, NULL);
1627 #endif /* NDEBUG */
1628
1629         free(self);
1630 }
1631
1632
1633 /**
1634  * Return the number of register classes for this architecture.
1635  * We report always these:
1636  *  - the general purpose registers
1637  *  - the SSE floating point register set
1638  *  - the virtual floating point registers
1639  */
1640 static int ia32_get_n_reg_class(const void *self) {
1641         return 3;
1642 }
1643
1644 /**
1645  * Return the register class for index i.
1646  */
1647 static const arch_register_class_t *ia32_get_reg_class(const void *self, int i) {
1648         assert(i >= 0 && i < 3 && "Invalid ia32 register class requested.");
1649         if (i == 0)
1650                 return &ia32_reg_classes[CLASS_ia32_gp];
1651         else if (i == 1)
1652                 return &ia32_reg_classes[CLASS_ia32_xmm];
1653         else
1654                 return &ia32_reg_classes[CLASS_ia32_vfp];
1655 }
1656
1657 /**
1658  * Get the register class which shall be used to store a value of a given mode.
1659  * @param self The this pointer.
1660  * @param mode The mode in question.
1661  * @return A register class which can hold values of the given mode.
1662  */
1663 const arch_register_class_t *ia32_get_reg_class_for_mode(const void *self, const ir_mode *mode) {
1664         const ia32_isa_t *isa = self;
1665         if (mode_is_float(mode)) {
1666                 return USE_SSE2(isa) ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
1667         }
1668         else
1669                 return &ia32_reg_classes[CLASS_ia32_gp];
1670 }
1671
1672 /**
1673  * Get the ABI restrictions for procedure calls.
1674  * @param self        The this pointer.
1675  * @param method_type The type of the method (procedure) in question.
1676  * @param abi         The abi object to be modified
1677  */
1678 static void ia32_get_call_abi(const void *self, ir_type *method_type, be_abi_call_t *abi) {
1679         const ia32_isa_t *isa = self;
1680         ir_type  *tp;
1681         ir_mode  *mode;
1682         unsigned  cc        = get_method_calling_convention(method_type);
1683         int       n         = get_method_n_params(method_type);
1684         int       biggest_n = -1;
1685         int       stack_idx = 0;
1686         int       i, ignore_1, ignore_2;
1687         ir_mode **modes;
1688         const arch_register_t *reg;
1689         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
1690
1691         unsigned use_push = !IS_P6_ARCH(isa->opt_arch);
1692
1693         /* set abi flags for calls */
1694         call_flags.bits.left_to_right         = 0;  /* always last arg first on stack */
1695         call_flags.bits.store_args_sequential = use_push;
1696         /* call_flags.bits.try_omit_fp                 not changed: can handle both settings */
1697         call_flags.bits.fp_free               = 0;  /* the frame pointer is fixed in IA32 */
1698         call_flags.bits.call_has_imm          = 1;  /* IA32 calls can have immediate address */
1699
1700         /* set stack parameter passing style */
1701         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
1702
1703         /* collect the mode for each type */
1704         modes = alloca(n * sizeof(modes[0]));
1705
1706         for (i = 0; i < n; i++) {
1707                 tp       = get_method_param_type(method_type, i);
1708                 modes[i] = get_type_mode(tp);
1709         }
1710
1711         /* set register parameters  */
1712         if (cc & cc_reg_param) {
1713                 /* determine the number of parameters passed via registers */
1714                 biggest_n = ia32_get_n_regparam_class(n, modes, &ignore_1, &ignore_2);
1715
1716                 /* loop over all parameters and set the register requirements */
1717                 for (i = 0; i <= biggest_n; i++) {
1718                         reg = ia32_get_RegParam_reg(n, modes, i, cc);
1719                         assert(reg && "kaputt");
1720                         be_abi_call_param_reg(abi, i, reg);
1721                 }
1722
1723                 stack_idx = i;
1724         }
1725
1726
1727         /* set stack parameters */
1728         for (i = stack_idx; i < n; i++) {
1729                 /* parameters on the stack are 32 bit aligned */
1730                 be_abi_call_param_stack(abi, i, 4, 0, 0);
1731         }
1732
1733
1734         /* set return registers */
1735         n = get_method_n_ress(method_type);
1736
1737         assert(n <= 2 && "more than two results not supported");
1738
1739         /* In case of 64bit returns, we will have two 32bit values */
1740         if (n == 2) {
1741                 tp   = get_method_res_type(method_type, 0);
1742                 mode = get_type_mode(tp);
1743
1744                 assert(!mode_is_float(mode) && "two FP results not supported");
1745
1746                 tp   = get_method_res_type(method_type, 1);
1747                 mode = get_type_mode(tp);
1748
1749                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
1750
1751                 be_abi_call_res_reg(abi, 0, &ia32_gp_regs[REG_EAX]);
1752                 be_abi_call_res_reg(abi, 1, &ia32_gp_regs[REG_EDX]);
1753         }
1754         else if (n == 1) {
1755                 const arch_register_t *reg;
1756
1757                 tp   = get_method_res_type(method_type, 0);
1758                 assert(is_atomic_type(tp));
1759                 mode = get_type_mode(tp);
1760
1761                 reg = mode_is_float(mode) ? &ia32_vfp_regs[REG_VF0] : &ia32_gp_regs[REG_EAX];
1762
1763                 be_abi_call_res_reg(abi, 0, reg);
1764         }
1765 }
1766
1767
1768 static const void *ia32_get_irn_ops(const arch_irn_handler_t *self, const ir_node *irn) {
1769         return &ia32_irn_ops;
1770 }
1771
1772 const arch_irn_handler_t ia32_irn_handler = {
1773         ia32_get_irn_ops
1774 };
1775
1776 const arch_irn_handler_t *ia32_get_irn_handler(const void *self) {
1777         return &ia32_irn_handler;
1778 }
1779
1780 int ia32_to_appear_in_schedule(void *block_env, const ir_node *irn) {
1781         return is_ia32_irn(irn) ? 1 : -1;
1782 }
1783
1784 /**
1785  * Initializes the code generator interface.
1786  */
1787 static const arch_code_generator_if_t *ia32_get_code_generator_if(void *self) {
1788         return &ia32_code_gen_if;
1789 }
1790
1791 /**
1792  * Returns the estimated execution time of an ia32 irn.
1793  */
1794 static sched_timestep_t ia32_sched_exectime(void *env, const ir_node *irn) {
1795         const arch_env_t *arch_env = env;
1796         return is_ia32_irn(irn) ? ia32_get_op_estimated_cost(arch_get_irn_ops(arch_env, irn), irn) : 1;
1797 }
1798
1799 list_sched_selector_t ia32_sched_selector;
1800
1801 /**
1802  * Returns the reg_pressure scheduler with to_appear_in_schedule() overloaded
1803  */
1804 static const list_sched_selector_t *ia32_get_list_sched_selector(const void *self, list_sched_selector_t *selector) {
1805         memcpy(&ia32_sched_selector, selector, sizeof(ia32_sched_selector));
1806         ia32_sched_selector.exectime              = ia32_sched_exectime;
1807         ia32_sched_selector.to_appear_in_schedule = ia32_to_appear_in_schedule;
1808         return &ia32_sched_selector;
1809 }
1810
1811 static const ilp_sched_selector_t *ia32_get_ilp_sched_selector(const void *self) {
1812         return NULL;
1813 }
1814
1815 /**
1816  * Returns the necessary byte alignment for storing a register of given class.
1817  */
1818 static int ia32_get_reg_class_alignment(const void *self, const arch_register_class_t *cls) {
1819         ir_mode *mode = arch_register_class_mode(cls);
1820         int bytes     = get_mode_size_bytes(mode);
1821
1822         if (mode_is_float(mode) && bytes > 8)
1823                 return 16;
1824         return bytes;
1825 }
1826
1827 static const be_execution_unit_t ***ia32_get_allowed_execution_units(const void *self, const ir_node *irn) {
1828         static const be_execution_unit_t *_allowed_units_BRANCH[] = {
1829                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH1],
1830                 &ia32_execution_units_BRANCH[IA32_EXECUNIT_TP_BRANCH_BRANCH2],
1831                 NULL,
1832         };
1833         static const be_execution_unit_t *_allowed_units_ALU[] = {
1834                 &ia32_execution_units_ALU[IA32_EXECUNIT_TP_ALU_ALU1],
1835                 &ia32_execution_units_ALU[IA32_EXECUNIT_TP_ALU_ALU2],
1836                 &ia32_execution_units_ALU[IA32_EXECUNIT_TP_ALU_ALU3],
1837                 &ia32_execution_units_ALU[IA32_EXECUNIT_TP_ALU_ALU4],
1838                 NULL,
1839         };
1840         static const be_execution_unit_t *_allowed_units_DUMMY[] = {
1841                 &ia32_execution_units_DUMMY[IA32_EXECUNIT_TP_DUMMY_DUMMY1],
1842                 &ia32_execution_units_DUMMY[IA32_EXECUNIT_TP_DUMMY_DUMMY2],
1843                 &ia32_execution_units_DUMMY[IA32_EXECUNIT_TP_DUMMY_DUMMY3],
1844                 &ia32_execution_units_DUMMY[IA32_EXECUNIT_TP_DUMMY_DUMMY4],
1845                 NULL,
1846         };
1847         static const be_execution_unit_t **_units_callret[] = {
1848                 _allowed_units_BRANCH,
1849                 NULL
1850         };
1851         static const be_execution_unit_t **_units_other[] = {
1852                 _allowed_units_ALU,
1853                 NULL
1854         };
1855         static const be_execution_unit_t **_units_dummy[] = {
1856                 _allowed_units_DUMMY,
1857                 NULL
1858         };
1859         const be_execution_unit_t ***ret;
1860
1861         if (is_ia32_irn(irn)) {
1862                 ret = get_ia32_exec_units(irn);
1863         }
1864         else if (is_be_node(irn)) {
1865                 if (be_is_Call(irn) || be_is_Return(irn)) {
1866                         ret = _units_callret;
1867                 }
1868                 else if (be_is_Barrier(irn)) {
1869                         ret = _units_dummy;
1870                 }
1871                 else {
1872                          ret = _units_other;
1873                 }
1874         }
1875         else {
1876                 ret = _units_dummy;
1877         }
1878
1879         return ret;
1880 }
1881
1882 /**
1883  * Return the abstract ia32 machine.
1884  */
1885 static const be_machine_t *ia32_get_machine(const void *self) {
1886         const ia32_isa_t *isa = self;
1887         return isa->cpu;
1888 }
1889
1890 /**
1891  * Return irp irgs in the desired order.
1892  */
1893 static ir_graph **ia32_get_irg_list(const void *self, ir_graph **irg_list) {
1894         return NULL;
1895 }
1896
1897 /**
1898  * Allows or disallows the creation of Psi nodes for the given Phi nodes.
1899  * @return 1 if allowed, 0 otherwise
1900  */
1901 static int ia32_is_psi_allowed(ir_node *sel, ir_node *phi_list, int i, int j)
1902 {
1903         ir_node *cmp, *cmp_a, *phi;
1904         ir_mode *mode;
1905
1906 /* we don't want long long an floating point Psi */
1907 #define IS_BAD_PSI_MODE(mode) (mode_is_float(mode) || get_mode_size_bits(mode) > 32)
1908
1909         if (get_irn_mode(sel) != mode_b)
1910                 return 0;
1911
1912         cmp   = get_Proj_pred(sel);
1913         cmp_a = get_Cmp_left(cmp);
1914         mode  = get_irn_mode(cmp_a);
1915
1916         if (IS_BAD_PSI_MODE(mode))
1917                 return 0;
1918
1919         /* check the Phi nodes */
1920         for (phi = phi_list; phi; phi = get_irn_link(phi)) {
1921                 ir_node *pred_i = get_irn_n(phi, i);
1922                 ir_node *pred_j = get_irn_n(phi, j);
1923                 ir_mode *mode_i = get_irn_mode(pred_i);
1924                 ir_mode *mode_j = get_irn_mode(pred_j);
1925
1926                 if (IS_BAD_PSI_MODE(mode_i) || IS_BAD_PSI_MODE(mode_j))
1927                         return 0;
1928         }
1929
1930 #undef IS_BAD_PSI_MODE
1931
1932         return 1;
1933 }
1934
1935 static ia32_intrinsic_env_t intrinsic_env = {
1936         NULL,    /**< the irg, these entities belong to */
1937         NULL,    /**< entity for first div operand (move into FPU) */
1938         NULL,    /**< entity for second div operand (move into FPU) */
1939         NULL,    /**< entity for converts ll -> d */
1940         NULL,    /**< entity for converts d -> ll */
1941 };
1942
1943 /**
1944  * Returns the libFirm configuration parameter for this backend.
1945  */
1946 static const backend_params *ia32_get_libfirm_params(void) {
1947         static const opt_if_conv_info_t ifconv = {
1948                 4,                    /* maxdepth, doesn't matter for Psi-conversion */
1949                 ia32_is_psi_allowed   /* allows or disallows Psi creation for given selector */
1950         };
1951         static const arch_dep_params_t ad = {
1952                 1,  /* also use subs */
1953                 4,  /* maximum shifts */
1954                 31, /* maximum shift amount */
1955
1956                 1,  /* allow Mulhs */
1957                 1,  /* allow Mulus */
1958                 32  /* Mulh allowed up to 32 bit */
1959         };
1960         static backend_params p = {
1961                 NULL,  /* no additional opcodes */
1962                 NULL,  /* will be set later */
1963                 1,     /* need dword lowering */
1964                 ia32_create_intrinsic_fkt,
1965                 &intrinsic_env,  /* context for ia32_create_intrinsic_fkt */
1966                 NULL,  /* will be set later */
1967         };
1968
1969         p.dep_param    = &ad;
1970         p.if_conv_info = &ifconv;
1971         return &p;
1972 }
1973 #ifdef WITH_LIBCORE
1974
1975 /* instruction set architectures. */
1976 static const lc_opt_enum_int_items_t arch_items[] = {
1977         { "386",        arch_i386, },
1978         { "486",        arch_i486, },
1979         { "pentium",    arch_pentium, },
1980         { "586",        arch_pentium, },
1981         { "pentiumpro", arch_pentium_pro, },
1982         { "686",        arch_pentium_pro, },
1983         { "pentiummmx", arch_pentium_mmx, },
1984         { "pentium2",   arch_pentium_2, },
1985         { "p2",         arch_pentium_2, },
1986         { "pentium3",   arch_pentium_3, },
1987         { "p3",         arch_pentium_3, },
1988         { "pentium4",   arch_pentium_4, },
1989         { "p4",         arch_pentium_4, },
1990         { "pentiumm",   arch_pentium_m, },
1991         { "pm",         arch_pentium_m, },
1992         { "core",       arch_core, },
1993         { "k6",         arch_k6, },
1994         { "athlon",     arch_athlon, },
1995         { "athlon64",   arch_athlon_64, },
1996         { "opteron",    arch_opteron, },
1997         { NULL,         0 }
1998 };
1999
2000 static lc_opt_enum_int_var_t arch_var = {
2001         &ia32_isa_template.arch, arch_items
2002 };
2003
2004 static lc_opt_enum_int_var_t opt_arch_var = {
2005         &ia32_isa_template.opt_arch, arch_items
2006 };
2007
2008 static const lc_opt_enum_int_items_t fp_unit_items[] = {
2009         { "x87" ,    fp_x87 },
2010         { "sse2",    fp_sse2 },
2011         { NULL,      0 }
2012 };
2013
2014 static lc_opt_enum_int_var_t fp_unit_var = {
2015         &ia32_isa_template.fp_kind, fp_unit_items
2016 };
2017
2018 static const lc_opt_enum_int_items_t gas_items[] = {
2019         { "linux",   ASM_LINUX_GAS },
2020         { "mingw",   ASM_MINGW_GAS },
2021         { NULL,      0 }
2022 };
2023
2024 static lc_opt_enum_int_var_t gas_var = {
2025         (int *)&asm_flavour, gas_items
2026 };
2027
2028 static const lc_opt_table_entry_t ia32_options[] = {
2029         LC_OPT_ENT_ENUM_INT("arch",      "select the instruction architecture", &arch_var),
2030         LC_OPT_ENT_ENUM_INT("opt",       "optimize for instruction architecture", &opt_arch_var),
2031         LC_OPT_ENT_ENUM_INT("fpunit",    "select the floating point unit", &fp_unit_var),
2032         LC_OPT_ENT_NEGBIT("noaddrmode",  "do not use address mode", &ia32_isa_template.opt, IA32_OPT_DOAM),
2033         LC_OPT_ENT_NEGBIT("nolea",       "do not optimize for LEAs", &ia32_isa_template.opt, IA32_OPT_LEA),
2034         LC_OPT_ENT_NEGBIT("noplacecnst", "do not place constants", &ia32_isa_template.opt, IA32_OPT_PLACECNST),
2035         LC_OPT_ENT_NEGBIT("noimmop",     "no operations with immediates", &ia32_isa_template.opt, IA32_OPT_IMMOPS),
2036         LC_OPT_ENT_NEGBIT("nopushargs",  "do not create pushs for function arguments", &ia32_isa_template.opt, IA32_OPT_PUSHARGS),
2037         LC_OPT_ENT_ENUM_INT("gasmode",   "set the GAS compatibility mode", &gas_var),
2038         { NULL }
2039 };
2040 #endif /* WITH_LIBCORE */
2041
2042 const arch_isa_if_t ia32_isa_if = {
2043         ia32_init,
2044         ia32_done,
2045         ia32_get_n_reg_class,
2046         ia32_get_reg_class,
2047         ia32_get_reg_class_for_mode,
2048         ia32_get_call_abi,
2049         ia32_get_irn_handler,
2050         ia32_get_code_generator_if,
2051         ia32_get_list_sched_selector,
2052         ia32_get_ilp_sched_selector,
2053         ia32_get_reg_class_alignment,
2054         ia32_get_libfirm_params,
2055         ia32_get_allowed_execution_units,
2056         ia32_get_machine,
2057         ia32_get_irg_list,
2058 };
2059
2060 void be_init_arch_ia32(void)
2061 {
2062         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
2063         lc_opt_entry_t *ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2064
2065         lc_opt_add_table(ia32_grp, ia32_options);
2066         be_register_isa_if("ia32", &ia32_isa_if);
2067 }
2068
2069 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_ia32);