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