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