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