fixed copy inserter
[libfirm] / ir / be / ia32 / bearch_ia32.c
1 /**
2  * This is the main ia32 firm backend driver.
3  *
4  * $Id$
5  */
6
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #ifdef _WIN32
12 #include <malloc.h>
13 #else
14 #include <alloca.h>
15 #endif
16
17 #include "pseudo_irg.h"
18 #include "irgwalk.h"
19 #include "irprog.h"
20 #include "irprintf.h"
21 #include "iredges_t.h"
22 #include "ircons.h"
23 #include "irgmod.h"
24 #include "irgopt.h"
25
26 #include "bitset.h"
27 #include "debug.h"
28
29 #include "../beabi.h"                 /* the general register allocator interface */
30 #include "../benode_t.h"
31 #include "../belower.h"
32 #include "../besched_t.h"
33 #include "../be.h"
34 #include "bearch_ia32_t.h"
35
36 #include "ia32_new_nodes.h"           /* ia32 nodes interface */
37 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
38 #include "ia32_gen_decls.h"           /* interface declaration emitter */
39 #include "ia32_transform.h"
40 #include "ia32_emitter.h"
41 #include "ia32_map_regs.h"
42 #include "ia32_optimize.h"
43 #include "ia32_x87.h"
44
45 #define DEBUG_MODULE "firm.be.ia32.isa"
46
47 /* TODO: ugly */
48 static set *cur_reg_set = NULL;
49
50 #undef is_Start
51 #define is_Start(irn) (get_irn_opcode(irn) == iro_Start)
52
53 ir_node *ia32_new_NoReg_gp(ia32_code_gen_t *cg) {
54         return be_abi_get_callee_save_irn(cg->birg->abi, &ia32_gp_regs[REG_GP_NOREG]);
55 }
56
57 ir_node *ia32_new_NoReg_fp(ia32_code_gen_t *cg) {
58         return be_abi_get_callee_save_irn(cg->birg->abi,
59                 USE_SSE2(cg) ? &ia32_xmm_regs[REG_XMM_NOREG] : &ia32_vfp_regs[REG_VFP_NOREG]);
60 }
61
62 /**************************************************
63  *                         _ _              _  __
64  *                        | | |            (_)/ _|
65  *  _ __ ___  __ _    __ _| | | ___   ___   _| |_
66  * | '__/ _ \/ _` |  / _` | | |/ _ \ / __| | |  _|
67  * | | |  __/ (_| | | (_| | | | (_) | (__  | | |
68  * |_|  \___|\__, |  \__,_|_|_|\___/ \___| |_|_|
69  *            __/ |
70  *           |___/
71  **************************************************/
72
73 static ir_node *my_skip_proj(const ir_node *n) {
74         while (is_Proj(n))
75                 n = get_Proj_pred(n);
76         return (ir_node *)n;
77 }
78
79
80 /**
81  * Return register requirements for an ia32 node.
82  * If the node returns a tuple (mode_T) then the proj's
83  * will be asked for this information.
84  */
85 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) {
86         const ia32_irn_ops_t      *ops = self;
87         const ia32_register_req_t *irn_req;
88         long                       node_pos = pos == -1 ? 0 : pos;
89         ir_mode                   *mode     = is_Block(irn) ? NULL : get_irn_mode(irn);
90         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, DEBUG_MODULE);
91
92         if (is_Block(irn) || mode == mode_M || mode == mode_X) {
93                 DBG((mod, LEVEL_1, "ignoring Block, mode_M, mode_X node %+F\n", irn));
94                 return NULL;
95         }
96
97         if (mode == mode_T && pos < 0) {
98                 DBG((mod, LEVEL_1, "ignoring request OUT requirements for node %+F\n", irn));
99                 return NULL;
100         }
101
102         DBG((mod, LEVEL_1, "get requirements at pos %d for %+F ... ", pos, irn));
103
104         if (is_Proj(irn)) {
105                 if (pos == -1) {
106                         node_pos = ia32_translate_proj_pos(irn);
107                 }
108                 else {
109                         node_pos = pos;
110                 }
111
112                 irn = my_skip_proj(irn);
113
114                 DB((mod, LEVEL_1, "skipping Proj, going to %+F at pos %d ... ", irn, node_pos));
115         }
116
117         if (is_ia32_irn(irn)) {
118                 if (pos >= 0) {
119                         irn_req = get_ia32_in_req(irn, pos);
120                 }
121                 else {
122                         irn_req = get_ia32_out_req(irn, node_pos);
123                 }
124
125                 DB((mod, LEVEL_1, "returning reqs for %+F at pos %d\n", irn, pos));
126
127                 memcpy(req, &(irn_req->req), sizeof(*req));
128
129                 if (arch_register_req_is(&(irn_req->req), should_be_same)) {
130                         assert(irn_req->same_pos >= 0 && "should be same constraint for in -> out NYI");
131                         req->other_same = get_irn_n(irn, irn_req->same_pos);
132                 }
133
134                 if (arch_register_req_is(&(irn_req->req), should_be_different)) {
135                         assert(irn_req->different_pos >= 0 && "should be different constraint for in -> out NYI");
136                         req->other_different = get_irn_n(irn, irn_req->different_pos);
137                 }
138         }
139         else {
140                 /* treat Phi like Const with default requirements */
141                 if (is_Phi(irn)) {
142                         DB((mod, LEVEL_1, "returning standard reqs for %+F\n", irn));
143                         if (mode_is_float(mode)) {
144                                 if (USE_SSE2(ops->cg))
145                                         memcpy(req, &(ia32_default_req_ia32_xmm.req), sizeof(*req));
146                                 else
147                                         memcpy(req, &(ia32_default_req_ia32_vfp.req), sizeof(*req));
148                         }
149                         else if (mode_is_int(mode) || mode_is_reference(mode))
150                                 memcpy(req, &(ia32_default_req_ia32_gp.req), sizeof(*req));
151                         else if (mode == mode_T || mode == mode_M) {
152                                 DBG((mod, LEVEL_1, "ignoring Phi node %+F\n", irn));
153                                 return NULL;
154                         }
155                         else
156                                 assert(0 && "unsupported Phi-Mode");
157                 }
158                 else {
159                         DB((mod, LEVEL_1, "returning NULL for %+F (not ia32)\n", irn));
160                         req = NULL;
161                 }
162         }
163
164         return req;
165 }
166
167 static void ia32_set_irn_reg(const void *self, ir_node *irn, const arch_register_t *reg) {
168         int                   pos = 0;
169         const ia32_irn_ops_t *ops = self;
170
171         if (get_irn_mode(irn) == mode_X) {
172                 return;
173         }
174
175         DBG((ops->cg->mod, LEVEL_1, "ia32 assigned register %s to node %+F\n", reg->name, irn));
176
177         if (is_Proj(irn)) {
178                 pos = ia32_translate_proj_pos(irn);
179                 irn = my_skip_proj(irn);
180         }
181
182         if (is_ia32_irn(irn)) {
183                 const arch_register_t **slots;
184
185                 slots      = get_ia32_slots(irn);
186                 slots[pos] = reg;
187         }
188         else {
189                 ia32_set_firm_reg(irn, reg, cur_reg_set);
190         }
191 }
192
193 static const arch_register_t *ia32_get_irn_reg(const void *self, const ir_node *irn) {
194         int pos = 0;
195         const arch_register_t *reg = NULL;
196
197         if (is_Proj(irn)) {
198
199                 if (get_irn_mode(irn) == mode_X) {
200                         return NULL;
201                 }
202
203                 pos = ia32_translate_proj_pos(irn);
204                 irn = my_skip_proj(irn);
205         }
206
207         if (is_ia32_irn(irn)) {
208                 const arch_register_t **slots;
209                 slots = get_ia32_slots(irn);
210                 reg   = slots[pos];
211         }
212         else {
213                 reg = ia32_get_firm_reg(irn, cur_reg_set);
214         }
215
216         return reg;
217 }
218
219 static arch_irn_class_t ia32_classify(const void *self, const ir_node *irn) {
220         irn = my_skip_proj(irn);
221         if (is_cfop(irn))
222                 return arch_irn_class_branch;
223         else if (is_ia32_irn(irn))
224                 return arch_irn_class_normal;
225         else
226                 return 0;
227 }
228
229 static arch_irn_flags_t ia32_get_flags(const void *self, const ir_node *irn) {
230         irn = my_skip_proj(irn);
231         if (is_ia32_irn(irn))
232                 return get_ia32_flags(irn);
233         else {
234                 return 0;
235         }
236 }
237
238 static entity *ia32_get_frame_entity(const void *self, const ir_node *irn) {
239         return is_ia32_irn(irn) ? get_ia32_frame_ent(irn) : NULL;
240 }
241
242 static void ia32_set_stack_bias(const void *self, ir_node *irn, int bias) {
243         char buf[64];
244         const ia32_irn_ops_t *ops = self;
245
246         if (get_ia32_frame_ent(irn)) {
247                 ia32_am_flavour_t am_flav = get_ia32_am_flavour(irn);
248
249                 DBG((ops->cg->mod, LEVEL_1, "stack biased %+F with %d\n", irn, bias));
250                 snprintf(buf, sizeof(buf), "%d", bias);
251
252                 if (get_ia32_op_type(irn) == ia32_Normal) {
253                         set_ia32_cnst(irn, buf);
254                 }
255                 else {
256                         add_ia32_am_offs(irn, buf);
257                         am_flav |= ia32_O;
258                         set_ia32_am_flavour(irn, am_flav);
259                 }
260         }
261 }
262
263 typedef struct {
264         be_abi_call_flags_bits_t flags;
265         const arch_isa_t *isa;
266         ir_graph *irg;
267 } ia32_abi_env_t;
268
269 static void *ia32_abi_init(const be_abi_call_t *call, const arch_env_t *aenv, ir_graph *irg)
270 {
271         ia32_abi_env_t *env    = xmalloc(sizeof(env[0]));
272         be_abi_call_flags_t fl = be_abi_call_get_flags(call);
273         env->flags = fl.bits;
274         env->irg   = irg;
275         env->isa   = aenv->isa;
276         return env;
277 }
278
279 static void ia32_abi_dont_save_regs(void *self, pset *s)
280 {
281         ia32_abi_env_t *env = self;
282         if(env->flags.try_omit_fp)
283                 pset_insert_ptr(s, env->isa->bp);
284 }
285
286 static const arch_register_t *ia32_abi_prologue(void *self, ir_node **mem, pmap *reg_map)
287 {
288         ia32_abi_env_t *env              = self;
289         const arch_register_t *frame_reg = env->isa->sp;
290
291         if(!env->flags.try_omit_fp) {
292                 int reg_size         = get_mode_size_bytes(env->isa->bp->reg_class->mode);
293                 ir_node *bl          = get_irg_start_block(env->irg);
294                 ir_node *curr_sp     = be_abi_reg_map_get(reg_map, env->isa->sp);
295                 ir_node *curr_bp     = be_abi_reg_map_get(reg_map, env->isa->bp);
296                 ir_node *curr_no_reg = be_abi_reg_map_get(reg_map, &ia32_gp_regs[REG_GP_NOREG]);
297                 ir_node *store_bp;
298
299                 curr_sp  = be_new_IncSP(env->isa->sp, env->irg, bl, curr_sp, *mem, reg_size, be_stack_dir_expand);
300                 store_bp = new_rd_ia32_Store(NULL, env->irg, bl, curr_sp, curr_no_reg, curr_bp, *mem, mode_T);
301                 set_ia32_am_support(store_bp, ia32_am_Dest);
302                 set_ia32_am_flavour(store_bp, ia32_B);
303                 set_ia32_op_type(store_bp, ia32_AddrModeD);
304                 *mem     = new_r_Proj(env->irg, bl, store_bp, mode_M, 0);
305                 curr_bp  = be_new_Copy(env->isa->bp->reg_class, env->irg, bl, curr_sp);
306                 be_set_constr_single_reg(curr_bp, BE_OUT_POS(0), env->isa->bp);
307                 be_node_set_flags(curr_bp, BE_OUT_POS(0), arch_irn_flags_ignore);
308
309                 be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
310                 be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
311         }
312
313         return frame_reg;
314 }
315
316 static void ia32_abi_epilogue(void *self, ir_node *bl, ir_node **mem, pmap *reg_map)
317 {
318         ia32_abi_env_t *env = self;
319         ir_node *curr_sp     = be_abi_reg_map_get(reg_map, env->isa->sp);
320         ir_node *curr_bp     = be_abi_reg_map_get(reg_map, env->isa->bp);
321         ir_node *curr_no_reg = be_abi_reg_map_get(reg_map, &ia32_gp_regs[REG_GP_NOREG]);
322
323         if(env->flags.try_omit_fp) {
324                 curr_sp = be_new_IncSP(env->isa->sp, env->irg, bl, curr_sp, *mem, BE_STACK_FRAME_SIZE, be_stack_dir_shrink);
325         }
326
327         else {
328                 ir_node *load_bp;
329                 ir_mode *mode_bp = env->isa->bp->reg_class->mode;
330
331                 curr_sp = be_new_SetSP(env->isa->sp, env->irg, bl, curr_sp, curr_bp, *mem);
332                 load_bp = new_rd_ia32_Load(NULL, env->irg, bl, curr_sp, curr_no_reg, *mem, mode_T);
333                 set_ia32_am_support(load_bp, ia32_am_Source);
334                 set_ia32_am_flavour(load_bp, ia32_B);
335                 set_ia32_op_type(load_bp, ia32_AddrModeS);
336                 set_ia32_ls_mode(load_bp, mode_bp);
337                 curr_bp = new_r_Proj(env->irg, bl, load_bp, mode_bp, 0);
338                 *mem    = new_r_Proj(env->irg, bl, load_bp, mode_M, 1);
339         }
340
341         be_abi_reg_map_set(reg_map, env->isa->sp, curr_sp);
342         be_abi_reg_map_set(reg_map, env->isa->bp, curr_bp);
343 }
344
345 /**
346  * Produces the type which sits between the stack args and the locals on the stack.
347  * it will contain the return address and space to store the old base pointer.
348  * @return The Firm type modeling the ABI between type.
349  */
350 static ir_type *ia32_abi_get_between_type(void *self)
351 {
352         static ir_type *omit_fp_between_type = NULL;
353         static ir_type *between_type         = NULL;
354
355         ia32_abi_env_t *env = self;
356
357         if(!between_type) {
358                 entity *old_bp_ent;
359                 entity *ret_addr_ent;
360                 entity *omit_fp_ret_addr_ent;
361
362                 ir_type *old_bp_type   = new_type_primitive(new_id_from_str("bp"), mode_P);
363                 ir_type *ret_addr_type = new_type_primitive(new_id_from_str("return_addr"), mode_P);
364
365                 between_type           = new_type_class(new_id_from_str("ia32_between_type"));
366                 old_bp_ent             = new_entity(between_type, new_id_from_str("old_bp"), old_bp_type);
367                 ret_addr_ent           = new_entity(between_type, new_id_from_str("ret_addr"), ret_addr_type);
368
369                 set_entity_offset_bytes(old_bp_ent, 0);
370                 set_entity_offset_bytes(ret_addr_ent, get_type_size_bytes(old_bp_type));
371                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
372
373                 omit_fp_between_type   = new_type_class(new_id_from_str("ia32_between_type_omit_fp"));
374                 omit_fp_ret_addr_ent   = new_entity(omit_fp_between_type, new_id_from_str("ret_addr"), ret_addr_type);
375
376                 set_entity_offset_bytes(omit_fp_ret_addr_ent, 0);
377                 set_type_size_bytes(omit_fp_between_type, get_type_size_bytes(ret_addr_type));
378         }
379
380         return env->flags.try_omit_fp ? omit_fp_between_type : between_type;
381 }
382
383 static const be_abi_callbacks_t ia32_abi_callbacks = {
384         ia32_abi_init,
385         free,
386         ia32_abi_get_between_type,
387         ia32_abi_dont_save_regs,
388         ia32_abi_prologue,
389         ia32_abi_epilogue,
390 };
391
392 /* fill register allocator interface */
393
394 static const arch_irn_ops_if_t ia32_irn_ops_if = {
395         ia32_get_irn_reg_req,
396         ia32_set_irn_reg,
397         ia32_get_irn_reg,
398         ia32_classify,
399         ia32_get_flags,
400         ia32_get_frame_entity,
401         ia32_set_stack_bias
402 };
403
404 ia32_irn_ops_t ia32_irn_ops = {
405         &ia32_irn_ops_if,
406         NULL
407 };
408
409
410
411 /**************************************************
412  *                _                         _  __
413  *               | |                       (_)/ _|
414  *   ___ ___   __| | ___  __ _  ___ _ __    _| |_
415  *  / __/ _ \ / _` |/ _ \/ _` |/ _ \ '_ \  | |  _|
416  * | (_| (_) | (_| |  __/ (_| |  __/ | | | | | |
417  *  \___\___/ \__,_|\___|\__, |\___|_| |_| |_|_|
418  *                        __/ |
419  *                       |___/
420  **************************************************/
421
422 /**
423  * Transforms the standard firm graph into
424  * an ia32 firm graph
425  */
426 static void ia32_prepare_graph(void *self) {
427         ia32_code_gen_t *cg = self;
428         DEBUG_ONLY(firm_dbg_module_t *old_mod = cg->mod;)
429
430         FIRM_DBG_REGISTER(cg->mod, "firm.be.ia32.transform");
431         irg_walk_blkwise_graph(cg->irg, ia32_place_consts_set_modes, ia32_transform_node, cg);
432         be_dump(cg->irg, "-transformed", dump_ir_block_graph_sched);
433
434         DEBUG_ONLY(cg->mod = old_mod;)
435
436         if (cg->opt.doam) {
437                 edges_deactivate(cg->irg);
438                 //dead_node_elimination(cg->irg);
439                 edges_activate(cg->irg);
440
441                 irg_walk_blkwise_graph(cg->irg, NULL, ia32_optimize_am, cg);
442                 be_dump(cg->irg, "-am", dump_ir_block_graph_sched);
443         }
444 }
445
446
447 /**
448  * Insert copies for all ia32 nodes where the should_be_same requirement
449  * is not fulfilled.
450  * Transform Sub into Neg -- Add if IN2 == OUT
451  */
452 static void ia32_finish_irg_walker(ir_node *irn, void *env) {
453         ia32_code_gen_t            *cg = env;
454         const ia32_register_req_t **reqs;
455         const arch_register_t      *out_reg, *in_reg;
456         int                         n_res, i;
457         ir_node                    *copy, *in_node, *block;
458         ia32_op_type_t              op_tp;
459
460         if (is_ia32_irn(irn)) {
461                 /* AM Dest nodes don't produce any values  */
462                 op_tp = get_ia32_op_type(irn);
463                 if (op_tp == ia32_AddrModeD)
464                         return;
465
466                 reqs  = get_ia32_out_req_all(irn);
467                 n_res = get_ia32_n_res(irn);
468                 block = get_nodes_block(irn);
469
470                 /* check all OUT requirements, if there is a should_be_same */
471                 if (op_tp == ia32_Normal) {
472                         for (i = 0; i < n_res; i++) {
473                                 if (arch_register_req_is(&(reqs[i]->req), should_be_same)) {
474                                         /* get in and out register */
475                                         out_reg = get_ia32_out_reg(irn, i);
476                                         in_node = get_irn_n(irn, reqs[i]->same_pos);
477                                         in_reg  = arch_get_irn_register(cg->arch_env, in_node);
478
479                                         /* don't copy ignore nodes */
480                                         if (arch_irn_is(cg->arch_env, in_node, ignore) && is_Proj(in_node))
481                                                 continue;
482
483                                         /* check if in and out register are equal */
484                                         if (! REGS_ARE_EQUAL(out_reg, in_reg)) {
485                                                 /* in case of a commutative op: just exchange the in's */
486                                                 if (is_ia32_commutative(irn)) {
487                                                         ir_node *in2 = get_irn_n(irn, reqs[i]->same_pos ^ 1);
488                                                         if (REGS_ARE_EQUAL(out_reg, arch_get_irn_register(cg->arch_env, in2))) {
489                                                                 set_irn_n(irn, reqs[i]->same_pos, in2);
490                                                                 set_irn_n(irn, reqs[i]->same_pos ^ 1, in_node);
491                                                         }
492                                                 }
493                                                 else {
494                                                         DBG((cg->mod, LEVEL_1, "inserting copy for %+F in_pos %d\n", irn, reqs[i]->same_pos));
495                                                         /* create copy from in register */
496                                                         copy = be_new_Copy(arch_register_get_class(in_reg), cg->irg, block, in_node);
497
498                                                         /* destination is the out register */
499                                                         arch_set_irn_register(cg->arch_env, copy, out_reg);
500
501                                                         /* insert copy before the node into the schedule */
502                                                         sched_add_before(irn, copy);
503
504                                                         /* set copy as in */
505                                                         set_irn_n(irn, reqs[i]->same_pos, copy);
506                                                 }
507                                         }
508                                 }
509                         }
510                 }
511
512                 /* If we have a CondJmp with immediate, we need to    */
513                 /* check if it's the right operand, otherwise we have */
514                 /* to change it, as CMP doesn't support immediate as  */
515                 /* left operands.                                     */
516                 if (is_ia32_CondJmp(irn) && (is_ia32_ImmConst(irn) || is_ia32_ImmSymConst(irn)) && op_tp == ia32_AddrModeS) {
517                         long pnc = get_negated_pnc(get_ia32_pncode(irn), get_ia32_res_mode(irn));
518                         set_ia32_op_type(irn, ia32_AddrModeD);
519                         set_ia32_pncode(irn, pnc);
520                 }
521
522                 /* check if there is a sub which need to be transformed */
523                 ia32_transform_sub_to_neg_add(irn, cg);
524
525                 /* transform a LEA into an Add if possible */
526                 ia32_transform_lea_to_add(irn, cg);
527         }
528
529         /* check for peephole optimization */
530         ia32_peephole_optimization(irn, cg);
531 }
532
533 /**
534  * Add Copy nodes for not fulfilled should_be_equal constraints
535  */
536 static void ia32_finish_irg(ir_graph *irg, ia32_code_gen_t *cg) {
537         irg_walk_blkwise_graph(irg, NULL, ia32_finish_irg_walker, cg);
538 }
539
540
541
542 /**
543  * Dummy functions for hooks we don't need but which must be filled.
544  */
545 static void ia32_before_sched(void *self) {
546 }
547
548 /**
549  * Called before the register allocator.
550  * Calculate a block schedule here. We need it for the x87
551  * simulator and the emitter.
552  */
553 static void ia32_before_ra(void *self) {
554         ia32_code_gen_t *cg = self;
555
556         cg->blk_sched = sched_create_block_schedule(cg->irg);
557 }
558
559
560 /**
561  * Transforms a be node into a Load.
562  */
563 static void transform_to_Load(ia32_transform_env_t *env) {
564         ir_node *irn         = env->irn;
565         entity  *ent         = be_get_frame_entity(irn);
566         ir_mode *mode        = env->mode;
567         ir_node *noreg       = ia32_new_NoReg_gp(env->cg);
568         ir_node *nomem       = new_rd_NoMem(env->irg);
569         ir_node *sched_point = NULL;
570         ir_node *ptr         = get_irn_n(irn, 0);
571         ir_node *mem         = be_is_Reload(irn) ? get_irn_n(irn, 1) : nomem;
572         ir_node *new_op, *proj;
573         const arch_register_t *reg;
574
575         if (sched_is_scheduled(irn)) {
576                 sched_point = sched_prev(irn);
577         }
578
579         if (mode_is_float(mode)) {
580                 if (USE_SSE2(env->cg))
581                         new_op = new_rd_ia32_fLoad(env->dbg, env->irg, env->block, ptr, noreg, mem, mode_T);
582                 else
583                         new_op = new_rd_ia32_vfld(env->dbg, env->irg, env->block, ptr, noreg, mem, mode_T);
584         }
585         else {
586                 new_op = new_rd_ia32_Load(env->dbg, env->irg, env->block, ptr, noreg, mem, mode_T);
587         }
588
589         set_ia32_am_support(new_op, ia32_am_Source);
590         set_ia32_op_type(new_op, ia32_AddrModeS);
591         set_ia32_am_flavour(new_op, ia32_B);
592         set_ia32_ls_mode(new_op, mode);
593         set_ia32_frame_ent(new_op, ent);
594         set_ia32_use_frame(new_op);
595
596         proj = new_rd_Proj(env->dbg, env->irg, env->block, new_op, mode, pn_Load_res);
597
598         if (sched_point) {
599                 sched_add_after(sched_point, new_op);
600                 sched_add_after(new_op, proj);
601
602                 sched_remove(irn);
603         }
604
605         /* copy the register from the old node to the new Load */
606         reg = arch_get_irn_register(env->cg->arch_env, irn);
607         arch_set_irn_register(env->cg->arch_env, new_op, reg);
608
609         SET_IA32_ORIG_NODE(new_op, ia32_get_old_node_name(env));
610
611         exchange(irn, proj);
612 }
613
614 /**
615  * Transforms a be node into a Store.
616  */
617 static void transform_to_Store(ia32_transform_env_t *env) {
618         ir_node *irn   = env->irn;
619         entity  *ent   = be_get_frame_entity(irn);
620         ir_mode *mode  = env->mode;
621         ir_node *noreg = ia32_new_NoReg_gp(env->cg);
622         ir_node *nomem = new_rd_NoMem(env->irg);
623         ir_node *ptr   = get_irn_n(irn, 0);
624         ir_node *val   = get_irn_n(irn, 1);
625         ir_node *new_op, *proj;
626         ir_node *sched_point = NULL;
627
628         if (sched_is_scheduled(irn)) {
629                 sched_point = sched_prev(irn);
630         }
631
632         if (mode_is_float(mode)) {
633                 if (USE_SSE2(env->cg))
634                         new_op = new_rd_ia32_fStore(env->dbg, env->irg, env->block, ptr, noreg, val, nomem, mode_T);
635                 else
636                         new_op = new_rd_ia32_vfst(env->dbg, env->irg, env->block, ptr, noreg, val, nomem, mode_T);
637         }
638         else if (get_mode_size_bits(mode) == 8) {
639                 new_op = new_rd_ia32_Store8Bit(env->dbg, env->irg, env->block, ptr, noreg, val, nomem, mode_T);
640         }
641         else {
642                 new_op = new_rd_ia32_Store(env->dbg, env->irg, env->block, ptr, noreg, val, nomem, mode_T);
643         }
644
645         set_ia32_am_support(new_op, ia32_am_Dest);
646         set_ia32_op_type(new_op, ia32_AddrModeD);
647         set_ia32_am_flavour(new_op, ia32_B);
648         set_ia32_ls_mode(new_op, mode);
649         set_ia32_frame_ent(new_op, ent);
650         set_ia32_use_frame(new_op);
651
652         proj = new_rd_Proj(env->dbg, env->irg, env->block, new_op, mode_M, 0);
653
654         if (sched_point) {
655                 sched_add_after(sched_point, new_op);
656                 sched_add_after(new_op, proj);
657
658                 sched_remove(irn);
659         }
660
661         SET_IA32_ORIG_NODE(new_op, ia32_get_old_node_name(env));
662
663         exchange(irn, proj);
664 }
665
666 /**
667  * Fix the mode of Spill/Reload
668  */
669 static ir_mode *fix_spill_mode(ia32_code_gen_t *cg, ir_mode *mode)
670 {
671         if (mode_is_float(mode)) {
672                 if (USE_SSE2(cg))
673                         mode = mode_D;
674                 else
675                         mode = mode_E;
676         }
677         else
678                 mode = mode_Is;
679         return mode;
680 }
681
682 /**
683  * Block-Walker: Calls the transform functions Spill and Reload.
684  */
685 static void ia32_after_ra_walker(ir_node *block, void *env) {
686         ir_node *node, *prev;
687         ia32_code_gen_t *cg = env;
688         ia32_transform_env_t tenv;
689
690         tenv.block = block;
691         tenv.irg   = current_ir_graph;
692         tenv.cg    = cg;
693         DEBUG_ONLY(tenv.mod = cg->mod;)
694
695         /* beware: the schedule is changed here */
696         for (node = sched_last(block); !sched_is_begin(node); node = prev) {
697                 prev = sched_prev(node);
698                 if (be_is_Reload(node)) {
699                         /* we always reload the whole register  */
700                         tenv.dbg  = get_irn_dbg_info(node);
701                         tenv.irn  = node;
702                         tenv.mode = fix_spill_mode(cg, get_irn_mode(node));
703                         transform_to_Load(&tenv);
704                 }
705                 else if (be_is_Spill(node)) {
706                         /* we always spill the whole register  */
707                         tenv.dbg  = get_irn_dbg_info(node);
708                         tenv.irn  = node;
709                         tenv.mode = fix_spill_mode(cg, get_irn_mode(be_get_Spill_context(node)));
710                         transform_to_Store(&tenv);
711                 }
712         }
713 }
714
715 /**
716  * We transform Spill and Reload here. This needs to be done before
717  * stack biasing otherwise we would miss the corrected offset for these nodes.
718  *
719  * If x87 instruction should be emitted, run the x87 simulator and patch
720  * the virtual instructions. This must obviously be done after register allocation.
721  */
722 static void ia32_after_ra(void *self) {
723         ia32_code_gen_t *cg = self;
724         irg_block_walk_graph(cg->irg, NULL, ia32_after_ra_walker, self);
725
726         /* if we do x87 code generation, rewrite all the virtual instructions and registers */
727         if (cg->used_x87) {
728                 x87_simulate_graph(cg->arch_env, cg->irg, cg->blk_sched);
729         }
730 }
731
732
733 /**
734  * Emits the code, closes the output file and frees
735  * the code generator interface.
736  */
737 static void ia32_codegen(void *self) {
738         ia32_code_gen_t *cg = self;
739         ir_graph        *irg = cg->irg;
740         FILE            *out = cg->out;
741
742         if (cg->emit_decls) {
743                 ia32_gen_decls(cg->out);
744                 cg->emit_decls = 0;
745         }
746
747         ia32_finish_irg(irg, cg);
748         be_dump(irg, "-finished", dump_ir_block_graph_sched);
749         ia32_gen_routine(out, irg, cg);
750
751         cur_reg_set = NULL;
752
753         pmap_destroy(cg->tv_ent);
754         pmap_destroy(cg->types);
755
756         /* de-allocate code generator */
757         del_set(cg->reg_set);
758         free(self);
759 }
760
761 static void *ia32_cg_init(FILE *F, const be_irg_t *birg);
762
763 static const arch_code_generator_if_t ia32_code_gen_if = {
764         ia32_cg_init,
765         NULL,                /* before abi introduce hook */
766         ia32_prepare_graph,
767         ia32_before_sched,   /* before scheduling hook */
768         ia32_before_ra,      /* before register allocation hook */
769         ia32_after_ra,       /* after register allocation hook */
770         ia32_codegen         /* emit && done */
771 };
772
773 /**
774  * Initializes the code generator.
775  */
776 static void *ia32_cg_init(FILE *F, const be_irg_t *birg) {
777         ia32_isa_t      *isa = (ia32_isa_t *)birg->main_env->arch_env->isa;
778         ia32_code_gen_t *cg  = xcalloc(1, sizeof(*cg));
779
780         cg->impl      = &ia32_code_gen_if;
781         cg->irg       = birg->irg;
782         cg->reg_set   = new_set(ia32_cmp_irn_reg_assoc, 1024);
783         cg->out       = F;
784         cg->arch_env  = birg->main_env->arch_env;
785         cg->types     = pmap_create();
786         cg->tv_ent    = pmap_create();
787         cg->birg      = birg;
788         cg->blk_sched = NULL;
789         cg->fp_kind   = isa->fp_kind;
790         cg->used_x87  = 0;
791
792         FIRM_DBG_REGISTER(cg->mod, "firm.be.ia32.cg");
793
794         /* set optimizations */
795         cg->opt.incdec    = 0;
796         cg->opt.doam      = 0;
797         cg->opt.placecnst = 1;
798         cg->opt.immops    = 1;
799         cg->opt.extbb     = 1;
800
801 #ifndef NDEBUG
802         if (isa->name_obst_size) {
803                 //printf("freed %d bytes from name obst\n", isa->name_obst_size);
804                 isa->name_obst_size = 0;
805                 obstack_free(isa->name_obst, NULL);
806                 obstack_init(isa->name_obst);
807         }
808 #endif /* NDEBUG */
809
810         isa->num_codegens++;
811
812         if (isa->num_codegens > 1)
813                 cg->emit_decls = 0;
814         else
815                 cg->emit_decls = 1;
816
817         cur_reg_set = cg->reg_set;
818
819         ia32_irn_ops.cg = cg;
820
821         return (arch_code_generator_t *)cg;
822 }
823
824
825
826 /*****************************************************************
827  *  ____             _                  _   _____  _____
828  * |  _ \           | |                | | |_   _|/ ____|  /\
829  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
830  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
831  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
832  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
833  *
834  *****************************************************************/
835
836 static ia32_isa_t ia32_isa_template = {
837         &ia32_isa_if,            /* isa interface implementation */
838         &ia32_gp_regs[REG_ESP],  /* stack pointer register */
839         &ia32_gp_regs[REG_EBP],  /* base pointer register */
840         -1,                      /* stack direction */
841         0,                       /* number of code generator objects so far */
842         NULL,                    /* 16bit register names */
843         NULL,                    /* 8bit register names */
844         fp_sse2,                 /* use SSE2 unit for fp operations */
845 #ifndef NDEBUG
846         NULL,                    /* name obstack */
847         0                        /* name obst size */
848 #endif
849 };
850
851 /**
852  * Initializes the backend ISA.
853  */
854 static void *ia32_init(void) {
855         static int inited = 0;
856         ia32_isa_t *isa;
857
858         if(inited)
859                 return NULL;
860
861         isa = xcalloc(1, sizeof(*isa));
862         memcpy(isa, &ia32_isa_template, sizeof(*isa));
863
864         ia32_register_init(isa);
865         ia32_create_opcodes();
866         ia32_register_copy_attr_func();
867
868         isa->regs_16bit = pmap_create();
869         isa->regs_8bit  = pmap_create();
870 //      isa->fp_kind    = fp_x87;
871
872         ia32_build_16bit_reg_map(isa->regs_16bit);
873         ia32_build_8bit_reg_map(isa->regs_8bit);
874
875 #ifndef NDEBUG
876         isa->name_obst = xcalloc(1, sizeof(*(isa->name_obst)));
877         obstack_init(isa->name_obst);
878         isa->name_obst_size = 0;
879 #endif /* NDEBUG */
880
881         inited = 1;
882
883         return isa;
884 }
885
886
887
888 /**
889  * Closes the output file and frees the ISA structure.
890  */
891 static void ia32_done(void *self) {
892         ia32_isa_t *isa = self;
893
894         pmap_destroy(isa->regs_16bit);
895         pmap_destroy(isa->regs_8bit);
896
897 #ifndef NDEBUG
898         //printf("name obst size = %d bytes\n", isa->name_obst_size);
899         obstack_free(isa->name_obst, NULL);
900 #endif /* NDEBUG */
901
902         free(self);
903 }
904
905
906 /**
907  * Return the number of register classes for this architecture.
908  * We report always these:
909  *  - the general purpose registers
910  *  - the floating point register set (depending on the unit used for FP)
911  *  - MMX/SE registers (currently not supported)
912  */
913 static int ia32_get_n_reg_class(const void *self) {
914         return 2;
915 }
916
917 /**
918  * Return the register class for index i.
919  */
920 static const arch_register_class_t *ia32_get_reg_class(const void *self, int i) {
921         const ia32_isa_t *isa = self;
922         assert(i >= 0 && i < 2 && "Invalid ia32 register class requested.");
923         if (i == 0)
924                 return &ia32_reg_classes[CLASS_ia32_gp];
925         return USE_SSE2(isa) ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
926 }
927
928 /**
929  * Get the register class which shall be used to store a value of a given mode.
930  * @param self The this pointer.
931  * @param mode The mode in question.
932  * @return A register class which can hold values of the given mode.
933  */
934 const arch_register_class_t *ia32_get_reg_class_for_mode(const void *self, const ir_mode *mode) {
935         const ia32_isa_t *isa = self;
936         if (mode_is_float(mode)) {
937                 return USE_SSE2(isa) ? &ia32_reg_classes[CLASS_ia32_xmm] : &ia32_reg_classes[CLASS_ia32_vfp];
938         }
939         else
940                 return &ia32_reg_classes[CLASS_ia32_gp];
941 }
942
943 /**
944  * Get the ABI restrictions for procedure calls.
945  * @param self        The this pointer.
946  * @param method_type The type of the method (procedure) in question.
947  * @param abi         The abi object to be modified
948  */
949 static void ia32_get_call_abi(const void *self, ir_type *method_type, be_abi_call_t *abi) {
950         const ia32_isa_t *isa = self;
951         ir_type  *tp;
952         ir_mode  *mode;
953         unsigned  cc        = get_method_calling_convention(method_type);
954         int       n         = get_method_n_params(method_type);
955         int       biggest_n = -1;
956         int       stack_idx = 0;
957         int       i, ignore_1, ignore_2;
958         ir_mode **modes;
959         const arch_register_t *reg;
960         be_abi_call_flags_t call_flags;
961
962         /* set abi flags for calls */
963         call_flags.bits.left_to_right         = 0;
964         call_flags.bits.store_args_sequential = 0;
965         call_flags.bits.try_omit_fp           = 1;
966         call_flags.bits.fp_free               = 0;
967         call_flags.bits.call_has_imm          = 1;
968
969         /* set stack parameter passing style */
970         be_abi_call_set_flags(abi, call_flags, &ia32_abi_callbacks);
971
972         /* collect the mode for each type */
973         modes = alloca(n * sizeof(modes[0]));
974
975         for (i = 0; i < n; i++) {
976                 tp       = get_method_param_type(method_type, i);
977                 modes[i] = get_type_mode(tp);
978         }
979
980         /* set register parameters  */
981         if (cc & cc_reg_param) {
982                 /* determine the number of parameters passed via registers */
983                 biggest_n = ia32_get_n_regparam_class(n, modes, &ignore_1, &ignore_2);
984
985                 /* loop over all parameters and set the register requirements */
986                 for (i = 0; i <= biggest_n; i++) {
987                         reg = ia32_get_RegParam_reg(n, modes, i, cc);
988                         assert(reg && "kaputt");
989                         be_abi_call_param_reg(abi, i, reg);
990                 }
991
992                 stack_idx = i;
993         }
994
995
996         /* set stack parameters */
997         for (i = stack_idx; i < n; i++) {
998                 be_abi_call_param_stack(abi, i, 1, 0, 0);
999         }
1000
1001
1002         /* set return registers */
1003         n = get_method_n_ress(method_type);
1004
1005         assert(n <= 2 && "more than two results not supported");
1006
1007         /* In case of 64bit returns, we will have two 32bit values */
1008         if (n == 2) {
1009                 tp   = get_method_res_type(method_type, 0);
1010                 mode = get_type_mode(tp);
1011
1012                 assert(!mode_is_float(mode) && "two FP results not supported");
1013
1014                 tp   = get_method_res_type(method_type, 1);
1015                 mode = get_type_mode(tp);
1016
1017                 assert(!mode_is_float(mode) && "two FP results not supported");
1018
1019                 be_abi_call_res_reg(abi, 0, &ia32_gp_regs[REG_EAX]);
1020                 be_abi_call_res_reg(abi, 1, &ia32_gp_regs[REG_EDX]);
1021         }
1022         else if (n == 1) {
1023                 const arch_register_t *reg;
1024
1025                 tp   = get_method_res_type(method_type, 0);
1026                 assert(is_atomic_type(tp));
1027                 mode = get_type_mode(tp);
1028
1029                 reg = mode_is_float(mode) ?
1030                         (USE_SSE2(isa) ? &ia32_xmm_regs[REG_XMM0] : &ia32_vfp_regs[REG_VF0]) :
1031                         &ia32_gp_regs[REG_EAX];
1032
1033                 be_abi_call_res_reg(abi, 0, reg);
1034         }
1035 }
1036
1037
1038 static const void *ia32_get_irn_ops(const arch_irn_handler_t *self, const ir_node *irn) {
1039         return &ia32_irn_ops;
1040 }
1041
1042 const arch_irn_handler_t ia32_irn_handler = {
1043         ia32_get_irn_ops
1044 };
1045
1046 const arch_irn_handler_t *ia32_get_irn_handler(const void *self) {
1047         return &ia32_irn_handler;
1048 }
1049
1050 int ia32_to_appear_in_schedule(void *block_env, const ir_node *irn) {
1051         return is_ia32_irn(irn);
1052 }
1053
1054 /**
1055  * Initializes the code generator interface.
1056  */
1057 static const arch_code_generator_if_t *ia32_get_code_generator_if(void *self) {
1058         return &ia32_code_gen_if;
1059 }
1060
1061 list_sched_selector_t ia32_sched_selector;
1062
1063 /**
1064  * Returns the reg_pressure scheduler with to_appear_in_schedule() overloaded
1065  */
1066 static const list_sched_selector_t *ia32_get_list_sched_selector(const void *self) {
1067 //      memcpy(&ia32_sched_selector, reg_pressure_selector, sizeof(list_sched_selector_t));
1068         memcpy(&ia32_sched_selector, trivial_selector, sizeof(list_sched_selector_t));
1069         ia32_sched_selector.to_appear_in_schedule = ia32_to_appear_in_schedule;
1070         return &ia32_sched_selector;
1071 }
1072
1073 /**
1074  * Returns the necessary byte alignment for storing a register of given class.
1075  */
1076 static int ia32_get_reg_class_alignment(const void *self, const arch_register_class_t *cls) {
1077         ir_mode *mode = arch_register_class_mode(cls);
1078         int bytes     = get_mode_size_bytes(mode);
1079
1080         if (mode_is_float(mode) && bytes > 8)
1081                 return 16;
1082         return bytes;
1083 }
1084
1085 #ifdef WITH_LIBCORE
1086 static void ia32_register_options(lc_opt_entry_t *ent)
1087 {
1088 }
1089 #endif /* WITH_LIBCORE */
1090
1091 const arch_isa_if_t ia32_isa_if = {
1092 #ifdef WITH_LIBCORE
1093         ia32_register_options,
1094 #endif
1095         ia32_init,
1096         ia32_done,
1097         ia32_get_n_reg_class,
1098         ia32_get_reg_class,
1099         ia32_get_reg_class_for_mode,
1100         ia32_get_call_abi,
1101         ia32_get_irn_handler,
1102         ia32_get_code_generator_if,
1103         ia32_get_list_sched_selector,
1104         ia32_get_reg_class_alignment
1105 };