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