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