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