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