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