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