1ff9e159499a41367aae873bebd6945a2c1e86bf
[libfirm] / ir / be / ia32 / ia32_emitter.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 file implements the ia32 node emitter.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @version     $Id$
25  *
26  * Summary table for x86 floatingpoint compares:
27  *   pnc_Eq  => !P && E
28  *   pnc_Lt  => !P && B
29  *   pnc_Le  => !P && BE
30  *   pnc_Gt  => A
31  *   pnc_Ge  => AE
32  *   pnc_Lg  => P || NE
33  *   pnc_Leg => NP  (ordered)
34  *   pnc_Uo  => P
35  *   pnc_Ue  => E
36  *   pnc_Ul  => B
37  *   pnc_Ule => BE
38  *   pnc_Ug  => P || A
39  *   pnc_Uge => P || AE
40  *   pnc_Ne  => NE
41  */
42 #include "config.h"
43
44 #include <limits.h>
45
46 #include "xmalloc.h"
47 #include "tv.h"
48 #include "iredges.h"
49 #include "debug.h"
50 #include "irgwalk.h"
51 #include "irprintf.h"
52 #include "irop_t.h"
53 #include "irargs_t.h"
54 #include "irprog_t.h"
55 #include "iredges_t.h"
56 #include "irtools.h"
57 #include "execfreq.h"
58 #include "error.h"
59 #include "raw_bitset.h"
60 #include "dbginfo.h"
61 #include "lc_opts.h"
62
63 #include "../besched.h"
64 #include "../benode.h"
65 #include "../beabi.h"
66 #include "../be_dbgout.h"
67 #include "../beemitter.h"
68 #include "../begnuas.h"
69 #include "../beirg.h"
70 #include "../be_dbgout.h"
71
72 #include "ia32_emitter.h"
73 #include "gen_ia32_emitter.h"
74 #include "gen_ia32_regalloc_if.h"
75 #include "ia32_nodes_attr.h"
76 #include "ia32_new_nodes.h"
77 #include "ia32_map_regs.h"
78 #include "ia32_architecture.h"
79 #include "bearch_ia32_t.h"
80
81 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
82
83 #define BLOCK_PREFIX ".L"
84
85 #define SNPRINTF_BUF_LEN 128
86
87 static const ia32_isa_t *isa;
88 static ia32_code_gen_t  *cg;
89 static char              pic_base_label[128];
90 static ir_label_t        exc_label_id;
91 static int               mark_spill_reload = 0;
92 static int               do_pic;
93
94 /** Return the next block in Block schedule */
95 static ir_node *get_prev_block_sched(const ir_node *block)
96 {
97         return get_irn_link(block);
98 }
99
100 /** Checks if the current block is a fall-through target. */
101 static int is_fallthrough(const ir_node *cfgpred)
102 {
103         ir_node *pred;
104
105         if (!is_Proj(cfgpred))
106                 return 1;
107         pred = get_Proj_pred(cfgpred);
108         if (is_ia32_SwitchJmp(pred))
109                 return 0;
110
111         return 1;
112 }
113
114 /**
115  * returns non-zero if the given block needs a label
116  * because of being a jump-target (and not a fall-through)
117  */
118 static int block_needs_label(const ir_node *block)
119 {
120         int need_label = 1;
121         int  n_cfgpreds = get_Block_n_cfgpreds(block);
122
123         if (has_Block_entity(block))
124                 return 1;
125
126         if (n_cfgpreds == 0) {
127                 need_label = 0;
128         } else if (n_cfgpreds == 1) {
129                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
130                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
131
132                 if (get_prev_block_sched(block) == cfgpred_block
133                                 && is_fallthrough(cfgpred)) {
134                         need_label = 0;
135                 }
136         }
137
138         return need_label;
139 }
140
141 /**
142  * Returns the register at in position pos.
143  */
144 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
145 {
146         ir_node               *op;
147         const arch_register_t *reg = NULL;
148
149         assert(get_irn_arity(irn) > pos && "Invalid IN position");
150
151         /* The out register of the operator at position pos is the
152            in register we need. */
153         op = get_irn_n(irn, pos);
154
155         reg = arch_get_irn_register(op);
156
157         assert(reg && "no in register found");
158
159         if (reg == &ia32_gp_regs[REG_GP_NOREG])
160                 panic("trying to emit noreg for %+F input %d", irn, pos);
161
162         /* in case of unknown register: just return a valid register */
163         if (reg == &ia32_gp_regs[REG_GP_UKNWN]) {
164                 const arch_register_req_t *req = arch_get_register_req(irn, pos);
165
166                 if (arch_register_req_is(req, limited)) {
167                         /* in case of limited requirements: get the first allowed register */
168                         unsigned idx = rbitset_next(req->limited, 0, 1);
169                         reg = arch_register_for_index(req->cls, idx);
170                 } else {
171                         /* otherwise get first register in class */
172                         reg = arch_register_for_index(req->cls, 0);
173                 }
174         }
175
176         return reg;
177 }
178
179 /**
180  * Returns the register at out position pos.
181  */
182 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
183 {
184         ir_node               *proj;
185         const arch_register_t *reg = NULL;
186
187         /* 1st case: irn is not of mode_T, so it has only                 */
188         /*           one OUT register -> good                             */
189         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
190         /*           Proj with the corresponding projnum for the register */
191
192         if (get_irn_mode(irn) != mode_T) {
193                 assert(pos == 0);
194                 reg = arch_get_irn_register(irn);
195         } else if (is_ia32_irn(irn)) {
196                 reg = arch_irn_get_register(irn, pos);
197         } else {
198                 const ir_edge_t *edge;
199
200                 foreach_out_edge(irn, edge) {
201                         proj = get_edge_src_irn(edge);
202                         assert(is_Proj(proj) && "non-Proj from mode_T node");
203                         if (get_Proj_proj(proj) == pos) {
204                                 reg = arch_get_irn_register(proj);
205                                 break;
206                         }
207                 }
208         }
209
210         assert(reg && "no out register found");
211         return reg;
212 }
213
214 /**
215  * Add a number to a prefix. This number will not be used a second time.
216  */
217 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
218 {
219         static unsigned long id = 0;
220         snprintf(buf, buflen, "%s%lu", prefix, ++id);
221         return buf;
222 }
223
224 /*************************************************************
225  *             _       _    __   _          _
226  *            (_)     | |  / _| | |        | |
227  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
228  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
229  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
230  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
231  * | |                                       | |
232  * |_|                                       |_|
233  *************************************************************/
234
235 /**
236  * Emit the name of the 8bit low register
237  */
238 static void emit_8bit_register(const arch_register_t *reg)
239 {
240         const char *reg_name = arch_register_get_name(reg);
241
242         be_emit_char('%');
243         be_emit_char(reg_name[1]);
244         be_emit_char('l');
245 }
246
247 /**
248  * Emit the name of the 8bit high register
249  */
250 static void emit_8bit_register_high(const arch_register_t *reg)
251 {
252         const char *reg_name = arch_register_get_name(reg);
253
254         be_emit_char('%');
255         be_emit_char(reg_name[1]);
256         be_emit_char('h');
257 }
258
259 static void emit_16bit_register(const arch_register_t *reg)
260 {
261         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
262
263         be_emit_char('%');
264         be_emit_string(reg_name);
265 }
266
267 /**
268  * emit a register, possible shortened by a mode
269  *
270  * @param reg   the register
271  * @param mode  the mode of the register or NULL for full register
272  */
273 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
274 {
275         const char *reg_name;
276
277         if (mode != NULL) {
278                 int size = get_mode_size_bits(mode);
279                 switch (size) {
280                         case  8: emit_8bit_register(reg);  return;
281                         case 16: emit_16bit_register(reg); return;
282                 }
283                 assert(mode_is_float(mode) || size == 32);
284         }
285
286         reg_name = arch_register_get_name(reg);
287
288         be_emit_char('%');
289         be_emit_string(reg_name);
290 }
291
292 void ia32_emit_source_register(const ir_node *node, int pos)
293 {
294         const arch_register_t *reg = get_in_reg(node, pos);
295
296         emit_register(reg, NULL);
297 }
298
299 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
300 {
301         be_gas_emit_entity(entity);
302
303         if (get_entity_owner(entity) == get_tls_type()) {
304                 if (get_entity_visibility(entity) == ir_visibility_external) {
305                         be_emit_cstring("@INDNTPOFF");
306                 } else {
307                         be_emit_cstring("@NTPOFF");
308                 }
309         }
310
311         if (do_pic && !no_pic_adjust) {
312                 be_emit_char('-');
313                 be_emit_string(pic_base_label);
314         }
315 }
316
317 static void emit_ia32_Immediate_no_prefix(const ir_node *node)
318 {
319         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
320
321         if (attr->symconst != NULL) {
322                 if (attr->sc_sign)
323                         be_emit_char('-');
324                 ia32_emit_entity(attr->symconst, attr->no_pic_adjust);
325         }
326         if (attr->symconst == NULL || attr->offset != 0) {
327                 if (attr->symconst != NULL) {
328                         be_emit_irprintf("%+d", attr->offset);
329                 } else {
330                         be_emit_irprintf("0x%X", attr->offset);
331                 }
332         }
333 }
334
335 static void emit_ia32_Immediate(const ir_node *node)
336 {
337         be_emit_char('$');
338         emit_ia32_Immediate_no_prefix(node);
339 }
340
341 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
342 {
343         const arch_register_t *reg;
344         const ir_node         *in = get_irn_n(node, pos);
345         if (is_ia32_Immediate(in)) {
346                 emit_ia32_Immediate(in);
347                 return;
348         }
349
350         reg = get_in_reg(node, pos);
351         emit_8bit_register(reg);
352 }
353
354 void ia32_emit_8bit_high_source_register(const ir_node *node, int pos)
355 {
356         const arch_register_t *reg = get_in_reg(node, pos);
357         emit_8bit_register_high(reg);
358 }
359
360 void ia32_emit_16bit_source_register_or_immediate(const ir_node *node, int pos)
361 {
362         const arch_register_t *reg;
363         const ir_node         *in = get_irn_n(node, pos);
364         if (is_ia32_Immediate(in)) {
365                 emit_ia32_Immediate(in);
366                 return;
367         }
368
369         reg = get_in_reg(node, pos);
370         emit_16bit_register(reg);
371 }
372
373 void ia32_emit_dest_register(const ir_node *node, int pos)
374 {
375         const arch_register_t *reg  = get_out_reg(node, pos);
376
377         emit_register(reg, NULL);
378 }
379
380 void ia32_emit_dest_register_size(const ir_node *node, int pos)
381 {
382         const arch_register_t *reg  = get_out_reg(node, pos);
383
384         emit_register(reg, get_ia32_ls_mode(node));
385 }
386
387 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
388 {
389         const arch_register_t *reg  = get_out_reg(node, pos);
390
391         emit_register(reg, mode_Bu);
392 }
393
394 void ia32_emit_x87_register(const ir_node *node, int pos)
395 {
396         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
397
398         assert(pos < 3);
399         be_emit_char('%');
400         be_emit_string(attr->x87[pos]->name);
401 }
402
403 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
404 {
405         assert(mode_is_int(mode) || mode_is_reference(mode));
406         switch (get_mode_size_bits(mode)) {
407                 case 8:  be_emit_char('b');     return;
408                 case 16: be_emit_char('w');     return;
409                 case 32: be_emit_char('l');     return;
410                 /* gas docu says q is the suffix but gcc, objdump and icc use ll
411                  * apparently */
412                 case 64: be_emit_cstring("ll"); return;
413         }
414         panic("Can't output mode_suffix for %+F", mode);
415 }
416
417 void ia32_emit_mode_suffix(const ir_node *node)
418 {
419         ir_mode *mode = get_ia32_ls_mode(node);
420         if (mode == NULL)
421                 mode = mode_Iu;
422
423         ia32_emit_mode_suffix_mode(mode);
424 }
425
426 void ia32_emit_x87_mode_suffix(const ir_node *node)
427 {
428         ir_mode *mode;
429
430         /* we only need to emit the mode on address mode */
431         if (get_ia32_op_type(node) == ia32_Normal)
432                 return;
433
434         mode = get_ia32_ls_mode(node);
435         assert(mode != NULL);
436
437         if (mode_is_float(mode)) {
438                 switch (get_mode_size_bits(mode)) {
439                         case 32: be_emit_char('s'); return;
440                         case 64: be_emit_char('l'); return;
441                         case 80:
442                         case 96: be_emit_char('t'); return;
443                 }
444         } else {
445                 assert(mode_is_int(mode));
446                 switch (get_mode_size_bits(mode)) {
447                         case 16: be_emit_char('s');     return;
448                         case 32: be_emit_char('l');     return;
449                         /* gas docu says q is the suffix but gcc, objdump and icc use ll
450                          * apparently */
451                         case 64: be_emit_cstring("ll"); return;
452                 }
453         }
454         panic("Can't output mode_suffix for %+F", mode);
455 }
456
457 static char get_xmm_mode_suffix(ir_mode *mode)
458 {
459         assert(mode_is_float(mode));
460         switch(get_mode_size_bits(mode)) {
461         case 32: return 's';
462         case 64: return 'd';
463         default: panic("Invalid XMM mode");
464         }
465 }
466
467 void ia32_emit_xmm_mode_suffix(const ir_node *node)
468 {
469         ir_mode *mode = get_ia32_ls_mode(node);
470         assert(mode != NULL);
471         be_emit_char('s');
472         be_emit_char(get_xmm_mode_suffix(mode));
473 }
474
475 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
476 {
477         ir_mode *mode = get_ia32_ls_mode(node);
478         assert(mode != NULL);
479         be_emit_char(get_xmm_mode_suffix(mode));
480 }
481
482 void ia32_emit_extend_suffix(const ir_node *node)
483 {
484         ir_mode *mode = get_ia32_ls_mode(node);
485         if (get_mode_size_bits(mode) == 32)
486                 return;
487         be_emit_char(mode_is_signed(mode) ? 's' : 'z');
488         ia32_emit_mode_suffix_mode(mode);
489 }
490
491 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
492 {
493         ir_node *in = get_irn_n(node, pos);
494         if (is_ia32_Immediate(in)) {
495                 emit_ia32_Immediate(in);
496         } else {
497                 const ir_mode         *mode = get_ia32_ls_mode(node);
498                 const arch_register_t *reg  = get_in_reg(node, pos);
499                 emit_register(reg, mode);
500         }
501 }
502
503 /**
504  * Returns the target block for a control flow node.
505  */
506 static ir_node *get_cfop_target_block(const ir_node *irn)
507 {
508         assert(get_irn_mode(irn) == mode_X);
509         return get_irn_link(irn);
510 }
511
512 /**
513  * Emits a block label for the given block.
514  */
515 static void ia32_emit_block_name(const ir_node *block)
516 {
517         if (has_Block_entity(block)) {
518                 ir_entity *entity = get_Block_entity(block);
519                 be_gas_emit_entity(entity);
520         } else {
521                 be_emit_cstring(BLOCK_PREFIX);
522                 be_emit_irprintf("%ld", get_irn_node_nr(block));
523         }
524 }
525
526 /**
527  * Emits the target label for a control flow node.
528  */
529 static void ia32_emit_cfop_target(const ir_node *node)
530 {
531         ir_node *block = get_cfop_target_block(node);
532         ia32_emit_block_name(block);
533 }
534
535 /*
536  * positive conditions for signed compares
537  */
538 static const char *const cmp2condition_s[] = {
539         NULL, /* always false */
540         "e",  /* == */
541         "l",  /* <  */
542         "le", /* <= */
543         "g",  /* >  */
544         "ge", /* >= */
545         "ne", /* != */
546         NULL  /* always true */
547 };
548
549 /*
550  * positive conditions for unsigned compares
551  */
552 static const char *const cmp2condition_u[] = {
553         NULL, /* always false */
554         "e",  /* == */
555         "b",  /* <  */
556         "be", /* <= */
557         "a",  /* >  */
558         "ae", /* >= */
559         "ne", /* != */
560         NULL  /* always true */
561 };
562
563 /**
564  * Emit the suffix for a compare instruction.
565  */
566 static void ia32_emit_cmp_suffix(int pnc)
567 {
568         const char *str;
569
570         if (pnc == ia32_pn_Cmp_parity) {
571                 be_emit_char('p');
572                 return;
573         }
574
575         if (pnc & ia32_pn_Cmp_float || pnc & ia32_pn_Cmp_unsigned) {
576                 str = cmp2condition_u[pnc & 7];
577         } else {
578                 str = cmp2condition_s[pnc & 7];
579         }
580
581         be_emit_string(str);
582 }
583
584 typedef enum ia32_emit_mod_t {
585         EMIT_RESPECT_LS   = 1U << 0,
586         EMIT_ALTERNATE_AM = 1U << 1,
587         EMIT_LONG         = 1U << 2,
588         EMIT_HIGH_REG     = 1U << 3,
589         EMIT_LOW_REG      = 1U << 4
590 } ia32_emit_mod_t;
591
592 /**
593  * Emits address mode.
594  */
595 void ia32_emit_am(const ir_node *node)
596 {
597         ir_entity *ent       = get_ia32_am_sc(node);
598         int        offs      = get_ia32_am_offs_int(node);
599         ir_node   *base      = get_irn_n(node, n_ia32_base);
600         int        has_base  = !is_ia32_NoReg_GP(base);
601         ir_node   *index     = get_irn_n(node, n_ia32_index);
602         int        has_index = !is_ia32_NoReg_GP(index);
603
604         /* just to be sure... */
605         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
606
607         /* emit offset */
608         if (ent != NULL) {
609                 const ia32_attr_t *attr = get_ia32_attr_const(node);
610                 if (is_ia32_am_sc_sign(node))
611                         be_emit_char('-');
612                 ia32_emit_entity(ent, attr->data.am_sc_no_pic_adjust);
613         }
614
615         /* also handle special case if nothing is set */
616         if (offs != 0 || (ent == NULL && !has_base && !has_index)) {
617                 if (ent != NULL) {
618                         be_emit_irprintf("%+d", offs);
619                 } else {
620                         be_emit_irprintf("%d", offs);
621                 }
622         }
623
624         if (has_base || has_index) {
625                 be_emit_char('(');
626
627                 /* emit base */
628                 if (has_base) {
629                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
630                         emit_register(reg, NULL);
631                 }
632
633                 /* emit index + scale */
634                 if (has_index) {
635                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
636                         int scale;
637                         be_emit_char(',');
638                         emit_register(reg, NULL);
639
640                         scale = get_ia32_am_scale(node);
641                         if (scale > 0) {
642                                 be_emit_irprintf(",%d", 1 << scale);
643                         }
644                 }
645                 be_emit_char(')');
646         }
647 }
648
649 /**
650  * fmt  parameter               output
651  * ---- ----------------------  ---------------------------------------------
652  * %%                           %
653  * %AM  <node>                  address mode of the node
654  * %AR  const arch_register_t*  address mode of the node or register
655  * %ASx <node>                  address mode of the node or source register x
656  * %Dx  <node>                  destination register x
657  * %I   <node>                  immediate of the node
658  * %L   <node>                  control flow target of the node
659  * %M   <node>                  mode suffix of the node
660  * %P   int                     condition code
661  * %R   const arch_register_t*  register
662  * %Sx  <node>                  source register x
663  * %s   const char*             string
664  * %u   unsigned int            unsigned int
665  * %d   signed int              signed int
666  *
667  * x starts at 0
668  * # modifier for %ASx, %D, %R, and %S uses ls mode of node to alter register width
669  * * modifier does not prefix immediates with $, but AM with *
670  * l modifier for %lu and %ld
671  * > modifier to output high 8bit register (ah, bh)
672  * < modifier to output low 8bit register (al, bl)
673  */
674 static void ia32_emitf(const ir_node *node, const char *fmt, ...)
675 {
676         va_list ap;
677         va_start(ap, fmt);
678
679         for (;;) {
680                 const char      *start = fmt;
681                 ia32_emit_mod_t  mod   = 0;
682
683                 while (*fmt != '%' && *fmt != '\n' && *fmt != '\0')
684                         ++fmt;
685                 if (fmt != start) {
686                         be_emit_string_len(start, fmt - start);
687                 }
688
689                 if (*fmt == '\n') {
690                         be_emit_finish_line_gas(node);
691                         ++fmt;
692                         if (*fmt == '\0')
693                                 break;
694                         continue;
695                 }
696
697                 if (*fmt == '\0')
698                         break;
699
700                 ++fmt;
701                 while (1) {
702                         switch(*fmt) {
703                         case '*': mod |= EMIT_ALTERNATE_AM; break;
704                         case '#': mod |= EMIT_RESPECT_LS;   break;
705                         case 'l': mod |= EMIT_LONG;         break;
706                         case '>': mod |= EMIT_HIGH_REG;     break;
707                         case '<': mod |= EMIT_LOW_REG;      break;
708                         default:
709                                 goto end_of_mods;
710                         }
711                         ++fmt;
712                 }
713 end_of_mods:
714
715                 switch (*fmt++) {
716                         case '%':
717                                 be_emit_char('%');
718                                 break;
719
720                         case 'A': {
721                                 switch (*fmt++) {
722 emit_AM:
723                                         case 'M':
724                                                 if (mod & EMIT_ALTERNATE_AM)
725                                                         be_emit_char('*');
726                                                 ia32_emit_am(node);
727                                                 break;
728
729                                         case 'R': {
730                                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
731                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
732                                                         goto emit_AM;
733                                                 } else {
734                                                         if (mod & EMIT_ALTERNATE_AM)
735                                                                 be_emit_char('*');
736                                                         emit_register(reg, NULL);
737                                                 }
738                                                 break;
739                                         }
740
741                                         case 'S':
742                                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
743                                                         ++fmt;
744                                                         goto emit_AM;
745                                                 } else {
746                                                         assert(get_ia32_op_type(node) == ia32_Normal);
747                                                         goto emit_S;
748                                                 }
749                                                 break;
750
751                                         default: goto unknown;
752                                 }
753                                 break;
754                         }
755
756                         case 'D': {
757                                 unsigned               pos;
758                                 const arch_register_t *reg;
759
760                                 if (*fmt < '0' || '9' <= *fmt)
761                                         goto unknown;
762
763                                 pos = *fmt++ - '0';
764                                 reg = get_out_reg(node, pos);
765                                 emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
766                                 break;
767                         }
768
769                         case 'I':
770                                 if (!(mod & EMIT_ALTERNATE_AM))
771                                         be_emit_char('$');
772                                 emit_ia32_Immediate_no_prefix(node);
773                                 break;
774
775                         case 'L':
776                                 ia32_emit_cfop_target(node);
777                                 break;
778
779                         case 'M': {
780                                 ia32_emit_mode_suffix_mode(get_ia32_ls_mode(node));
781                                 break;
782                         }
783
784                         case 'P': {
785                                 int pnc = va_arg(ap, int);
786                                 ia32_emit_cmp_suffix(pnc);
787                                 break;
788                         }
789
790                         case 'R': {
791                                 const arch_register_t *reg = va_arg(ap, const arch_register_t*);
792                                 if (mod & EMIT_HIGH_REG) {
793                                         emit_8bit_register_high(reg);
794                                 } else if (mod & EMIT_LOW_REG) {
795                                         emit_8bit_register(reg);
796                                 } else {
797                                         emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
798                                 }
799                                 break;
800                         }
801
802 emit_S:
803                         case 'S': {
804                                 unsigned       pos;
805                                 const ir_node *in;
806
807                                 if (*fmt < '0' || '9' <= *fmt)
808                                         goto unknown;
809
810                                 pos = *fmt++ - '0';
811                                 in  = get_irn_n(node, pos);
812                                 if (is_ia32_Immediate(in)) {
813                                         if (!(mod & EMIT_ALTERNATE_AM))
814                                                 be_emit_char('$');
815                                         emit_ia32_Immediate_no_prefix(in);
816                                 } else {
817                                         const arch_register_t *reg;
818
819                                         if (mod & EMIT_ALTERNATE_AM)
820                                                 be_emit_char('*');
821                                         reg = get_in_reg(node, pos);
822                                         emit_register(reg, mod & EMIT_RESPECT_LS ? get_ia32_ls_mode(node) : NULL);
823                                 }
824                                 break;
825                         }
826
827                         case 's': {
828                                 const char *str = va_arg(ap, const char*);
829                                 be_emit_string(str);
830                                 break;
831                         }
832
833                         case 'u':
834                                 if (mod & EMIT_LONG) {
835                                         unsigned long num = va_arg(ap, unsigned long);
836                                         be_emit_irprintf("%lu", num);
837                                 } else {
838                                         unsigned num = va_arg(ap, unsigned);
839                                         be_emit_irprintf("%u", num);
840                                 }
841                                 break;
842
843                         case 'd':
844                                 if (mod & EMIT_LONG) {
845                                         long num = va_arg(ap, long);
846                                         be_emit_irprintf("%ld", num);
847                                 } else {
848                                         int num = va_arg(ap, int);
849                                         be_emit_irprintf("%d", num);
850                                 }
851                                 break;
852
853                         default:
854 unknown:
855                                 panic("unknown format conversion in ia32_emitf()");
856                 }
857         }
858
859         va_end(ap);
860 }
861
862 /**
863  * Emits registers and/or address mode of a binary operation.
864  */
865 void ia32_emit_binop(const ir_node *node)
866 {
867         if (is_ia32_Immediate(get_irn_n(node, n_ia32_binary_right))) {
868                 ia32_emitf(node, "%#S4, %#AS3");
869         } else {
870                 ia32_emitf(node, "%#AS4, %#S3");
871         }
872 }
873
874 /**
875  * Emits registers and/or address mode of a binary operation.
876  */
877 void ia32_emit_x87_binop(const ir_node *node)
878 {
879         switch(get_ia32_op_type(node)) {
880                 case ia32_Normal:
881                         {
882                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
883                                 const arch_register_t *in1      = x87_attr->x87[0];
884                                 const arch_register_t *in       = x87_attr->x87[1];
885                                 const arch_register_t *out      = x87_attr->x87[2];
886
887                                 if (out == NULL) {
888                                         out = in1;
889                                 } else if (out == in) {
890                                         in = in1;
891                                 }
892
893                                 be_emit_char('%');
894                                 be_emit_string(arch_register_get_name(in));
895                                 be_emit_cstring(", %");
896                                 be_emit_string(arch_register_get_name(out));
897                         }
898                         break;
899                 case ia32_AddrModeS:
900                         ia32_emit_am(node);
901                         break;
902                 case ia32_AddrModeD:
903                 default:
904                         assert(0 && "unsupported op type");
905         }
906 }
907
908 /**
909  * Emits registers and/or address mode of a unary operation.
910  */
911 void ia32_emit_unop(const ir_node *node, int pos)
912 {
913         char fmt[] = "%ASx";
914         fmt[3] = '0' + pos;
915         ia32_emitf(node, fmt);
916 }
917
918 static void emit_ia32_IMul(const ir_node *node)
919 {
920         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
921         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
922
923         /* do we need the 3-address form? */
924         if (is_ia32_NoReg_GP(left) ||
925                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
926                 ia32_emitf(node, "\timul%M %#S4, %#AS3, %#D0\n");
927         } else {
928                 ia32_emitf(node, "\timul%M %#AS4, %#S3\n");
929         }
930 }
931
932 /**
933  * walks up a tree of copies/perms/spills/reloads to find the original value
934  * that is moved around
935  */
936 static ir_node *find_original_value(ir_node *node)
937 {
938         if (irn_visited(node))
939                 return NULL;
940
941         mark_irn_visited(node);
942         if (be_is_Copy(node)) {
943                 return find_original_value(be_get_Copy_op(node));
944         } else if (be_is_CopyKeep(node)) {
945                 return find_original_value(be_get_CopyKeep_op(node));
946         } else if (is_Proj(node)) {
947                 ir_node *pred = get_Proj_pred(node);
948                 if (be_is_Perm(pred)) {
949                         return find_original_value(get_irn_n(pred, get_Proj_proj(node)));
950                 } else if (be_is_MemPerm(pred)) {
951                         return find_original_value(get_irn_n(pred, get_Proj_proj(node) + 1));
952                 } else if (is_ia32_Load(pred)) {
953                         return find_original_value(get_irn_n(pred, n_ia32_Load_mem));
954                 } else {
955                         return node;
956                 }
957         } else if (is_ia32_Store(node)) {
958                 return find_original_value(get_irn_n(node, n_ia32_Store_val));
959         } else if (is_Phi(node)) {
960                 int i, arity;
961                 arity = get_irn_arity(node);
962                 for (i = 0; i < arity; ++i) {
963                         ir_node *in  = get_irn_n(node, i);
964                         ir_node *res = find_original_value(in);
965
966                         if (res != NULL)
967                                 return res;
968                 }
969                 return NULL;
970         } else {
971                 return node;
972         }
973 }
974
975 static int determine_final_pnc(const ir_node *node, int flags_pos, int pnc)
976 {
977         ir_node           *flags = get_irn_n(node, flags_pos);
978         const ia32_attr_t *flags_attr;
979         flags = skip_Proj(flags);
980
981         if (is_ia32_Sahf(flags)) {
982                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
983                 if (!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
984                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
985                         inc_irg_visited(current_ir_graph);
986                         cmp = find_original_value(cmp);
987                         assert(cmp != NULL);
988                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
989                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
990                 }
991
992                 flags_attr = get_ia32_attr_const(cmp);
993                 if (flags_attr->data.ins_permuted)
994                         pnc = get_mirrored_pnc(pnc);
995                 pnc |= ia32_pn_Cmp_float;
996         } else if (is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
997                         || is_ia32_Fucompi(flags)) {
998                 flags_attr = get_ia32_attr_const(flags);
999
1000                 if (flags_attr->data.ins_permuted)
1001                         pnc = get_mirrored_pnc(pnc);
1002                 pnc |= ia32_pn_Cmp_float;
1003         } else {
1004                 flags_attr = get_ia32_attr_const(flags);
1005
1006                 if (flags_attr->data.ins_permuted)
1007                         pnc = get_mirrored_pnc(pnc);
1008                 if (flags_attr->data.cmp_unsigned)
1009                         pnc |= ia32_pn_Cmp_unsigned;
1010         }
1011
1012         return pnc;
1013 }
1014
1015 static pn_Cmp ia32_get_negated_pnc(pn_Cmp pnc)
1016 {
1017         ir_mode *mode = pnc & ia32_pn_Cmp_float ? mode_F : mode_Iu;
1018         return get_negated_pnc(pnc, mode);
1019 }
1020
1021 void ia32_emit_cmp_suffix_node(const ir_node *node, int flags_pos)
1022 {
1023         pn_Cmp pnc = get_ia32_condcode(node);
1024         pnc = determine_final_pnc(node, flags_pos, pnc);
1025
1026         ia32_emit_cmp_suffix(pnc);
1027 }
1028
1029 /**
1030  * Emits an exception label for a given node.
1031  */
1032 static void ia32_emit_exc_label(const ir_node *node)
1033 {
1034         be_emit_string(be_gas_insn_label_prefix());
1035         be_emit_irprintf("%lu", get_ia32_exc_label_id(node));
1036 }
1037
1038 /**
1039  * Returns the Proj with projection number proj and NOT mode_M
1040  */
1041 static ir_node *get_proj(const ir_node *node, long proj)
1042 {
1043         const ir_edge_t *edge;
1044         ir_node         *src;
1045
1046         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
1047
1048         foreach_out_edge(node, edge) {
1049                 src = get_edge_src_irn(edge);
1050
1051                 assert(is_Proj(src) && "Proj expected");
1052                 if (get_irn_mode(src) == mode_M)
1053                         continue;
1054
1055                 if (get_Proj_proj(src) == proj)
1056                         return src;
1057         }
1058         return NULL;
1059 }
1060
1061 static int can_be_fallthrough(const ir_node *node)
1062 {
1063         ir_node *target_block = get_cfop_target_block(node);
1064         ir_node *block        = get_nodes_block(node);
1065         return get_prev_block_sched(target_block) == block;
1066 }
1067
1068 /**
1069  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
1070  */
1071 static void emit_ia32_Jcc(const ir_node *node)
1072 {
1073         int            need_parity_label = 0;
1074         const ir_node *proj_true;
1075         const ir_node *proj_false;
1076         const ir_node *block;
1077         pn_Cmp         pnc = get_ia32_condcode(node);
1078
1079         pnc = determine_final_pnc(node, 0, pnc);
1080
1081         /* get both Projs */
1082         proj_true = get_proj(node, pn_ia32_Jcc_true);
1083         assert(proj_true && "Jcc without true Proj");
1084
1085         proj_false = get_proj(node, pn_ia32_Jcc_false);
1086         assert(proj_false && "Jcc without false Proj");
1087
1088         block      = get_nodes_block(node);
1089
1090         if (can_be_fallthrough(proj_true)) {
1091                 /* exchange both proj's so the second one can be omitted */
1092                 const ir_node *t = proj_true;
1093
1094                 proj_true  = proj_false;
1095                 proj_false = t;
1096                 pnc        = ia32_get_negated_pnc(pnc);
1097         }
1098
1099         if (pnc & ia32_pn_Cmp_float) {
1100                 /* Some floating point comparisons require a test of the parity flag,
1101                  * which indicates that the result is unordered */
1102                 switch (pnc & 0x0f) {
1103                 case pn_Cmp_Uo: {
1104                         ia32_emitf(proj_true, "\tjp %L\n");
1105                         break;
1106                 }
1107
1108                 case pn_Cmp_Leg:
1109                         ia32_emitf(proj_true, "\tjnp %L\n");
1110                         break;
1111
1112                 case pn_Cmp_Eq:
1113                 case pn_Cmp_Lt:
1114                 case pn_Cmp_Le:
1115                         /* we need a local label if the false proj is a fallthrough
1116                          * as the falseblock might have no label emitted then */
1117                         if (can_be_fallthrough(proj_false)) {
1118                                 need_parity_label = 1;
1119                                 ia32_emitf(proj_false, "\tjp 1f\n");
1120                         } else {
1121                                 ia32_emitf(proj_false, "\tjp %L\n");
1122                         }
1123                         goto emit_jcc;
1124
1125                 case pn_Cmp_Ug:
1126                 case pn_Cmp_Uge:
1127                 case pn_Cmp_Ne:
1128                         ia32_emitf(proj_true, "\tjp %L\n");
1129                         goto emit_jcc;
1130
1131                 default:
1132                         goto emit_jcc;
1133                 }
1134         } else {
1135 emit_jcc:
1136                 ia32_emitf(proj_true, "\tj%P %L\n", pnc);
1137         }
1138
1139         if (need_parity_label) {
1140                 ia32_emitf(NULL, "1:\n");
1141         }
1142
1143         /* the second Proj might be a fallthrough */
1144         if (can_be_fallthrough(proj_false)) {
1145                 ia32_emitf(proj_false, "\t/* fallthrough to %L */\n");
1146         } else {
1147                 ia32_emitf(proj_false, "\tjmp %L\n");
1148         }
1149 }
1150
1151 /**
1152  * Emits an ia32 Setcc. This is mostly easy but some floating point compares
1153  * are tricky.
1154  */
1155 static void emit_ia32_Setcc(const ir_node *node)
1156 {
1157         const arch_register_t *dreg = get_out_reg(node, pn_ia32_Setcc_res);
1158
1159         pn_Cmp pnc = get_ia32_condcode(node);
1160         pnc        = determine_final_pnc(node, n_ia32_Setcc_eflags, pnc);
1161         if (pnc & ia32_pn_Cmp_float) {
1162                 switch (pnc & 0x0f) {
1163                 case pn_Cmp_Uo:
1164                         ia32_emitf(node, "\tsetp %#R\n", dreg);
1165                         return;
1166
1167                 case pn_Cmp_Leg:
1168                         ia32_emitf(node, "\tsetnp %#R\n", dreg);
1169                         return;
1170
1171                 case pn_Cmp_Eq:
1172                 case pn_Cmp_Lt:
1173                 case pn_Cmp_Le:
1174                         ia32_emitf(node, "\tset%P %<R\n", pnc, dreg);
1175                         ia32_emitf(node, "\tsetnp %>R\n", dreg);
1176                         ia32_emitf(node, "\tandb %>R, %<R\n", dreg, dreg);
1177                         return;
1178
1179                 case pn_Cmp_Ug:
1180                 case pn_Cmp_Uge:
1181                 case pn_Cmp_Ne:
1182                         ia32_emitf(node, "\tset%P %<R\n", pnc, dreg);
1183                         ia32_emitf(node, "\tsetp %>R\n", dreg);
1184                         ia32_emitf(node, "\torb %>R, %<R\n", dreg, dreg);
1185                         return;
1186
1187                 default:
1188                         break;
1189                 }
1190         }
1191         ia32_emitf(node, "\tset%P %#R\n", pnc, dreg);
1192 }
1193
1194 static void emit_ia32_CMovcc(const ir_node *node)
1195 {
1196         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
1197         const arch_register_t *out          = arch_irn_get_register(node, pn_ia32_res);
1198         pn_Cmp                 pnc          = get_ia32_condcode(node);
1199         const arch_register_t *in_true;
1200         const arch_register_t *in_false;
1201
1202         pnc = determine_final_pnc(node, n_ia32_CMovcc_eflags, pnc);
1203         /* although you can't set ins_permuted in the constructor it might still
1204          * be set by memory operand folding
1205          * Permuting inputs of a cmov means the condition is negated!
1206          */
1207         if (attr->data.ins_permuted)
1208                 pnc = ia32_get_negated_pnc(pnc);
1209
1210         in_true  = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_true));
1211         in_false = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_false));
1212
1213         /* should be same constraint fullfilled? */
1214         if (out == in_false) {
1215                 /* yes -> nothing to do */
1216         } else if (out == in_true) {
1217                 const arch_register_t *tmp;
1218
1219                 assert(get_ia32_op_type(node) == ia32_Normal);
1220
1221                 pnc = ia32_get_negated_pnc(pnc);
1222
1223                 tmp      = in_true;
1224                 in_true  = in_false;
1225                 in_false = tmp;
1226         } else {
1227                 /* we need a mov */
1228                 ia32_emitf(node, "\tmovl %R, %R\n", in_false, out);
1229         }
1230
1231         /* TODO: handling of Nans isn't correct yet */
1232         if (pnc & ia32_pn_Cmp_float) {
1233                 switch (pnc & 0x0f) {
1234                 case pn_Cmp_Uo:
1235                 case pn_Cmp_Leg:
1236                 case pn_Cmp_Eq:
1237                 case pn_Cmp_Lt:
1238                 case pn_Cmp_Le:
1239                 case pn_Cmp_Ug:
1240                 case pn_Cmp_Uge:
1241                 case pn_Cmp_Ne:
1242                         panic("CMov with floatingpoint compare/parity not supported yet");
1243                 }
1244         }
1245
1246         ia32_emitf(node, "\tcmov%P %#AR, %#R\n", pnc, in_true, out);
1247 }
1248
1249 /*********************************************************
1250  *                 _ _       _
1251  *                (_) |     (_)
1252  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
1253  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
1254  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
1255  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
1256  *                         _/ |               | |
1257  *                        |__/                |_|
1258  *********************************************************/
1259
1260 /* jump table entry (target and corresponding number) */
1261 typedef struct _branch_t {
1262         ir_node *target;
1263         int      value;
1264 } branch_t;
1265
1266 /* jump table for switch generation */
1267 typedef struct _jmp_tbl_t {
1268         ir_node  *defProj;                 /**< default target */
1269         long      min_value;               /**< smallest switch case */
1270         long      max_value;               /**< largest switch case */
1271         long      num_branches;            /**< number of jumps */
1272         char      label[SNPRINTF_BUF_LEN]; /**< label of the jump table */
1273         branch_t *branches;                /**< jump array */
1274 } jmp_tbl_t;
1275
1276 /**
1277  * Compare two variables of type branch_t. Used to sort all switch cases
1278  */
1279 static int ia32_cmp_branch_t(const void *a, const void *b)
1280 {
1281         branch_t *b1 = (branch_t *)a;
1282         branch_t *b2 = (branch_t *)b;
1283
1284         if (b1->value <= b2->value)
1285                 return -1;
1286         else
1287                 return 1;
1288 }
1289
1290 static void generate_jump_table(jmp_tbl_t *tbl, const ir_node *node)
1291 {
1292         int                 i;
1293         long                pnc;
1294         long                default_pn;
1295         ir_node            *proj;
1296         const ir_edge_t    *edge;
1297
1298         /* fill the table structure */
1299         get_unique_label(tbl->label, SNPRINTF_BUF_LEN, ".TBL_");
1300         tbl->defProj      = NULL;
1301         tbl->num_branches = get_irn_n_edges(node) - 1;
1302         tbl->branches     = XMALLOCNZ(branch_t, tbl->num_branches);
1303         tbl->min_value    = LONG_MAX;
1304         tbl->max_value    = LONG_MIN;
1305
1306         default_pn = get_ia32_condcode(node);
1307         i = 0;
1308         /* go over all proj's and collect them */
1309         foreach_out_edge(node, edge) {
1310                 proj = get_edge_src_irn(edge);
1311                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1312
1313                 pnc = get_Proj_proj(proj);
1314
1315                 /* check for default proj */
1316                 if (pnc == default_pn) {
1317                         assert(tbl->defProj == NULL && "found two default Projs at SwitchJmp");
1318                         tbl->defProj = proj;
1319                 } else {
1320                         tbl->min_value = pnc < tbl->min_value ? pnc : tbl->min_value;
1321                         tbl->max_value = pnc > tbl->max_value ? pnc : tbl->max_value;
1322
1323                         /* create branch entry */
1324                         tbl->branches[i].target = proj;
1325                         tbl->branches[i].value  = pnc;
1326                         ++i;
1327                 }
1328
1329         }
1330         assert(i == tbl->num_branches);
1331
1332         /* sort the branches by their number */
1333         qsort(tbl->branches, tbl->num_branches, sizeof(tbl->branches[0]), ia32_cmp_branch_t);
1334 }
1335
1336 /**
1337  * Emits code for a SwitchJmp (creates a jump table if
1338  * possible otherwise a cmp-jmp cascade). Port from
1339  * cggg ia32 backend
1340  */
1341 static void emit_ia32_SwitchJmp(const ir_node *node)
1342 {
1343         unsigned long       interval;
1344         int                 last_value, i;
1345         jmp_tbl_t           tbl;
1346
1347         /* fill the table structure */
1348         generate_jump_table(&tbl, node);
1349
1350         /* two-complement's magic make this work without overflow */
1351         interval = tbl.max_value - tbl.min_value;
1352
1353         /* emit the table */
1354         ia32_emitf(node,        "\tcmpl $%u, %S0\n", interval);
1355         ia32_emitf(tbl.defProj, "\tja %L\n");
1356
1357         if (tbl.num_branches > 1) {
1358                 /* create table */
1359                 ia32_emitf(node, "\tjmp *%s(,%S0,4)\n", tbl.label);
1360
1361                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1362                 ia32_emitf(NULL, "\t.align 4\n");
1363                 ia32_emitf(NULL, "%s:\n", tbl.label);
1364
1365                 last_value = tbl.branches[0].value;
1366                 for (i = 0; i != tbl.num_branches; ++i) {
1367                         while (last_value != tbl.branches[i].value) {
1368                                 ia32_emitf(tbl.defProj, ".long %L\n");
1369                                 ++last_value;
1370                         }
1371                         ia32_emitf(tbl.branches[i].target, ".long %L\n");
1372                         ++last_value;
1373                 }
1374                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1375         } else {
1376                 /* one jump is enough */
1377                 ia32_emitf(tbl.branches[0].target, "\tjmp %L\n");
1378         }
1379
1380         free(tbl.branches);
1381 }
1382
1383 /**
1384  * Emits code for a unconditional jump.
1385  */
1386 static void emit_ia32_Jmp(const ir_node *node)
1387 {
1388         ir_node *block;
1389
1390         /* for now, the code works for scheduled and non-schedules blocks */
1391         block = get_nodes_block(node);
1392
1393         /* we have a block schedule */
1394         if (can_be_fallthrough(node)) {
1395                 ia32_emitf(node, "\t/* fallthrough to %L */\n");
1396         } else {
1397                 ia32_emitf(node, "\tjmp %L\n");
1398         }
1399 }
1400
1401 /**
1402  * Emit an inline assembler operand.
1403  *
1404  * @param node  the ia32_ASM node
1405  * @param s     points to the operand (a %c)
1406  *
1407  * @return  pointer to the first char in s NOT in the current operand
1408  */
1409 static const char* emit_asm_operand(const ir_node *node, const char *s)
1410 {
1411         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1412         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1413                                                             ia32_attr);
1414         const arch_register_t *reg;
1415         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1416         const ia32_asm_reg_t  *asm_reg;
1417         const char            *reg_name;
1418         char                   c;
1419         char                   modifier = 0;
1420         int                    num      = -1;
1421         int                    p;
1422
1423         assert(*s == '%');
1424         c = *(++s);
1425
1426         /* parse modifiers */
1427         switch(c) {
1428         case 0:
1429                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %%\n", node);
1430                 be_emit_char('%');
1431                 return s + 1;
1432         case '%':
1433                 be_emit_char('%');
1434                 return s + 1;
1435         case 'w':
1436         case 'b':
1437         case 'h':
1438                 modifier = c;
1439                 ++s;
1440                 break;
1441         case '0':
1442         case '1':
1443         case '2':
1444         case '3':
1445         case '4':
1446         case '5':
1447         case '6':
1448         case '7':
1449         case '8':
1450         case '9':
1451                 break;
1452         default:
1453                 ir_fprintf(stderr,
1454                                 "Warning: asm text (%+F) contains unknown modifier '%c' for asm op\n",
1455                                 node, c);
1456                 ++s;
1457                 break;
1458         }
1459
1460         /* parse number */
1461         sscanf(s, "%d%n", &num, &p);
1462         if (num < 0) {
1463                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1464                            node);
1465                 return s;
1466         } else {
1467                 s += p;
1468         }
1469
1470         if (num < 0 || ARR_LEN(asm_regs) <= num) {
1471                 ir_fprintf(stderr,
1472                                 "Error: Custom assembler references invalid input/output (%+F)\n",
1473                                 node);
1474                 return s;
1475         }
1476         asm_reg = & asm_regs[num];
1477         assert(asm_reg->valid);
1478
1479         /* get register */
1480         if (asm_reg->use_input == 0) {
1481                 reg = get_out_reg(node, asm_reg->inout_pos);
1482         } else {
1483                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1484
1485                 /* might be an immediate value */
1486                 if (is_ia32_Immediate(pred)) {
1487                         emit_ia32_Immediate(pred);
1488                         return s;
1489                 }
1490                 reg = get_in_reg(node, asm_reg->inout_pos);
1491         }
1492         if (reg == NULL) {
1493                 ir_fprintf(stderr,
1494                                 "Warning: no register assigned for %d asm op (%+F)\n",
1495                                 num, node);
1496                 return s;
1497         }
1498
1499         if (asm_reg->memory) {
1500                 be_emit_char('(');
1501         }
1502
1503         /* emit it */
1504         if (modifier != 0) {
1505                 be_emit_char('%');
1506                 switch(modifier) {
1507                 case 'b':
1508                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1509                         break;
1510                 case 'h':
1511                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1512                         break;
1513                 case 'w':
1514                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1515                         break;
1516                 default:
1517                         panic("Invalid asm op modifier");
1518                 }
1519                 be_emit_string(reg_name);
1520         } else {
1521                 emit_register(reg, asm_reg->mode);
1522         }
1523
1524         if (asm_reg->memory) {
1525                 be_emit_char(')');
1526         }
1527
1528         return s;
1529 }
1530
1531 /**
1532  * Emits code for an ASM pseudo op.
1533  */
1534 static void emit_ia32_Asm(const ir_node *node)
1535 {
1536         const void            *gen_attr = get_irn_generic_attr_const(node);
1537         const ia32_asm_attr_t *attr
1538                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1539         ident                 *asm_text = attr->asm_text;
1540         const char            *s        = get_id_str(asm_text);
1541
1542         ia32_emitf(node, "#APP\t\n");
1543
1544         if (s[0] != '\t')
1545                 be_emit_char('\t');
1546
1547         while(*s != 0) {
1548                 if (*s == '%') {
1549                         s = emit_asm_operand(node, s);
1550                 } else {
1551                         be_emit_char(*s++);
1552                 }
1553         }
1554
1555         ia32_emitf(NULL, "\n#NO_APP\n");
1556 }
1557
1558 /**********************************
1559  *   _____                  ____
1560  *  / ____|                |  _ \
1561  * | |     ___  _ __  _   _| |_) |
1562  * | |    / _ \| '_ \| | | |  _ <
1563  * | |___| (_) | |_) | |_| | |_) |
1564  *  \_____\___/| .__/ \__, |____/
1565  *             | |     __/ |
1566  *             |_|    |___/
1567  **********************************/
1568
1569 /**
1570  * Emit movsb/w instructions to make mov count divideable by 4
1571  */
1572 static void emit_CopyB_prolog(unsigned size)
1573 {
1574         if (size & 1)
1575                 ia32_emitf(NULL, "\tmovsb\n");
1576         if (size & 2)
1577                 ia32_emitf(NULL, "\tmovsw\n");
1578 }
1579
1580 /**
1581  * Emit rep movsd instruction for memcopy.
1582  */
1583 static void emit_ia32_CopyB(const ir_node *node)
1584 {
1585         unsigned size = get_ia32_copyb_size(node);
1586
1587         emit_CopyB_prolog(size);
1588         ia32_emitf(node, "\trep movsd\n");
1589 }
1590
1591 /**
1592  * Emits unrolled memcopy.
1593  */
1594 static void emit_ia32_CopyB_i(const ir_node *node)
1595 {
1596         unsigned size = get_ia32_copyb_size(node);
1597
1598         emit_CopyB_prolog(size);
1599
1600         size >>= 2;
1601         while (size--) {
1602                 ia32_emitf(NULL, "\tmovsd\n");
1603         }
1604 }
1605
1606
1607
1608 /***************************
1609  *   _____
1610  *  / ____|
1611  * | |     ___  _ ____   __
1612  * | |    / _ \| '_ \ \ / /
1613  * | |___| (_) | | | \ V /
1614  *  \_____\___/|_| |_|\_/
1615  *
1616  ***************************/
1617
1618 /**
1619  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1620  */
1621 static void emit_ia32_Conv_with_FP(const ir_node *node, const char* conv_f,
1622                 const char* conv_d)
1623 {
1624         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1625         int                 ls_bits = get_mode_size_bits(ls_mode);
1626         const char         *conv    = ls_bits == 32 ? conv_f : conv_d;
1627
1628         ia32_emitf(node, "\tcvt%s %AS3, %D0\n", conv);
1629 }
1630
1631 static void emit_ia32_Conv_I2FP(const ir_node *node)
1632 {
1633         emit_ia32_Conv_with_FP(node, "si2ss", "si2sd");
1634 }
1635
1636 static void emit_ia32_Conv_FP2I(const ir_node *node)
1637 {
1638         emit_ia32_Conv_with_FP(node, "ss2si", "sd2si");
1639 }
1640
1641 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1642 {
1643         emit_ia32_Conv_with_FP(node, "sd2ss", "ss2sd");
1644 }
1645
1646 /**
1647  * Emits code for an Int conversion.
1648  */
1649 static void emit_ia32_Conv_I2I(const ir_node *node)
1650 {
1651         ir_mode *smaller_mode = get_ia32_ls_mode(node);
1652         int      signed_mode  = mode_is_signed(smaller_mode);
1653         const char *sign_suffix;
1654
1655         assert(!mode_is_float(smaller_mode));
1656
1657         sign_suffix = signed_mode ? "s" : "z";
1658         ia32_emitf(node, "\tmov%s%Ml %#AS3, %D0\n", sign_suffix);
1659 }
1660
1661 /**
1662  * Emits a call
1663  */
1664 static void emit_ia32_Call(const ir_node *node)
1665 {
1666         /* Special case: Call must not have its immediates prefixed by $, instead
1667          * address mode is prefixed by *. */
1668         ia32_emitf(node, "\tcall %*AS3\n");
1669 }
1670
1671
1672 /*******************************************
1673  *  _                          _
1674  * | |                        | |
1675  * | |__   ___ _ __   ___   __| | ___  ___
1676  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1677  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1678  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1679  *
1680  *******************************************/
1681
1682 /**
1683  * Emits code to increase stack pointer.
1684  */
1685 static void emit_be_IncSP(const ir_node *node)
1686 {
1687         int offs = be_get_IncSP_offset(node);
1688
1689         if (offs == 0)
1690                 return;
1691
1692         if (offs > 0) {
1693                 ia32_emitf(node, "\tsubl $%u, %D0\n", offs);
1694         } else {
1695                 ia32_emitf(node, "\taddl $%u, %D0\n", -offs);
1696         }
1697 }
1698
1699 static inline bool is_unknown_reg(const arch_register_t *reg)
1700 {
1701         if(reg == &ia32_gp_regs[REG_GP_UKNWN]
1702                         || reg == &ia32_xmm_regs[REG_XMM_UKNWN]
1703                         || reg == &ia32_vfp_regs[REG_VFP_UKNWN])
1704                 return true;
1705
1706         return false;
1707 }
1708
1709 /**
1710  * Emits code for Copy/CopyKeep.
1711  */
1712 static void Copy_emitter(const ir_node *node, const ir_node *op)
1713 {
1714         const arch_register_t *in  = arch_get_irn_register(op);
1715         const arch_register_t *out = arch_get_irn_register(node);
1716
1717         if (in == out) {
1718                 return;
1719         }
1720         if (is_unknown_reg(in))
1721                 return;
1722         /* copies of vf nodes aren't real... */
1723         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1724                 return;
1725
1726         if (get_irn_mode(node) == mode_E) {
1727                 ia32_emitf(node, "\tmovsd %R, %R\n", in, out);
1728         } else {
1729                 ia32_emitf(node, "\tmovl %R, %R\n", in, out);
1730         }
1731 }
1732
1733 static void emit_be_Copy(const ir_node *node)
1734 {
1735         Copy_emitter(node, be_get_Copy_op(node));
1736 }
1737
1738 static void emit_be_CopyKeep(const ir_node *node)
1739 {
1740         Copy_emitter(node, be_get_CopyKeep_op(node));
1741 }
1742
1743 /**
1744  * Emits code for exchange.
1745  */
1746 static void emit_be_Perm(const ir_node *node)
1747 {
1748         const arch_register_t *in0, *in1;
1749         const arch_register_class_t *cls0, *cls1;
1750
1751         in0 = arch_get_irn_register(get_irn_n(node, 0));
1752         in1 = arch_get_irn_register(get_irn_n(node, 1));
1753
1754         cls0 = arch_register_get_class(in0);
1755         cls1 = arch_register_get_class(in1);
1756
1757         assert(cls0 == cls1 && "Register class mismatch at Perm");
1758
1759         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1760                 ia32_emitf(node, "\txchg %R, %R\n", in1, in0);
1761         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1762                 ia32_emitf(NULL, "\txorpd %R, %R\n", in1, in0);
1763                 ia32_emitf(NULL, "\txorpd %R, %R\n", in0, in1);
1764                 ia32_emitf(node, "\txorpd %R, %R\n", in1, in0);
1765         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1766                 /* is a NOP */
1767         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1768                 /* is a NOP */
1769         } else {
1770                 panic("unexpected register class in be_Perm (%+F)", node);
1771         }
1772 }
1773
1774 /**
1775  * Emits code for Constant loading.
1776  */
1777 static void emit_ia32_Const(const ir_node *node)
1778 {
1779         ia32_emitf(node, "\tmovl %I, %D0\n");
1780 }
1781
1782 /**
1783  * Emits code to load the TLS base
1784  */
1785 static void emit_ia32_LdTls(const ir_node *node)
1786 {
1787         ia32_emitf(node, "\tmovl %%gs:0, %D0\n");
1788 }
1789
1790 /* helper function for emit_ia32_Minus64Bit */
1791 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1792 {
1793         ia32_emitf(node, "\tmovl %R, %R\n", src, dst);
1794 }
1795
1796 /* helper function for emit_ia32_Minus64Bit */
1797 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1798 {
1799         ia32_emitf(node, "\tnegl %R\n", reg);
1800 }
1801
1802 /* helper function for emit_ia32_Minus64Bit */
1803 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1804 {
1805         ia32_emitf(node, "\tsbbl $0, %R\n", reg);
1806 }
1807
1808 /* helper function for emit_ia32_Minus64Bit */
1809 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1810 {
1811         ia32_emitf(node, "\tsbbl %R, %R\n", src, dst);
1812 }
1813
1814 /* helper function for emit_ia32_Minus64Bit */
1815 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1816 {
1817         ia32_emitf(node, "\txchgl %R, %R\n", src, dst);
1818 }
1819
1820 /* helper function for emit_ia32_Minus64Bit */
1821 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1822 {
1823         ia32_emitf(node, "\txorl %R, %R\n", reg, reg);
1824 }
1825
1826 static void emit_ia32_Minus64Bit(const ir_node *node)
1827 {
1828         const arch_register_t *in_lo  = get_in_reg(node, 0);
1829         const arch_register_t *in_hi  = get_in_reg(node, 1);
1830         const arch_register_t *out_lo = get_out_reg(node, 0);
1831         const arch_register_t *out_hi = get_out_reg(node, 1);
1832
1833         if (out_lo == in_lo) {
1834                 if (out_hi != in_hi) {
1835                         /* a -> a, b -> d */
1836                         goto zero_neg;
1837                 } else {
1838                         /* a -> a, b -> b */
1839                         goto normal_neg;
1840                 }
1841         } else if (out_lo == in_hi) {
1842                 if (out_hi == in_lo) {
1843                         /* a -> b, b -> a */
1844                         emit_xchg(node, in_lo, in_hi);
1845                         goto normal_neg;
1846                 } else {
1847                         /* a -> b, b -> d */
1848                         emit_mov(node, in_hi, out_hi);
1849                         emit_mov(node, in_lo, out_lo);
1850                         goto normal_neg;
1851                 }
1852         } else {
1853                 if (out_hi == in_lo) {
1854                         /* a -> c, b -> a */
1855                         emit_mov(node, in_lo, out_lo);
1856                         goto zero_neg;
1857                 } else if (out_hi == in_hi) {
1858                         /* a -> c, b -> b */
1859                         emit_mov(node, in_lo, out_lo);
1860                         goto normal_neg;
1861                 } else {
1862                         /* a -> c, b -> d */
1863                         emit_mov(node, in_lo, out_lo);
1864                         goto zero_neg;
1865                 }
1866         }
1867
1868 normal_neg:
1869         emit_neg( node, out_hi);
1870         emit_neg( node, out_lo);
1871         emit_sbb0(node, out_hi);
1872         return;
1873
1874 zero_neg:
1875         emit_zero(node, out_hi);
1876         emit_neg( node, out_lo);
1877         emit_sbb( node, in_hi, out_hi);
1878 }
1879
1880 static void emit_ia32_GetEIP(const ir_node *node)
1881 {
1882         ia32_emitf(node, "\tcall %s\n", pic_base_label);
1883         ia32_emitf(NULL, "%s:\n", pic_base_label);
1884         ia32_emitf(node, "\tpopl %D0\n");
1885 }
1886
1887 static void emit_ia32_ClimbFrame(const ir_node *node)
1888 {
1889         const ia32_climbframe_attr_t *attr = get_ia32_climbframe_attr_const(node);
1890
1891         ia32_emitf(node, "\tmovl %S0, %D0\n");
1892         ia32_emitf(node, "\tmovl $%u, %S1\n", attr->count);
1893         ia32_emitf(NULL, BLOCK_PREFIX "%ld:\n", get_irn_node_nr(node));
1894         ia32_emitf(node, "\tmovl (%D0), %D0\n");
1895         ia32_emitf(node, "\tdec %S1\n");
1896         ia32_emitf(node, "\tjnz " BLOCK_PREFIX "%ld\n", get_irn_node_nr(node));
1897 }
1898
1899 static void emit_be_Return(const ir_node *node)
1900 {
1901         unsigned pop = be_Return_get_pop(node);
1902
1903         if (pop > 0 || be_Return_get_emit_pop(node)) {
1904                 ia32_emitf(node, "\tret $%u\n", pop);
1905         } else {
1906                 ia32_emitf(node, "\tret\n");
1907         }
1908 }
1909
1910 static void emit_Nothing(const ir_node *node)
1911 {
1912         (void) node;
1913 }
1914
1915
1916 /***********************************************************************************
1917  *                  _          __                                             _
1918  *                 (_)        / _|                                           | |
1919  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1920  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1921  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1922  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1923  *
1924  ***********************************************************************************/
1925
1926 /**
1927  * Enters the emitter functions for handled nodes into the generic
1928  * pointer of an opcode.
1929  */
1930 static void ia32_register_emitters(void)
1931 {
1932 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1933 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1934 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1935 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1936 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1937 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1938
1939         /* first clear the generic function pointer for all ops */
1940         clear_irp_opcodes_generic_func();
1941
1942         /* register all emitter functions defined in spec */
1943         ia32_register_spec_emitters();
1944
1945         /* other ia32 emitter functions */
1946         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1947         IA32_EMIT(Asm);
1948         IA32_EMIT(CMovcc);
1949         IA32_EMIT(Call);
1950         IA32_EMIT(Const);
1951         IA32_EMIT(Conv_FP2FP);
1952         IA32_EMIT(Conv_FP2I);
1953         IA32_EMIT(Conv_I2FP);
1954         IA32_EMIT(Conv_I2I);
1955         IA32_EMIT(CopyB);
1956         IA32_EMIT(CopyB_i);
1957         IA32_EMIT(GetEIP);
1958         IA32_EMIT(IMul);
1959         IA32_EMIT(Jcc);
1960         IA32_EMIT(Setcc);
1961         IA32_EMIT(LdTls);
1962         IA32_EMIT(Minus64Bit);
1963         IA32_EMIT(SwitchJmp);
1964         IA32_EMIT(ClimbFrame);
1965         IA32_EMIT(Jmp);
1966
1967         /* benode emitter */
1968         BE_EMIT(Copy);
1969         BE_EMIT(CopyKeep);
1970         BE_EMIT(IncSP);
1971         BE_EMIT(Perm);
1972         BE_EMIT(Return);
1973
1974         BE_IGN(Barrier);
1975         BE_IGN(Keep);
1976         BE_IGN(Start);
1977
1978         /* firm emitter */
1979         IGN(Phi);
1980
1981 #undef BE_EMIT
1982 #undef EMIT
1983 #undef IGN
1984 #undef IA32_EMIT2
1985 #undef IA32_EMIT
1986 }
1987
1988 typedef void (*emit_func_ptr) (const ir_node *);
1989
1990 /**
1991  * Assign and emit an exception label if the current instruction can fail.
1992  */
1993 static void ia32_assign_exc_label(ir_node *node)
1994 {
1995         /* assign a new ID to the instruction */
1996         set_ia32_exc_label_id(node, ++exc_label_id);
1997         /* print it */
1998         ia32_emit_exc_label(node);
1999         be_emit_char(':');
2000         be_emit_pad_comment();
2001         be_emit_cstring("/* exception to Block ");
2002         ia32_emit_cfop_target(node);
2003         be_emit_cstring(" */\n");
2004         be_emit_write_line();
2005 }
2006
2007 /**
2008  * Emits code for a node.
2009  */
2010 static void ia32_emit_node(ir_node *node)
2011 {
2012         ir_op *op = get_irn_op(node);
2013
2014         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
2015
2016         if (is_ia32_irn(node)) {
2017                 if (get_ia32_exc_label(node)) {
2018                         /* emit the exception label of this instruction */
2019                         ia32_assign_exc_label(node);
2020                 }
2021                 if (mark_spill_reload) {
2022                         if (is_ia32_is_spill(node)) {
2023                                 ia32_emitf(NULL, "\txchg %ebx, %ebx        /* spill mark */\n");
2024                         }
2025                         if (is_ia32_is_reload(node)) {
2026                                 ia32_emitf(NULL, "\txchg %edx, %edx        /* reload mark */\n");
2027                         }
2028                         if (is_ia32_is_remat(node)) {
2029                                 ia32_emitf(NULL, "\txchg %ecx, %ecx        /* remat mark */\n");
2030                         }
2031                 }
2032         }
2033         if (op->ops.generic) {
2034                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
2035
2036                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
2037
2038                 (*func) (node);
2039         } else {
2040                 emit_Nothing(node);
2041                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
2042                 abort();
2043         }
2044 }
2045
2046 /**
2047  * Emits gas alignment directives
2048  */
2049 static void ia32_emit_alignment(unsigned align, unsigned skip)
2050 {
2051         ia32_emitf(NULL, "\t.p2align %u,,%u\n", align, skip);
2052 }
2053
2054 /**
2055  * Emits gas alignment directives for Labels depended on cpu architecture.
2056  */
2057 static void ia32_emit_align_label(void)
2058 {
2059         unsigned align        = ia32_cg_config.label_alignment;
2060         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
2061         ia32_emit_alignment(align, maximum_skip);
2062 }
2063
2064 /**
2065  * Test whether a block should be aligned.
2066  * For cpus in the P4/Athlon class it is useful to align jump labels to
2067  * 16 bytes. However we should only do that if the alignment nops before the
2068  * label aren't executed more often than we have jumps to the label.
2069  */
2070 static int should_align_block(const ir_node *block)
2071 {
2072         static const double DELTA = .0001;
2073         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
2074         ir_node      *prev        = get_prev_block_sched(block);
2075         double        block_freq;
2076         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
2077         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
2078         int           i, n_cfgpreds;
2079
2080         if (exec_freq == NULL)
2081                 return 0;
2082         if (ia32_cg_config.label_alignment_factor <= 0)
2083                 return 0;
2084
2085         block_freq = get_block_execfreq(exec_freq, block);
2086         if (block_freq < DELTA)
2087                 return 0;
2088
2089         n_cfgpreds = get_Block_n_cfgpreds(block);
2090         for(i = 0; i < n_cfgpreds; ++i) {
2091                 const ir_node *pred      = get_Block_cfgpred_block(block, i);
2092                 double         pred_freq = get_block_execfreq(exec_freq, pred);
2093
2094                 if (pred == prev) {
2095                         prev_freq += pred_freq;
2096                 } else {
2097                         jmp_freq  += pred_freq;
2098                 }
2099         }
2100
2101         if (prev_freq < DELTA && !(jmp_freq < DELTA))
2102                 return 1;
2103
2104         jmp_freq /= prev_freq;
2105
2106         return jmp_freq > ia32_cg_config.label_alignment_factor;
2107 }
2108
2109 /**
2110  * Emit the block header for a block.
2111  *
2112  * @param block       the block
2113  * @param prev_block  the previous block
2114  */
2115 static void ia32_emit_block_header(ir_node *block)
2116 {
2117         ir_graph     *irg = current_ir_graph;
2118         int           need_label = block_needs_label(block);
2119         int           i, arity;
2120         ir_exec_freq *exec_freq = cg->birg->exec_freq;
2121
2122         if (block == get_irg_end_block(irg))
2123                 return;
2124
2125         if (ia32_cg_config.label_alignment > 0) {
2126                 /* align the current block if:
2127                  * a) if should be aligned due to its execution frequency
2128                  * b) there is no fall-through here
2129                  */
2130                 if (should_align_block(block)) {
2131                         ia32_emit_align_label();
2132                 } else {
2133                         /* if the predecessor block has no fall-through,
2134                            we can always align the label. */
2135                         int i;
2136                         int has_fallthrough = 0;
2137
2138                         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
2139                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2140                                 if (can_be_fallthrough(cfg_pred)) {
2141                                         has_fallthrough = 1;
2142                                         break;
2143                                 }
2144                         }
2145
2146                         if (!has_fallthrough)
2147                                 ia32_emit_align_label();
2148                 }
2149         }
2150
2151         if (need_label) {
2152                 ia32_emit_block_name(block);
2153                 be_emit_char(':');
2154
2155                 be_emit_pad_comment();
2156                 be_emit_cstring("   /* ");
2157         } else {
2158                 be_emit_cstring("\t/* ");
2159                 ia32_emit_block_name(block);
2160                 be_emit_cstring(": ");
2161         }
2162
2163         be_emit_cstring("preds:");
2164
2165         /* emit list of pred blocks in comment */
2166         arity = get_irn_arity(block);
2167         if (arity <= 0) {
2168                 be_emit_cstring(" none");
2169         } else {
2170                 for (i = 0; i < arity; ++i) {
2171                         ir_node *predblock = get_Block_cfgpred_block(block, i);
2172                         be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2173                 }
2174         }
2175         if (exec_freq != NULL) {
2176                 be_emit_irprintf(", freq: %f",
2177                                  get_block_execfreq(exec_freq, block));
2178         }
2179         be_emit_cstring(" */\n");
2180         be_emit_write_line();
2181 }
2182
2183 /**
2184  * Walks over the nodes in a block connected by scheduling edges
2185  * and emits code for each node.
2186  */
2187 static void ia32_gen_block(ir_node *block)
2188 {
2189         ir_node *node;
2190
2191         ia32_emit_block_header(block);
2192
2193         /* emit the contents of the block */
2194         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2195         sched_foreach(block, node) {
2196                 ia32_emit_node(node);
2197         }
2198 }
2199
2200 typedef struct exc_entry {
2201         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2202         ir_node *block;      /** The block to call then. */
2203 } exc_entry;
2204
2205 /**
2206  * Block-walker:
2207  * Sets labels for control flow nodes (jump target).
2208  * Links control predecessors to there destination blocks.
2209  */
2210 static void ia32_gen_labels(ir_node *block, void *data)
2211 {
2212         exc_entry **exc_list = data;
2213         ir_node *pred;
2214         int     n;
2215
2216         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2217                 pred = get_Block_cfgpred(block, n);
2218                 set_irn_link(pred, block);
2219
2220                 pred = skip_Proj(pred);
2221                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2222                         exc_entry e;
2223
2224                         e.exc_instr = pred;
2225                         e.block     = block;
2226                         ARR_APP1(exc_entry, *exc_list, e);
2227                         set_irn_link(pred, block);
2228                 }
2229         }
2230 }
2231
2232 /**
2233  * Compare two exception_entries.
2234  */
2235 static int cmp_exc_entry(const void *a, const void *b)
2236 {
2237         const exc_entry *ea = a;
2238         const exc_entry *eb = b;
2239
2240         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2241                 return -1;
2242         return +1;
2243 }
2244
2245 /**
2246  * Main driver. Emits the code for one routine.
2247  */
2248 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2249 {
2250         ir_entity *entity     = get_irg_entity(irg);
2251         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2252         int i, n;
2253
2254         cg       = ia32_cg;
2255         isa      = cg->isa;
2256         do_pic   = cg->birg->main_env->options->pic;
2257
2258         be_gas_elf_type_char = '@';
2259
2260         ia32_register_emitters();
2261
2262         get_unique_label(pic_base_label, sizeof(pic_base_label), ".PIC_BASE");
2263
2264         be_dbg_method_begin(entity, be_abi_get_stack_layout(cg->birg->abi));
2265         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2266
2267         /* we use links to point to target blocks */
2268         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2269         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2270
2271         /* initialize next block links */
2272         n = ARR_LEN(cg->blk_sched);
2273         for (i = 0; i < n; ++i) {
2274                 ir_node *block = cg->blk_sched[i];
2275                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2276
2277                 set_irn_link(block, prev);
2278         }
2279
2280         for (i = 0; i < n; ++i) {
2281                 ir_node *block = cg->blk_sched[i];
2282
2283                 ia32_gen_block(block);
2284         }
2285
2286         be_gas_emit_function_epilog(entity);
2287         be_dbg_method_end();
2288         be_emit_char('\n');
2289         be_emit_write_line();
2290
2291         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2292
2293         /* Sort the exception table using the exception label id's.
2294            Those are ascending with ascending addresses. */
2295         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2296         {
2297                 int i;
2298
2299                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2300                         be_emit_cstring("\t.long ");
2301                         ia32_emit_exc_label(exc_list[i].exc_instr);
2302                         be_emit_char('\n');
2303                         be_emit_cstring("\t.long ");
2304                         ia32_emit_block_name(exc_list[i].block);
2305                         be_emit_char('\n');
2306                 }
2307         }
2308         DEL_ARR_F(exc_list);
2309 }
2310
2311 static const lc_opt_table_entry_t ia32_emitter_options[] = {
2312         LC_OPT_ENT_BOOL("mark_spill_reload",   "mark spills and reloads with ud opcodes", &mark_spill_reload),
2313         LC_OPT_LAST
2314 };
2315
2316 /* ==== Experimental binary emitter ==== */
2317
2318 static unsigned char reg_gp_map[N_ia32_gp_REGS];
2319 //static unsigned char reg_mmx_map[N_ia32_mmx_REGS];
2320 //static unsigned char reg_sse_map[N_ia32_xmm_REGS];
2321 static unsigned char pnc_map_signed[8];
2322 static unsigned char pnc_map_unsigned[8];
2323
2324 static void build_reg_map(void)
2325 {
2326         reg_gp_map[REG_EAX] = 0x0;
2327         reg_gp_map[REG_ECX] = 0x1;
2328         reg_gp_map[REG_EDX] = 0x2;
2329         reg_gp_map[REG_EBX] = 0x3;
2330         reg_gp_map[REG_ESP] = 0x4;
2331         reg_gp_map[REG_EBP] = 0x5;
2332         reg_gp_map[REG_ESI] = 0x6;
2333         reg_gp_map[REG_EDI] = 0x7;
2334
2335         pnc_map_signed[pn_Cmp_Eq]    = 0x04;
2336         pnc_map_signed[pn_Cmp_Lt]    = 0x0C;
2337         pnc_map_signed[pn_Cmp_Le]    = 0x0E;
2338         pnc_map_signed[pn_Cmp_Gt]    = 0x0F;
2339         pnc_map_signed[pn_Cmp_Ge]    = 0x0D;
2340         pnc_map_signed[pn_Cmp_Lg]    = 0x05;
2341
2342         pnc_map_unsigned[pn_Cmp_Eq]    = 0x04;
2343         pnc_map_unsigned[pn_Cmp_Lt]    = 0x02;
2344         pnc_map_unsigned[pn_Cmp_Le]    = 0x06;
2345         pnc_map_unsigned[pn_Cmp_Gt]    = 0x07;
2346         pnc_map_unsigned[pn_Cmp_Ge]    = 0x03;
2347         pnc_map_unsigned[pn_Cmp_Lg]    = 0x05;
2348 }
2349
2350 /** Returns the encoding for a pnc field. */
2351 static unsigned char pnc2cc(int pnc)
2352 {
2353         unsigned char cc;
2354         if (pnc == ia32_pn_Cmp_parity) {
2355                 cc = 0x0A;
2356         } else if (pnc & ia32_pn_Cmp_float || pnc & ia32_pn_Cmp_unsigned) {
2357                 cc = pnc_map_unsigned[pnc & 0x07];
2358         } else {
2359                 cc = pnc_map_signed[pnc & 0x07];
2360         }
2361         assert(cc != 0);
2362         return cc;
2363 }
2364
2365 /** Sign extension bit values for binops */
2366 enum SignExt {
2367         UNSIGNED_IMM = 0,  /**< unsigned immediate */
2368         SIGNEXT_IMM  = 2,  /**< sign extended immediate */
2369 };
2370
2371 /** The mod encoding of the ModR/M */
2372 enum Mod {
2373         MOD_IND          = 0x00, /**< [reg1] */
2374         MOD_IND_BYTE_OFS = 0x40, /**< [reg1 + byte ofs] */
2375         MOD_IND_WORD_OFS = 0x80, /**< [reg1 + word ofs] */
2376         MOD_REG          = 0xC0  /**< reg1 */
2377 };
2378
2379 /** create R/M encoding for ModR/M */
2380 #define ENC_RM(x) (x)
2381 /** create REG encoding for ModR/M */
2382 #define ENC_REG(x) ((x) << 3)
2383
2384 /** create encoding for a SIB byte */
2385 #define ENC_SIB(scale, index, base) ((scale) << 6 | (index) << 3 | (base))
2386
2387 /* Node: The following routines are supposed to append bytes, words, dwords
2388    to the output stream.
2389    Currently the implementation is stupid in that it still creates output
2390    for an "assembler" in the form of .byte, .long
2391    We will change this when enough infrastructure is there to create complete
2392    machine code in memory/object files */
2393
2394 static void bemit8(const unsigned char byte)
2395 {
2396         be_emit_irprintf("\t.byte 0x%x\n", byte);
2397         be_emit_write_line();
2398 }
2399
2400 static void bemit16(const unsigned short u16)
2401 {
2402         be_emit_irprintf("\t.word 0x%x\n", u16);
2403         be_emit_write_line();
2404 }
2405
2406 static void bemit32(const unsigned u32)
2407 {
2408         be_emit_irprintf("\t.long 0x%x\n", u32);
2409         be_emit_write_line();
2410 }
2411
2412 /**
2413  * Emit address of an entity. If @p is_relative is true then a relative
2414  * offset from behind the address to the entity is created.
2415  */
2416 static void bemit_entity(ir_entity *entity, bool entity_sign, int offset,
2417                          bool is_relative)
2418 {
2419         if (entity == NULL) {
2420                 bemit32(offset);
2421                 return;
2422         }
2423
2424         /* the final version should remember the position in the bytestream
2425            and patch it with the correct address at linktime... */
2426         be_emit_cstring("\t.long ");
2427         if (entity_sign)
2428                 be_emit_char('-');
2429         be_gas_emit_entity(entity);
2430
2431         if (get_entity_owner(entity) == get_tls_type()) {
2432                 if (get_entity_visibility(entity) == ir_visibility_external) {
2433                         be_emit_cstring("@INDNTPOFF");
2434                 } else {
2435                         be_emit_cstring("@NTPOFF");
2436                 }
2437         }
2438
2439         if (is_relative) {
2440                 be_emit_cstring("-.");
2441                 offset -= 4;
2442         }
2443
2444         if (offset != 0) {
2445                 be_emit_irprintf("%+d", offset);
2446         }
2447         be_emit_char('\n');
2448         be_emit_write_line();
2449 }
2450
2451 static void bemit_jmp_destination(const ir_node *dest_block)
2452 {
2453         be_emit_cstring("\t.long ");
2454         ia32_emit_block_name(dest_block);
2455         be_emit_cstring(" - . - 4\n");
2456         be_emit_write_line();
2457 }
2458
2459 /* end emit routines, all emitters following here should only use the functions
2460    above. */
2461
2462 typedef enum reg_modifier {
2463         REG_LOW  = 0,
2464         REG_HIGH = 1
2465 } reg_modifier_t;
2466
2467 /** Create a ModR/M byte for src1,src2 registers */
2468 static void bemit_modrr(const arch_register_t *src1,
2469                         const arch_register_t *src2)
2470 {
2471         unsigned char modrm = MOD_REG;
2472         modrm |= ENC_RM(reg_gp_map[src1->index]);
2473         modrm |= ENC_REG(reg_gp_map[src2->index]);
2474         bemit8(modrm);
2475 }
2476
2477 /** Create a ModR/M8 byte for src1,src2 registers */
2478 static void bemit_modrr8(reg_modifier_t high_part1, const arch_register_t *src1,
2479                                                  reg_modifier_t high_part2, const arch_register_t *src2)
2480 {
2481         unsigned char modrm = MOD_REG;
2482         modrm |= ENC_RM(reg_gp_map[src1->index] +  (high_part1 == REG_HIGH ? 4 : 0));
2483         modrm |= ENC_REG(reg_gp_map[src2->index] + (high_part2 == REG_HIGH ? 4 : 0));
2484         bemit8(modrm);
2485 }
2486
2487 /** Create a ModR/M byte for one register and extension */
2488 static void bemit_modru(const arch_register_t *reg, unsigned ext)
2489 {
2490         unsigned char modrm = MOD_REG;
2491         assert(ext <= 7);
2492         modrm |= ENC_RM(reg_gp_map[reg->index]);
2493         modrm |= ENC_REG(ext);
2494         bemit8(modrm);
2495 }
2496
2497 /** Create a ModR/M8 byte for one register */
2498 static void bemit_modrm8(reg_modifier_t high_part, const arch_register_t *reg)
2499 {
2500         unsigned char modrm = MOD_REG;
2501         assert(reg_gp_map[reg->index] < 4);
2502         modrm |= ENC_RM(reg_gp_map[reg->index] + (high_part == REG_HIGH ? 4 : 0));
2503         modrm |= MOD_REG;
2504         bemit8(modrm);
2505 }
2506
2507 /**
2508  * Calculate the size of an signed immediate in bytes.
2509  *
2510  * @param offset  an offset
2511  */
2512 static unsigned get_signed_imm_size(int offset)
2513 {
2514         if (-128 <= offset && offset < 128) {
2515                 return 1;
2516         } else if (-32768 <= offset && offset < 32768) {
2517                 return 2;
2518         } else {
2519                 return 4;
2520         }
2521 }
2522
2523 /**
2524  * Emit an address mode.
2525  *
2526  * @param reg   content of the reg field: either a register index or an opcode extension
2527  * @param node  the node
2528  */
2529 static void bemit_mod_am(unsigned reg, const ir_node *node)
2530 {
2531         ir_entity *ent       = get_ia32_am_sc(node);
2532         int        offs      = get_ia32_am_offs_int(node);
2533         ir_node   *base      = get_irn_n(node, n_ia32_base);
2534         int        has_base  = !is_ia32_NoReg_GP(base);
2535         ir_node   *index     = get_irn_n(node, n_ia32_index);
2536         int        has_index = !is_ia32_NoReg_GP(index);
2537         unsigned   modrm     = 0;
2538         unsigned   sib       = 0;
2539         unsigned   emitoffs  = 0;
2540         bool       emitsib   = false;
2541         unsigned   base_enc;
2542
2543         /* set the mod part depending on displacement */
2544         if (ent != NULL) {
2545                 modrm |= MOD_IND_WORD_OFS;
2546                 emitoffs = 32;
2547         } else if (offs == 0) {
2548                 modrm |= MOD_IND;
2549                 emitoffs = 0;
2550         } else if (-128 <= offs && offs < 128) {
2551                 modrm |= MOD_IND_BYTE_OFS;
2552                 emitoffs = 8;
2553         } else {
2554                 modrm |= MOD_IND_WORD_OFS;
2555                 emitoffs = 32;
2556         }
2557
2558         if (has_base) {
2559                 const arch_register_t *base_reg = arch_get_irn_register(base);
2560                 base_enc = reg_gp_map[base_reg->index];
2561         } else {
2562                 /* Use the EBP encoding + MOD_IND if NO base register. There is
2563                  * always a 32bit offset present in this case. */
2564                 modrm    = MOD_IND;
2565                 base_enc = 0x05;
2566                 emitoffs = 32;
2567         }
2568
2569         /* Determine if we need a SIB byte. */
2570         if (has_index) {
2571                 const arch_register_t *reg_index = arch_get_irn_register(index);
2572                 int                    scale     = get_ia32_am_scale(node);
2573                 assert(scale < 4);
2574                 /* R/M set to ESP means SIB in 32bit mode. */
2575                 modrm   |= ENC_RM(0x04);
2576                 sib      = ENC_SIB(scale, reg_gp_map[reg_index->index], base_enc);
2577                 emitsib = true;
2578         } else if (base_enc == 0x04) {
2579                 /* for the above reason we are forced to emit a SIB when base is ESP.
2580                  * Only the base is used, index must be ESP too, which means no index.
2581                  */
2582                 modrm   |= ENC_RM(0x04);
2583                 sib      = ENC_SIB(0, 0x04, 0x04);
2584                 emitsib  = true;
2585         } else {
2586                 modrm |= ENC_RM(base_enc);
2587         }
2588
2589         /* We are forced to emit an 8bit offset as EBP base without offset is a
2590          * special case for SIB without base register. */
2591         if (base_enc == 0x05 && emitoffs == 0) {
2592                 modrm    |= MOD_IND_BYTE_OFS;
2593                 emitoffs  = 8;
2594         }
2595
2596         modrm |= ENC_REG(reg);
2597
2598         bemit8(modrm);
2599         if (emitsib)
2600                 bemit8(sib);
2601
2602         /* emit displacement */
2603         if (emitoffs == 8) {
2604                 bemit8((unsigned) offs);
2605         } else if (emitoffs == 32) {
2606                 bemit_entity(ent, is_ia32_am_sc_sign(node), offs, false);
2607         }
2608 }
2609
2610 /**
2611  * Emit a binop with a immediate operand.
2612  *
2613  * @param node        the node to emit
2614  * @param opcode_eax  the opcode for the op eax, imm variant
2615  * @param opcode      the opcode for the reg, imm variant
2616  * @param ruval       the opcode extension for opcode
2617  */
2618 static void bemit_binop_with_imm(
2619         const ir_node *node,
2620         unsigned char opcode_ax,
2621         unsigned char opcode, unsigned char ruval)
2622 {
2623         /* Use in-reg, because some instructions (cmp, test) have no out-reg. */
2624         const ir_node               *op   = get_irn_n(node, n_ia32_binary_right);
2625         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(op);
2626         unsigned                     size;
2627
2628         /* Some instructions (test) have no short form with 32bit value + 8bit
2629          * immediate. */
2630         if (attr->symconst != NULL || opcode & SIGNEXT_IMM) {
2631                 size = 4;
2632         } else {
2633                 /* check for sign extension */
2634                 size = get_signed_imm_size(attr->offset);
2635         }
2636
2637         switch (size) {
2638         case 1:
2639                 bemit8(opcode | SIGNEXT_IMM);
2640                 /* cmp has this special mode */
2641                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
2642                         bemit_mod_am(ruval, node);
2643                 } else {
2644                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
2645                         bemit_modru(reg, ruval);
2646                 }
2647                 bemit8((unsigned char)attr->offset);
2648                 return;
2649         case 2:
2650         case 4:
2651                 /* check for eax variant: this variant is shorter for 32bit immediates only */
2652                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
2653                         bemit8(opcode);
2654                         bemit_mod_am(ruval, node);
2655                 } else {
2656                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
2657                         if (reg->index == REG_EAX) {
2658                                 bemit8(opcode_ax);
2659                         } else {
2660                                 bemit8(opcode);
2661                                 bemit_modru(reg, ruval);
2662                         }
2663                 }
2664                 bemit_entity(attr->symconst, attr->sc_sign, attr->offset, false);
2665                 return;
2666         }
2667         panic("invalid imm size?!?");
2668 }
2669
2670 /**
2671  * Emits a binop.
2672  */
2673 static void bemit_binop_2(const ir_node *node, unsigned code)
2674 {
2675         const arch_register_t *out = get_in_reg(node, n_ia32_binary_left);
2676         bemit8(code);
2677         if (get_ia32_op_type(node) == ia32_Normal) {
2678                 const arch_register_t *op2 = get_in_reg(node, n_ia32_binary_right);
2679                 bemit_modrr(op2, out);
2680         } else {
2681                 bemit_mod_am(reg_gp_map[out->index], node);
2682         }
2683 }
2684
2685 /**
2686  * Emit a binop.
2687  */
2688 static void bemit_binop(const ir_node *node, const unsigned char opcodes[4])
2689 {
2690         ir_node *right = get_irn_n(node, n_ia32_binary_right);
2691         if (is_ia32_Immediate(right)) {
2692                 bemit_binop_with_imm(node, opcodes[1], opcodes[2], opcodes[3]);
2693         } else {
2694                 bemit_binop_2(node, opcodes[0]);
2695         }
2696 }
2697
2698 /**
2699  * Emit an unop.
2700  */
2701 static void bemit_unop(const ir_node *node, unsigned char code, unsigned char ext, int input)
2702 {
2703         bemit8(code);
2704         if (get_ia32_op_type(node) == ia32_Normal) {
2705                 const arch_register_t *in = get_in_reg(node, input);
2706                 bemit_modru(in, ext);
2707         } else {
2708                 bemit_mod_am(ext, node);
2709         }
2710 }
2711
2712 static void bemit_unop_reg(const ir_node *node, unsigned char code, int input)
2713 {
2714         const arch_register_t *out = get_out_reg(node, 0);
2715         bemit_unop(node, code, reg_gp_map[out->index], input);
2716 }
2717
2718 static void bemit_unop_mem(const ir_node *node, unsigned char code, unsigned char ext)
2719 {
2720         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node));
2721         if (size == 16)
2722                 bemit8(0x66);
2723         bemit8(size == 8 ? code : code + 1);
2724         bemit_mod_am(ext, node);
2725 }
2726
2727 static void bemit_immediate(const ir_node *node, bool relative)
2728 {
2729         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
2730         bemit_entity(attr->symconst, attr->sc_sign, attr->offset, relative);
2731 }
2732
2733 static void bemit_copy(const ir_node *copy)
2734 {
2735         const arch_register_t *in  = get_in_reg(copy, 0);
2736         const arch_register_t *out = get_out_reg(copy, 0);
2737
2738         if (in == out || is_unknown_reg(in))
2739                 return;
2740         /* copies of vf nodes aren't real... */
2741         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
2742                 return;
2743
2744         if (get_irn_mode(copy) == mode_E) {
2745                 panic("NIY");
2746         } else {
2747                 assert(arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_gp]);
2748                 bemit8(0x8B);
2749                 bemit_modrr(in, out);
2750         }
2751 }
2752
2753 static void bemit_perm(const ir_node *node)
2754 {
2755         const arch_register_t       *in0  = arch_get_irn_register(get_irn_n(node, 0));
2756         const arch_register_t       *in1  = arch_get_irn_register(get_irn_n(node, 1));
2757         const arch_register_class_t *cls0 = arch_register_get_class(in0);
2758
2759         assert(cls0 == arch_register_get_class(in1) && "Register class mismatch at Perm");
2760
2761         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
2762                 if (in0->index == REG_EAX) {
2763                         bemit8(0x90 + reg_gp_map[in1->index]);
2764                 } else if (in1->index == REG_EAX) {
2765                         bemit8(0x90 + reg_gp_map[in0->index]);
2766                 } else {
2767                         bemit8(0x87);
2768                         bemit_modrr(in0, in1);
2769                 }
2770         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
2771                 panic("unimplemented"); // TODO implement
2772                 //ia32_emitf(NULL, "\txorpd %R, %R\n", in1, in0);
2773                 //ia32_emitf(NULL, "\txorpd %R, %R\n", in0, in1);
2774                 //ia32_emitf(node, "\txorpd %R, %R\n", in1, in0);
2775         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
2776                 /* is a NOP */
2777         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
2778                 /* is a NOP */
2779         } else {
2780                 panic("unexpected register class in be_Perm (%+F)", node);
2781         }
2782 }
2783
2784 static void bemit_xor0(const ir_node *node)
2785 {
2786         const arch_register_t *out = get_out_reg(node, 0);
2787         bemit8(0x31);
2788         bemit_modrr(out, out);
2789 }
2790
2791 static void bemit_mov_const(const ir_node *node)
2792 {
2793         const arch_register_t *out = get_out_reg(node, 0);
2794         bemit8(0xB8 + reg_gp_map[out->index]);
2795         bemit_immediate(node, false);
2796 }
2797
2798 /**
2799  * Creates a function for a Binop with 3 possible encodings.
2800  */
2801 #define BINOP(op, op0, op1, op2, op2_ext)                                 \
2802 static void bemit_ ## op(const ir_node *node) {                           \
2803         static const unsigned char op ## _codes[] = {op0, op1, op2, op2_ext}; \
2804         bemit_binop(node, op ## _codes);                                      \
2805 }
2806
2807 /*    insn  def  eax,imm   imm */
2808 BINOP(add,  0x03, 0x05, 0x81, 0)
2809 BINOP(or,   0x0B, 0x0D, 0x81, 1)
2810 BINOP(adc,  0x13, 0x15, 0x81, 2)
2811 BINOP(sbb,  0x1B, 0x1D, 0x81, 3)
2812 BINOP(and,  0x23, 0x25, 0x81, 4)
2813 BINOP(sub,  0x2B, 0x2D, 0x81, 5)
2814 BINOP(xor,  0x33, 0x35, 0x81, 6)
2815 BINOP(test, 0x85, 0xA9, 0xF7, 0)
2816
2817 #define BINOPMEM(op, ext) \
2818 static void bemit_##op(const ir_node *node) \
2819 { \
2820         ir_node *val; \
2821         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node)); \
2822         if (size == 16) \
2823                 bemit8(0x66); \
2824         val = get_irn_n(node, n_ia32_unary_op); \
2825         if (is_ia32_Immediate(val)) { \
2826                 const ia32_immediate_attr_t *attr   = get_ia32_immediate_attr_const(val); \
2827                 int                          offset = attr->offset; \
2828                 if (attr->symconst == NULL && get_signed_imm_size(offset) == 1) { \
2829                         bemit8(0x83); \
2830                         bemit_mod_am(ext, node); \
2831                         bemit8(offset); \
2832                 } else { \
2833                         bemit8(0x81); \
2834                         bemit_mod_am(ext, node); \
2835                         if (size == 16) { \
2836                                 bemit16(offset); \
2837                         } else { \
2838                                 bemit_entity(attr->symconst, attr->sc_sign, offset, false); \
2839                         } \
2840                 } \
2841         } else { \
2842                 bemit8(ext << 3 | 1); \
2843                 bemit_mod_am(reg_gp_map[get_out_reg(val, 0)->index], node); \
2844         } \
2845 } \
2846  \
2847 static void bemit_##op##8bit(const ir_node *node) \
2848 { \
2849         ir_node *val = get_irn_n(node, n_ia32_unary_op); \
2850         if (is_ia32_Immediate(val)) { \
2851                 bemit8(0x80); \
2852                 bemit_mod_am(ext, node); \
2853                 bemit8(get_ia32_immediate_attr_const(val)->offset); \
2854         } else { \
2855                 bemit8(ext << 3); \
2856                 bemit_mod_am(reg_gp_map[get_out_reg(val, 0)->index], node); \
2857         } \
2858 }
2859
2860 BINOPMEM(addmem,  0)
2861 BINOPMEM(ormem,   1)
2862 BINOPMEM(andmem,  4)
2863 BINOPMEM(submem,  5)
2864 BINOPMEM(xormem,  6)
2865
2866
2867 /**
2868  * Creates a function for an Unop with code /ext encoding.
2869  */
2870 #define UNOP(op, code, ext, input)              \
2871 static void bemit_ ## op(const ir_node *node) { \
2872         bemit_unop(node, code, ext, input);         \
2873 }
2874
2875 UNOP(not,     0xF7, 2, n_ia32_Not_val)
2876 UNOP(neg,     0xF7, 3, n_ia32_Neg_val)
2877 UNOP(mul,     0xF7, 4, n_ia32_Mul_right)
2878 UNOP(imul1op, 0xF7, 5, n_ia32_IMul1OP_right)
2879 UNOP(div,     0xF7, 6, n_ia32_Div_divisor)
2880 UNOP(idiv,    0xF7, 7, n_ia32_IDiv_divisor)
2881
2882 /* TODO: am support for IJmp */
2883 UNOP(ijmp,    0xFF, 4, n_ia32_IJmp_target)
2884
2885 #define SHIFT(op, ext) \
2886 static void bemit_##op(const ir_node *node) \
2887 { \
2888         const arch_register_t *out   = get_out_reg(node, 0); \
2889         ir_node               *count = get_irn_n(node, 1); \
2890         if (is_ia32_Immediate(count)) { \
2891                 int offset = get_ia32_immediate_attr_const(count)->offset; \
2892                 if (offset == 1) { \
2893                         bemit8(0xD1); \
2894                         bemit_modru(out, ext); \
2895                 } else { \
2896                         bemit8(0xC1); \
2897                         bemit_modru(out, ext); \
2898                         bemit8(offset); \
2899                 } \
2900         } else { \
2901                 bemit8(0xD3); \
2902                 bemit_modru(out, ext); \
2903         } \
2904 } \
2905  \
2906 static void bemit_##op##mem(const ir_node *node) \
2907 { \
2908         ir_node *count; \
2909         unsigned size = get_mode_size_bits(get_ia32_ls_mode(node)); \
2910         if (size == 16) \
2911                 bemit8(0x66); \
2912         count = get_irn_n(node, 1); \
2913         if (is_ia32_Immediate(count)) { \
2914                 int offset = get_ia32_immediate_attr_const(count)->offset; \
2915                 if (offset == 1) { \
2916                         bemit8(size == 8 ? 0xD0 : 0xD1); \
2917                         bemit_mod_am(ext, node); \
2918                 } else { \
2919                         bemit8(size == 8 ? 0xC0 : 0xC1); \
2920                         bemit_mod_am(ext, node); \
2921                         bemit8(offset); \
2922                 } \
2923         } else { \
2924                 bemit8(size == 8 ? 0xD2 : 0xD3); \
2925                 bemit_mod_am(ext, node); \
2926         } \
2927 }
2928
2929 SHIFT(rol, 0)
2930 SHIFT(ror, 1)
2931 SHIFT(shl, 4)
2932 SHIFT(shr, 5)
2933 SHIFT(sar, 7)
2934
2935 static void bemit_shld(const ir_node *node)
2936 {
2937         const arch_register_t *in  = get_in_reg(node, n_ia32_ShlD_val_low);
2938         const arch_register_t *out = get_out_reg(node, pn_ia32_ShlD_res);
2939         ir_node *count = get_irn_n(node, n_ia32_ShlD_count);
2940         bemit8(0x0F);
2941         if (is_ia32_Immediate(count)) {
2942                 bemit8(0xA4);
2943                 bemit_modrr(out, in);
2944                 bemit8(get_ia32_immediate_attr_const(count)->offset);
2945         } else {
2946                 bemit8(0xA5);
2947                 bemit_modrr(out, in);
2948         }
2949 }
2950
2951 static void bemit_shrd(const ir_node *node)
2952 {
2953         const arch_register_t *in  = get_in_reg(node, n_ia32_ShrD_val_low);
2954         const arch_register_t *out = get_out_reg(node, pn_ia32_ShrD_res);
2955         ir_node *count = get_irn_n(node, n_ia32_ShrD_count);
2956         bemit8(0x0F);
2957         if (is_ia32_Immediate(count)) {
2958                 bemit8(0xAC);
2959                 bemit_modrr(out, in);
2960                 bemit8(get_ia32_immediate_attr_const(count)->offset);
2961         } else {
2962                 bemit8(0xAD);
2963                 bemit_modrr(out, in);
2964         }
2965 }
2966
2967 /**
2968  * binary emitter for setcc.
2969  */
2970 static void bemit_setcc(const ir_node *node)
2971 {
2972         const arch_register_t *dreg = get_out_reg(node, pn_ia32_Setcc_res);
2973
2974         pn_Cmp pnc = get_ia32_condcode(node);
2975         pnc        = determine_final_pnc(node, n_ia32_Setcc_eflags, pnc);
2976         if (pnc & ia32_pn_Cmp_float) {
2977                 switch (pnc & 0x0f) {
2978                 case pn_Cmp_Uo:
2979                          /* setp <dreg */
2980                         bemit8(0x0F);
2981                         bemit8(0x9A);
2982                         bemit_modrm8(REG_LOW, dreg);
2983                         return;
2984
2985                 case pn_Cmp_Leg:
2986                          /* setnp <dreg*/
2987                         bemit8(0x0F);
2988                         bemit8(0x9B);
2989                         bemit_modrm8(REG_LOW, dreg);
2990                         return;
2991
2992                 case pn_Cmp_Eq:
2993                 case pn_Cmp_Lt:
2994                 case pn_Cmp_Le:
2995                          /* set%PNC <dreg */
2996                         bemit8(0x0F);
2997                         bemit8(0x90 | pnc2cc(pnc));
2998                         bemit_modrm8(REG_LOW, dreg);
2999
3000                         /* setnp >dreg */
3001                         bemit8(0x0F);
3002                         bemit8(0x9B);
3003                         bemit_modrm8(REG_HIGH, dreg);
3004
3005                         /* andb %>dreg, %<dreg */
3006                         bemit8(0x20);
3007                         bemit_modrr8(REG_LOW, dreg, REG_HIGH, dreg);
3008                         return;
3009
3010                 case pn_Cmp_Ug:
3011                 case pn_Cmp_Uge:
3012                 case pn_Cmp_Ne:
3013                         /* set%PNC <dreg */
3014                         bemit8(0x0F);
3015                         bemit8(0x90 | pnc2cc(pnc));
3016                         bemit_modrm8(REG_LOW, dreg);
3017
3018                         /* setp >dreg */
3019                         bemit8(0x0F);
3020                         bemit8(0x9A);
3021                         bemit_modrm8(REG_HIGH, dreg);
3022
3023                         /* orb %>dreg, %<dreg */
3024                         bemit8(0x08);
3025                         bemit_modrr8(REG_LOW, dreg, REG_HIGH, dreg);
3026                         return;
3027
3028                 default:
3029                         break;
3030                 }
3031         }
3032         /* set%PNC <dreg */
3033         bemit8(0x0F);
3034         bemit8(0x90 | pnc2cc(pnc));
3035         bemit_modrm8(REG_LOW, dreg);
3036 }
3037
3038 static void bemit_cmovcc(const ir_node *node)
3039 {
3040         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
3041         int                    ins_permuted = attr->data.ins_permuted;
3042         const arch_register_t *out          = arch_irn_get_register(node, pn_ia32_res);
3043         pn_Cmp                 pnc          = get_ia32_condcode(node);
3044         const arch_register_t *in_true;
3045         const arch_register_t *in_false;
3046
3047         pnc = determine_final_pnc(node, n_ia32_CMovcc_eflags, pnc);
3048
3049         in_true  = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_true));
3050         in_false = arch_get_irn_register(get_irn_n(node, n_ia32_CMovcc_val_false));
3051
3052         /* should be same constraint fullfilled? */
3053         if (out == in_false) {
3054                 /* yes -> nothing to do */
3055         } else if (out == in_true) {
3056                 assert(get_ia32_op_type(node) == ia32_Normal);
3057                 ins_permuted = !ins_permuted;
3058                 in_true      = in_false;
3059         } else {
3060                 /* we need a mov */
3061                 bemit8(0x8B); // mov %in_false, %out
3062                 bemit_modrr(in_false, out);
3063         }
3064
3065         if (ins_permuted)
3066                 pnc = ia32_get_negated_pnc(pnc);
3067
3068         /* TODO: handling of Nans isn't correct yet */
3069
3070         bemit8(0x0F);
3071         bemit8(0x40 | pnc2cc(pnc));
3072         if (get_ia32_op_type(node) == ia32_Normal) {
3073                 bemit_modrr(in_true, out);
3074         } else {
3075                 bemit_mod_am(reg_gp_map[out->index], node);
3076         }
3077 }
3078
3079 static void bemit_cmp(const ir_node *node)
3080 {
3081         unsigned  ls_size = get_mode_size_bits(get_ia32_ls_mode(node));
3082         ir_node  *right;
3083
3084         if (ls_size == 16)
3085                 bemit8(0x66);
3086
3087         right = get_irn_n(node, n_ia32_binary_right);
3088         if (is_ia32_Immediate(right)) {
3089                 /* Use in-reg, because some instructions (cmp, test) have no out-reg. */
3090                 const ir_node               *op   = get_irn_n(node, n_ia32_binary_right);
3091                 const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(op);
3092                 unsigned                     size;
3093
3094                 if (attr->symconst != NULL) {
3095                         size = 4;
3096                 } else {
3097                         /* check for sign extension */
3098                         size = get_signed_imm_size(attr->offset);
3099                 }
3100
3101                 switch (size) {
3102                         case 1:
3103                                 bemit8(0x81 | SIGNEXT_IMM);
3104                                 /* cmp has this special mode */
3105                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
3106                                         bemit_mod_am(7, node);
3107                                 } else {
3108                                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
3109                                         bemit_modru(reg, 7);
3110                                 }
3111                                 bemit8((unsigned char)attr->offset);
3112                                 return;
3113                         case 2:
3114                         case 4:
3115                                 /* check for eax variant: this variant is shorter for 32bit immediates only */
3116                                 if (get_ia32_op_type(node) == ia32_AddrModeS) {
3117                                         bemit8(0x81);
3118                                         bemit_mod_am(7, node);
3119                                 } else {
3120                                         const arch_register_t *reg = get_in_reg(node, n_ia32_binary_left);
3121                                         if (reg->index == REG_EAX) {
3122                                                 bemit8(0x3D);
3123                                         } else {
3124                                                 bemit8(0x81);
3125                                                 bemit_modru(reg, 7);
3126                                         }
3127                                 }
3128                                 if (ls_size == 16) {
3129                                         bemit16(attr->offset);
3130                                 } else {
3131                                         bemit_entity(attr->symconst, attr->sc_sign, attr->offset, false);
3132                                 }
3133                                 return;
3134                 }
3135                 panic("invalid imm size?!?");
3136         } else {
3137                 const arch_register_t *out = get_in_reg(node, n_ia32_binary_left);
3138                 bemit8(0x3B);
3139                 if (get_ia32_op_type(node) == ia32_Normal) {
3140                         const arch_register_t *op2 = get_in_reg(node, n_ia32_binary_right);
3141                         bemit_modrr(op2, out);
3142                 } else {
3143                         bemit_mod_am(reg_gp_map[out->index], node);
3144                 }
3145         }
3146 }
3147
3148 static void bemit_cmp8bit(const ir_node *node)
3149 {
3150         ir_node *right = get_irn_n(node, n_ia32_binary_right);
3151         if (is_ia32_Immediate(right)) {
3152                 if (get_ia32_op_type(node) == ia32_Normal) {
3153                         const arch_register_t *out = get_in_reg(node, n_ia32_Cmp_left);
3154                         if (out->index == REG_EAX) {
3155                                 bemit8(0x3C);
3156                         } else {
3157                                 bemit8(0x80);
3158                                 bemit_modru(out, 7);
3159                         }
3160                 } else {
3161                         bemit8(0x80);
3162                         bemit_mod_am(7, node);
3163                 }
3164                 bemit8(get_ia32_immediate_attr_const(right)->offset);
3165         } else {
3166                 const arch_register_t *out = get_in_reg(node, n_ia32_Cmp_left);
3167                 bemit8(0x3A);
3168                 if (get_ia32_op_type(node) == ia32_Normal) {
3169                         const arch_register_t *in = get_in_reg(node, n_ia32_Cmp_right);
3170                         bemit_modrr(out, in);
3171                 } else {
3172                         bemit_mod_am(reg_gp_map[out->index], node);
3173                 }
3174         }
3175 }
3176
3177 static void bemit_test8bit(const ir_node *node)
3178 {
3179         ir_node *right = get_irn_n(node, n_ia32_Test8Bit_right);
3180         if (is_ia32_Immediate(right)) {
3181                 if (get_ia32_op_type(node) == ia32_Normal) {
3182                         const arch_register_t *out = get_in_reg(node, n_ia32_Test8Bit_left);
3183                         if (out->index == REG_EAX) {
3184                                 bemit8(0xA8);
3185                         } else {
3186                                 bemit8(0xF6);
3187                                 bemit_modru(out, 0);
3188                         }
3189                 } else {
3190                         bemit8(0xF6);
3191                         bemit_mod_am(0, node);
3192                 }
3193                 bemit8(get_ia32_immediate_attr_const(right)->offset);
3194         } else {
3195                 const arch_register_t *out = get_in_reg(node, n_ia32_Test8Bit_left);
3196                 bemit8(0x84);
3197                 if (get_ia32_op_type(node) == ia32_Normal) {
3198                         const arch_register_t *in = get_in_reg(node, n_ia32_Test8Bit_right);
3199                         bemit_modrr(out, in);
3200                 } else {
3201                         bemit_mod_am(reg_gp_map[out->index], node);
3202                 }
3203         }
3204 }
3205
3206 static void bemit_imul(const ir_node *node)
3207 {
3208         ir_node *right = get_irn_n(node, n_ia32_IMul_right);
3209         /* Do we need the immediate form? */
3210         if (is_ia32_Immediate(right)) {
3211                 int imm = get_ia32_immediate_attr_const(right)->offset;
3212                 if (get_signed_imm_size(imm) == 1) {
3213                         bemit_unop_reg(node, 0x6B, n_ia32_IMul_left);
3214                         bemit8(imm);
3215                 } else {
3216                         bemit_unop_reg(node, 0x69, n_ia32_IMul_left);
3217                         bemit32(imm);
3218                 }
3219         } else {
3220                 bemit8(0x0F);
3221                 bemit_unop_reg(node, 0xAF, n_ia32_IMul_right);
3222         }
3223 }
3224
3225 static void bemit_dec(const ir_node *node)
3226 {
3227         const arch_register_t *out = get_out_reg(node, pn_ia32_Dec_res);
3228         bemit8(0x48 + reg_gp_map[out->index]);
3229 }
3230
3231 static void bemit_inc(const ir_node *node)
3232 {
3233         const arch_register_t *out = get_out_reg(node, pn_ia32_Inc_res);
3234         bemit8(0x40 + reg_gp_map[out->index]);
3235 }
3236
3237 #define UNOPMEM(op, code, ext) \
3238 static void bemit_##op(const ir_node *node) \
3239 { \
3240         bemit_unop_mem(node, code, ext); \
3241 }
3242
3243 UNOPMEM(notmem, 0xF6, 2)
3244 UNOPMEM(negmem, 0xF6, 3)
3245 UNOPMEM(incmem, 0xFE, 0)
3246 UNOPMEM(decmem, 0xFE, 1)
3247
3248 static void bemit_ldtls(const ir_node *node)
3249 {
3250         const arch_register_t *out = get_out_reg(node, 0);
3251
3252         bemit8(0x65); // gs:
3253         if (out->index == REG_EAX) {
3254                 bemit8(0xA1); // movl 0, %eax
3255         } else {
3256                 bemit8(0x8B); // movl 0, %reg
3257                 bemit8(MOD_IND | ENC_REG(reg_gp_map[out->index]) | ENC_RM(0x05));
3258         }
3259         bemit32(0);
3260 }
3261
3262 /**
3263  * Emit a Lea.
3264  */
3265 static void bemit_lea(const ir_node *node)
3266 {
3267         const arch_register_t *out = get_out_reg(node, 0);
3268         bemit8(0x8D);
3269         bemit_mod_am(reg_gp_map[out->index], node);
3270 }
3271
3272 /* helper function for bemit_minus64bit */
3273 static void bemit_helper_mov(const arch_register_t *src, const arch_register_t *dst)
3274 {
3275         bemit8(0x8B); // movl %src, %dst
3276         bemit_modrr(src, dst);
3277 }
3278
3279 /* helper function for bemit_minus64bit */
3280 static void bemit_helper_neg(const arch_register_t *reg)
3281 {
3282         bemit8(0xF7); // negl %reg
3283         bemit_modru(reg, 3);
3284 }
3285
3286 /* helper function for bemit_minus64bit */
3287 static void bemit_helper_sbb0(const arch_register_t *reg)
3288 {
3289         bemit8(0x83); // sbbl $0, %reg
3290         bemit_modru(reg, 3);
3291         bemit8(0);
3292 }
3293
3294 /* helper function for bemit_minus64bit */
3295 static void bemit_helper_sbb(const arch_register_t *src, const arch_register_t *dst)
3296 {
3297         bemit8(0x1B); // sbbl %src, %dst
3298         bemit_modrr(src, dst);
3299 }
3300
3301 /* helper function for bemit_minus64bit */
3302 static void bemit_helper_xchg(const arch_register_t *src, const arch_register_t *dst)
3303 {
3304         if (src->index == REG_EAX) {
3305                 bemit8(0x90 + reg_gp_map[dst->index]); // xchgl %eax, %dst
3306         } else if (dst->index == REG_EAX) {
3307                 bemit8(0x90 + reg_gp_map[src->index]); // xchgl %src, %eax
3308         } else {
3309                 bemit8(0x87); // xchgl %src, %dst
3310                 bemit_modrr(src, dst);
3311         }
3312 }
3313
3314 /* helper function for bemit_minus64bit */
3315 static void bemit_helper_zero(const arch_register_t *reg)
3316 {
3317         bemit8(0x33); // xorl %reg, %reg
3318         bemit_modrr(reg, reg);
3319 }
3320
3321 static void bemit_minus64bit(const ir_node *node)
3322 {
3323         const arch_register_t *in_lo  = get_in_reg(node, 0);
3324         const arch_register_t *in_hi  = get_in_reg(node, 1);
3325         const arch_register_t *out_lo = get_out_reg(node, 0);
3326         const arch_register_t *out_hi = get_out_reg(node, 1);
3327
3328         if (out_lo == in_lo) {
3329                 if (out_hi != in_hi) {
3330                         /* a -> a, b -> d */
3331                         goto zero_neg;
3332                 } else {
3333                         /* a -> a, b -> b */
3334                         goto normal_neg;
3335                 }
3336         } else if (out_lo == in_hi) {
3337                 if (out_hi == in_lo) {
3338                         /* a -> b, b -> a */
3339                         bemit_helper_xchg(in_lo, in_hi);
3340                         goto normal_neg;
3341                 } else {
3342                         /* a -> b, b -> d */
3343                         bemit_helper_mov(in_hi, out_hi);
3344                         bemit_helper_mov(in_lo, out_lo);
3345                         goto normal_neg;
3346                 }
3347         } else {
3348                 if (out_hi == in_lo) {
3349                         /* a -> c, b -> a */
3350                         bemit_helper_mov(in_lo, out_lo);
3351                         goto zero_neg;
3352                 } else if (out_hi == in_hi) {
3353                         /* a -> c, b -> b */
3354                         bemit_helper_mov(in_lo, out_lo);
3355                         goto normal_neg;
3356                 } else {
3357                         /* a -> c, b -> d */
3358                         bemit_helper_mov(in_lo, out_lo);
3359                         goto zero_neg;
3360                 }
3361         }
3362
3363 normal_neg:
3364         bemit_helper_neg( out_hi);
3365         bemit_helper_neg( out_lo);
3366         bemit_helper_sbb0(out_hi);
3367         return;
3368
3369 zero_neg:
3370         bemit_helper_zero(out_hi);
3371         bemit_helper_neg( out_lo);
3372         bemit_helper_sbb( in_hi, out_hi);
3373 }
3374
3375 /**
3376  * Emit a single opcode.
3377  */
3378 #define EMIT_SINGLEOP(op, code)                 \
3379 static void bemit_ ## op(const ir_node *node) { \
3380         (void) node;                                \
3381         bemit8(code);                               \
3382 }
3383
3384 //EMIT_SINGLEOP(daa,  0x27)
3385 //EMIT_SINGLEOP(das,  0x2F)
3386 //EMIT_SINGLEOP(aaa,  0x37)
3387 //EMIT_SINGLEOP(aas,  0x3F)
3388 //EMIT_SINGLEOP(nop,  0x90)
3389 EMIT_SINGLEOP(cwtl,  0x98)
3390 EMIT_SINGLEOP(cltd,  0x99)
3391 //EMIT_SINGLEOP(fwait, 0x9B)
3392 EMIT_SINGLEOP(sahf,  0x9E)
3393 //EMIT_SINGLEOP(popf, 0x9D)
3394 EMIT_SINGLEOP(leave, 0xC9)
3395 EMIT_SINGLEOP(int3,  0xCC)
3396 //EMIT_SINGLEOP(iret, 0xCF)
3397 //EMIT_SINGLEOP(xlat, 0xD7)
3398 //EMIT_SINGLEOP(lock, 0xF0)
3399 EMIT_SINGLEOP(rep,   0xF3)
3400 //EMIT_SINGLEOP(halt, 0xF4)
3401 EMIT_SINGLEOP(cmc,   0xF5)
3402 EMIT_SINGLEOP(stc,   0xF9)
3403 //EMIT_SINGLEOP(cli,  0xFA)
3404 //EMIT_SINGLEOP(sti,  0xFB)
3405 //EMIT_SINGLEOP(std,  0xFD)
3406
3407 /**
3408  * Emits a MOV out, [MEM].
3409  */
3410 static void bemit_load(const ir_node *node)
3411 {
3412         const arch_register_t *out = get_out_reg(node, 0);
3413
3414         if (out->index == REG_EAX) {
3415                 ir_node   *base      = get_irn_n(node, n_ia32_base);
3416                 int        has_base  = !is_ia32_NoReg_GP(base);
3417                 ir_node   *index     = get_irn_n(node, n_ia32_index);
3418                 int        has_index = !is_ia32_NoReg_GP(index);
3419                 if (!has_base && !has_index) {
3420                         ir_entity *ent  = get_ia32_am_sc(node);
3421                         int        offs = get_ia32_am_offs_int(node);
3422                         /* load from constant address to EAX can be encoded
3423                            as 0xA1 [offset] */
3424                         bemit8(0xA1);
3425                         bemit_entity(ent, 0, offs, false);
3426                         return;
3427                 }
3428         }
3429         bemit8(0x8B);
3430         bemit_mod_am(reg_gp_map[out->index], node);
3431 }
3432
3433 /**
3434  * Emits a MOV [mem], in.
3435  */
3436 static void bemit_store(const ir_node *node)
3437 {
3438         const ir_node *value = get_irn_n(node, n_ia32_Store_val);
3439         unsigned       size  = get_mode_size_bits(get_ia32_ls_mode(node));
3440
3441         if (is_ia32_Immediate(value)) {
3442                 if (size == 8) {
3443                         bemit8(0xC6);
3444                         bemit_mod_am(0, node);
3445                         bemit8(get_ia32_immediate_attr_const(value)->offset);
3446                 } else if (size == 16) {
3447                         bemit8(0x66);
3448                         bemit8(0xC7);
3449                         bemit_mod_am(0, node);
3450                         bemit16(get_ia32_immediate_attr_const(value)->offset);
3451                 } else {
3452                         bemit8(0xC7);
3453                         bemit_mod_am(0, node);
3454                         bemit_immediate(value, false);
3455                 }
3456         } else {
3457                 const arch_register_t *in = get_in_reg(node, n_ia32_Store_val);
3458
3459                 if (in->index == REG_EAX) {
3460                         ir_node   *base      = get_irn_n(node, n_ia32_base);
3461                         int        has_base  = !is_ia32_NoReg_GP(base);
3462                         ir_node   *index     = get_irn_n(node, n_ia32_index);
3463                         int        has_index = !is_ia32_NoReg_GP(index);
3464                         if (!has_base && !has_index) {
3465                                 ir_entity *ent  = get_ia32_am_sc(node);
3466                                 int        offs = get_ia32_am_offs_int(node);
3467                                 /* store to constant address from EAX can be encoded as
3468                                  * 0xA2/0xA3 [offset]*/
3469                                 if (size == 8) {
3470                                         bemit8(0xA2);
3471                                 } else {
3472                                         if (size == 16)
3473                                                 bemit8(0x66);
3474                                         bemit8(0xA3);
3475                                 }
3476                                 bemit_entity(ent, 0, offs, false);
3477                                 return;
3478                         }
3479                 }
3480
3481                 if (size == 8) {
3482                         bemit8(0x88);
3483                 } else {
3484                         if (size == 16)
3485                                 bemit8(0x66);
3486                         bemit8(0x89);
3487                 }
3488                 bemit_mod_am(reg_gp_map[in->index], node);
3489         }
3490 }
3491
3492 static void bemit_conv_i2i(const ir_node *node)
3493 {
3494         ir_mode  *smaller_mode = get_ia32_ls_mode(node);
3495         unsigned  opcode;
3496
3497         bemit8(0x0F);
3498         /*        8 16 bit source
3499          * movzx B6 B7
3500          * movsx BE BF
3501          */
3502         opcode = 0xB6;
3503         if (mode_is_signed(smaller_mode))           opcode |= 0x08;
3504         if (get_mode_size_bits(smaller_mode) == 16) opcode |= 0x01;
3505         bemit_unop_reg(node, opcode, n_ia32_Conv_I2I_val);
3506 }
3507
3508 /**
3509  * Emit a Push.
3510  */
3511 static void bemit_push(const ir_node *node)
3512 {
3513         const ir_node *value = get_irn_n(node, n_ia32_Push_val);
3514
3515         if (is_ia32_Immediate(value)) {
3516                 const ia32_immediate_attr_t *attr
3517                         = get_ia32_immediate_attr_const(value);
3518                 unsigned size = get_signed_imm_size(attr->offset);
3519                 if (attr->symconst)
3520                         size = 4;
3521                 switch (size) {
3522                 case 1:
3523                         bemit8(0x6A);
3524                         bemit8((unsigned char)attr->offset);
3525                         break;
3526                 case 2:
3527                 case 4:
3528                         bemit8(0x68);
3529                         bemit_immediate(value, false);
3530                         break;
3531                 }
3532         } else if (is_ia32_NoReg_GP(value)) {
3533                 bemit8(0xFF);
3534                 bemit_mod_am(6, node);
3535         } else {
3536                 const arch_register_t *reg = get_in_reg(node, n_ia32_Push_val);
3537                 bemit8(0x50 + reg_gp_map[reg->index]);
3538         }
3539 }
3540
3541 /**
3542  * Emit a Pop.
3543  */
3544 static void bemit_pop(const ir_node *node)
3545 {
3546         const arch_register_t *reg = get_out_reg(node, pn_ia32_Pop_res);
3547         bemit8(0x58 + reg_gp_map[reg->index]);
3548 }
3549
3550 static void bemit_popmem(const ir_node *node)
3551 {
3552         bemit8(0x8F);
3553         bemit_mod_am(0, node);
3554 }
3555
3556 static void bemit_call(const ir_node *node)
3557 {
3558         ir_node *proc = get_irn_n(node, n_ia32_Call_addr);
3559
3560         if (is_ia32_Immediate(proc)) {
3561                 bemit8(0xE8);
3562                 bemit_immediate(proc, true);
3563         } else {
3564                 bemit_unop(node, 0xFF, 2, n_ia32_Call_addr);
3565         }
3566 }
3567
3568 static void bemit_jmp(const ir_node *dest_block)
3569 {
3570         bemit8(0xE9);
3571         bemit_jmp_destination(dest_block);
3572 }
3573
3574 static void bemit_jump(const ir_node *node)
3575 {
3576         if (can_be_fallthrough(node))
3577                 return;
3578
3579         bemit_jmp(get_cfop_target_block(node));
3580 }
3581
3582 static void bemit_jcc(int pnc, const ir_node *dest_block)
3583 {
3584         unsigned char cc = pnc2cc(pnc);
3585         bemit8(0x0F);
3586         bemit8(0x80 + cc);
3587         bemit_jmp_destination(dest_block);
3588 }
3589
3590 static void bemit_jp(bool odd, const ir_node *dest_block)
3591 {
3592         bemit8(0x0F);
3593         bemit8(0x8A + odd);
3594         bemit_jmp_destination(dest_block);
3595 }
3596
3597 static void bemit_ia32_jcc(const ir_node *node)
3598 {
3599         int            pnc = get_ia32_condcode(node);
3600         const ir_node *proj_true;
3601         const ir_node *proj_false;
3602         const ir_node *dest_true;
3603         const ir_node *dest_false;
3604         const ir_node *block;
3605
3606         pnc = determine_final_pnc(node, 0, pnc);
3607
3608         /* get both Projs */
3609         proj_true = get_proj(node, pn_ia32_Jcc_true);
3610         assert(proj_true && "Jcc without true Proj");
3611
3612         proj_false = get_proj(node, pn_ia32_Jcc_false);
3613         assert(proj_false && "Jcc without false Proj");
3614
3615         block = get_nodes_block(node);
3616
3617         if (can_be_fallthrough(proj_true)) {
3618                 /* exchange both proj's so the second one can be omitted */
3619                 const ir_node *t = proj_true;
3620
3621                 proj_true  = proj_false;
3622                 proj_false = t;
3623                 pnc        = ia32_get_negated_pnc(pnc);
3624         }
3625
3626         dest_true  = get_cfop_target_block(proj_true);
3627         dest_false = get_cfop_target_block(proj_false);
3628
3629         if (pnc & ia32_pn_Cmp_float) {
3630                 /* Some floating point comparisons require a test of the parity flag,
3631                  * which indicates that the result is unordered */
3632                 switch (pnc & 15) {
3633                         case pn_Cmp_Uo: {
3634                                 bemit_jp(false, dest_true);
3635                                 break;
3636                         }
3637
3638                         case pn_Cmp_Leg:
3639                                 bemit_jp(true, dest_true);
3640                                 break;
3641
3642                         case pn_Cmp_Eq:
3643                         case pn_Cmp_Lt:
3644                         case pn_Cmp_Le:
3645                                 /* we need a local label if the false proj is a fallthrough
3646                                  * as the falseblock might have no label emitted then */
3647                                 if (can_be_fallthrough(proj_false)) {
3648                                         bemit8(0x7A);
3649                                         bemit8(0x06);  // jp + 6
3650                                 } else {
3651                                         bemit_jp(false, dest_false);
3652                                 }
3653                                 goto emit_jcc;
3654
3655                         case pn_Cmp_Ug:
3656                         case pn_Cmp_Uge:
3657                         case pn_Cmp_Ne:
3658                                 bemit_jp(false, dest_true);
3659                                 goto emit_jcc;
3660
3661                         default:
3662                                 goto emit_jcc;
3663                 }
3664         } else {
3665 emit_jcc:
3666                 bemit_jcc(pnc, dest_true);
3667         }
3668
3669         /* the second Proj might be a fallthrough */
3670         if (can_be_fallthrough(proj_false)) {
3671                 /* it's a fallthrough */
3672         } else {
3673                 bemit_jmp(dest_false);
3674         }
3675 }
3676
3677 static void bemit_switchjmp(const ir_node *node)
3678 {
3679         unsigned long          interval;
3680         int                    last_value;
3681         int                    i;
3682         jmp_tbl_t              tbl;
3683         const arch_register_t *in;
3684
3685         /* fill the table structure */
3686         generate_jump_table(&tbl, node);
3687
3688         /* two-complement's magic make this work without overflow */
3689         interval = tbl.max_value - tbl.min_value;
3690
3691         in = get_in_reg(node, 0);
3692         /* emit the table */
3693         if (get_signed_imm_size(interval) == 1) {
3694                 bemit8(0x83); // cmpl $imm8, %in
3695                 bemit_modru(in, 7);
3696                 bemit8(interval);
3697         } else {
3698                 bemit8(0x81); // cmpl $imm32, %in
3699                 bemit_modru(in, 7);
3700                 bemit32(interval);
3701         }
3702         bemit8(0x0F); // ja tbl.defProj
3703         bemit8(0x87);
3704         ia32_emitf(tbl.defProj, ".long %L - . - 4\n");
3705
3706         if (tbl.num_branches > 1) {
3707                 /* create table */
3708                 bemit8(0xFF); // jmp *tbl.label(,%in,4)
3709                 bemit8(MOD_IND | ENC_REG(4) | ENC_RM(0x04));
3710                 bemit8(ENC_SIB(2, reg_gp_map[in->index], 0x05));
3711                 be_emit_irprintf("\t.long %s\n", tbl.label);
3712
3713                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
3714                 be_emit_cstring(".align 4\n");
3715                 be_emit_irprintf("%s:\n", tbl.label);
3716
3717                 last_value = tbl.branches[0].value;
3718                 for (i = 0; i != tbl.num_branches; ++i) {
3719                         while (last_value != tbl.branches[i].value) {
3720                                 ia32_emitf(tbl.defProj, ".long %L\n");
3721                                 ++last_value;
3722                         }
3723                         ia32_emitf(tbl.branches[i].target, ".long %L\n");
3724                         ++last_value;
3725                 }
3726                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
3727         } else {
3728                 /* one jump is enough */
3729                 panic("switch only has one case");
3730                 //ia32_emitf(tbl.branches[0].target, "\tjmp %L\n");
3731         }
3732
3733         be_emit_write_line();
3734
3735         free(tbl.branches);
3736 }
3737
3738 /**
3739  * Emits a return.
3740  */
3741 static void bemit_return(const ir_node *node)
3742 {
3743         unsigned pop = be_Return_get_pop(node);
3744         if (pop > 0 || be_Return_get_emit_pop(node)) {
3745                 bemit8(0xC2);
3746                 assert(pop <= 0xffff);
3747                 bemit16(pop);
3748         } else {
3749                 bemit8(0xC3);
3750         }
3751 }
3752
3753 static void bemit_subsp(const ir_node *node)
3754 {
3755         const arch_register_t *out;
3756         /* sub %in, %esp */
3757         bemit_sub(node);
3758         /* mov %esp, %out */
3759         bemit8(0x8B);
3760         out = get_out_reg(node, 1);
3761         bemit8(MOD_REG | ENC_REG(reg_gp_map[out->index]) | ENC_RM(0x04));
3762 }
3763
3764 static void bemit_incsp(const ir_node *node)
3765 {
3766         int                    offs;
3767         const arch_register_t *reg;
3768         unsigned               size;
3769         unsigned               ext;
3770
3771         offs = be_get_IncSP_offset(node);
3772         if (offs == 0)
3773                 return;
3774
3775         if (offs > 0) {
3776                 ext = 5; /* sub */
3777         } else {
3778                 ext = 0; /* add */
3779                 offs = -offs;
3780         }
3781
3782         size = get_signed_imm_size(offs);
3783         bemit8(size == 1 ? 0x83 : 0x81);
3784
3785         reg  = get_out_reg(node, 0);
3786         bemit_modru(reg, ext);
3787
3788         if (size == 1) {
3789                 bemit8(offs);
3790         } else {
3791                 bemit32(offs);
3792         }
3793 }
3794
3795 static void bemit_copybi(const ir_node *node)
3796 {
3797         unsigned size = get_ia32_copyb_size(node);
3798         if (size & 1)
3799                 bemit8(0xA4); // movsb
3800         if (size & 2) {
3801                 bemit8(0x66);
3802                 bemit8(0xA5); // movsw
3803         }
3804         size >>= 2;
3805         while (size--) {
3806                 bemit8(0xA5); // movsl
3807         }
3808 }
3809
3810 static void bemit_fbinop(const ir_node *node, unsigned code, unsigned code_to)
3811 {
3812         if (get_ia32_op_type(node) == ia32_Normal) {
3813                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
3814                 const arch_register_t *in1      = x87_attr->x87[0];
3815                 const arch_register_t *in       = x87_attr->x87[1];
3816                 const arch_register_t *out      = x87_attr->x87[2];
3817
3818                 if (out == NULL) {
3819                         out = in1;
3820                 } else if (out == in) {
3821                         in = in1;
3822                 }
3823
3824                 if (out->index == 0) {
3825                         bemit8(0xD8);
3826                         bemit8(MOD_REG | ENC_REG(code) | ENC_RM(in->index));
3827                 } else {
3828                         bemit8(0xDC);
3829                         bemit8(MOD_REG | ENC_REG(code_to) | ENC_RM(out->index));
3830                 }
3831         } else {
3832                 if (get_mode_size_bits(get_ia32_ls_mode(node)) == 32) {
3833                         bemit8(0xD8);
3834                 } else {
3835                         bemit8(0xDC);
3836                 }
3837                 bemit_mod_am(code, node);
3838         }
3839 }
3840
3841 static void bemit_fbinopp(const ir_node *node, unsigned const code)
3842 {
3843         const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
3844         const arch_register_t *out      = x87_attr->x87[2];
3845         bemit8(0xDE);
3846         bemit8(code + out->index);
3847 }
3848
3849 static void bemit_fabs(const ir_node *node)
3850 {
3851         (void)node;
3852
3853         bemit8(0xD9);
3854         bemit8(0xE1);
3855 }
3856
3857 static void bemit_fadd(const ir_node *node)
3858 {
3859         bemit_fbinop(node, 0, 0);
3860 }
3861
3862 static void bemit_faddp(const ir_node *node)
3863 {
3864         bemit_fbinopp(node, 0xC0);
3865 }
3866
3867 static void bemit_fchs(const ir_node *node)
3868 {
3869         (void)node;
3870
3871         bemit8(0xD9);
3872         bemit8(0xE0);
3873 }
3874
3875 static void bemit_fdiv(const ir_node *node)
3876 {
3877         bemit_fbinop(node, 6, 7);
3878 }
3879
3880 static void bemit_fdivp(const ir_node *node)
3881 {
3882         bemit_fbinopp(node, 0xF8);
3883 }
3884
3885 static void bemit_fdivr(const ir_node *node)
3886 {
3887         bemit_fbinop(node, 7, 6);
3888 }
3889
3890 static void bemit_fdivrp(const ir_node *node)
3891 {
3892         bemit_fbinopp(node, 0xF0);
3893 }
3894
3895 static void bemit_fild(const ir_node *node)
3896 {
3897         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3898                 case 16:
3899                         bemit8(0xDF); // filds
3900                         bemit_mod_am(0, node);
3901                         return;
3902
3903                 case 32:
3904                         bemit8(0xDB); // fildl
3905                         bemit_mod_am(0, node);
3906                         return;
3907
3908                 case 64:
3909                         bemit8(0xDF); // fildll
3910                         bemit_mod_am(5, node);
3911                         return;
3912
3913                 default:
3914                         panic("invalid mode size");
3915         }
3916 }
3917
3918 static void bemit_fist(const ir_node *node)
3919 {
3920         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3921                 case 16:
3922                         bemit8(0xDF); // fists
3923                         break;
3924
3925                 case 32:
3926                         bemit8(0xDB); // fistl
3927                         break;
3928
3929                 default:
3930                         panic("invalid mode size");
3931         }
3932         bemit_mod_am(2, node);
3933 }
3934
3935 static void bemit_fistp(const ir_node *node)
3936 {
3937         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3938                 case 16:
3939                         bemit8(0xDF); // fistps
3940                         bemit_mod_am(3, node);
3941                         return;
3942
3943                 case 32:
3944                         bemit8(0xDB); // fistpl
3945                         bemit_mod_am(3, node);
3946                         return;
3947
3948                 case 64:
3949                         bemit8(0xDF); // fistpll
3950                         bemit_mod_am(7, node);
3951                         return;
3952
3953                 default:
3954                         panic("invalid mode size");
3955         }
3956 }
3957
3958 static void bemit_fld(const ir_node *node)
3959 {
3960         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
3961                 case 32:
3962                         bemit8(0xD9); // flds
3963                         bemit_mod_am(0, node);
3964                         return;
3965
3966                 case 64:
3967                         bemit8(0xDD); // fldl
3968                         bemit_mod_am(0, node);
3969                         return;
3970
3971                 case 80:
3972                 case 96:
3973                         bemit8(0xDB); // fldt
3974                         bemit_mod_am(5, node);
3975                         return;
3976
3977                 default:
3978                         panic("invalid mode size");
3979         }
3980 }
3981
3982 static void bemit_fld1(const ir_node *node)
3983 {
3984         (void)node;
3985         bemit8(0xD9);
3986         bemit8(0xE8); // fld1
3987 }
3988
3989 static void bemit_fldcw(const ir_node *node)
3990 {
3991         bemit8(0xD9); // fldcw
3992         bemit_mod_am(5, node);
3993 }
3994
3995 static void bemit_fldz(const ir_node *node)
3996 {
3997         (void)node;
3998         bemit8(0xD9);
3999         bemit8(0xEE); // fldz
4000 }
4001
4002 static void bemit_fmul(const ir_node *node)
4003 {
4004         bemit_fbinop(node, 1, 1);
4005 }
4006
4007 static void bemit_fmulp(const ir_node *node)
4008 {
4009         bemit_fbinopp(node, 0xC8);
4010 }
4011
4012 static void bemit_fpop(const ir_node *node)
4013 {
4014         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4015         bemit8(0xDD);
4016         bemit8(0xD8 + attr->x87[0]->index);
4017 }
4018
4019 static void bemit_fpush(const ir_node *node)
4020 {
4021         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4022         bemit8(0xD9);
4023         bemit8(0xC0 + attr->x87[0]->index);
4024 }
4025
4026 static void bemit_fpushcopy(const ir_node *node)
4027 {
4028         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4029         bemit8(0xD9);
4030         bemit8(0xC0 + attr->x87[0]->index);
4031 }
4032
4033 static void bemit_fst(const ir_node *node)
4034 {
4035         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
4036                 case 32:
4037                         bemit8(0xD9); // fsts
4038                         break;
4039
4040                 case 64:
4041                         bemit8(0xDD); // fstl
4042                         break;
4043
4044                 default:
4045                         panic("invalid mode size");
4046         }
4047         bemit_mod_am(2, node);
4048 }
4049
4050 static void bemit_fstp(const ir_node *node)
4051 {
4052         switch (get_mode_size_bits(get_ia32_ls_mode(node))) {
4053                 case 32:
4054                         bemit8(0xD9); // fstps
4055                         bemit_mod_am(3, node);
4056                         return;
4057
4058                 case 64:
4059                         bemit8(0xDD); // fstpl
4060                         bemit_mod_am(3, node);
4061                         return;
4062
4063                 case 80:
4064                 case 96:
4065                         bemit8(0xDB); // fstpt
4066                         bemit_mod_am(7, node);
4067                         return;
4068
4069                 default:
4070                         panic("invalid mode size");
4071         }
4072 }
4073
4074 static void bemit_fsub(const ir_node *node)
4075 {
4076         bemit_fbinop(node, 4, 5);
4077 }
4078
4079 static void bemit_fsubp(const ir_node *node)
4080 {
4081         bemit_fbinopp(node, 0xE8);
4082 }
4083
4084 static void bemit_fsubr(const ir_node *node)
4085 {
4086         bemit_fbinop(node, 5, 4);
4087 }
4088
4089 static void bemit_fsubrp(const ir_node *node)
4090 {
4091         bemit_fbinopp(node, 0xE0);
4092 }
4093
4094 static void bemit_fnstcw(const ir_node *node)
4095 {
4096         bemit8(0xD9); // fnstcw
4097         bemit_mod_am(7, node);
4098 }
4099
4100 static void bemit_fnstsw(void)
4101 {
4102         bemit8(0xDF); // fnstsw %ax
4103         bemit8(0xE0);
4104 }
4105
4106 static void bemit_ftstfnstsw(const ir_node *node)
4107 {
4108         (void)node;
4109
4110         bemit8(0xD9); // ftst
4111         bemit8(0xE4);
4112         bemit_fnstsw();
4113 }
4114
4115 static void bemit_fucomi(const ir_node *node)
4116 {
4117         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4118         bemit8(0xDB); // fucomi
4119         bemit8(0xE8 + attr->x87[1]->index);
4120 }
4121
4122 static void bemit_fucomip(const ir_node *node)
4123 {
4124         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4125         bemit8(0xDF); // fucomip
4126         bemit8(0xE8 + attr->x87[1]->index);
4127 }
4128
4129 static void bemit_fucomfnstsw(const ir_node *node)
4130 {
4131         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4132         bemit8(0xDD); // fucom
4133         bemit8(0xE0 + attr->x87[1]->index);
4134         bemit_fnstsw();
4135 }
4136
4137 static void bemit_fucompfnstsw(const ir_node *node)
4138 {
4139         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4140         bemit8(0xDD); // fucomp
4141         bemit8(0xE8 + attr->x87[1]->index);
4142         bemit_fnstsw();
4143 }
4144
4145 static void bemit_fucomppfnstsw(const ir_node *node)
4146 {
4147         (void)node;
4148
4149         bemit8(0xDA); // fucompp
4150         bemit8(0xE9);
4151         bemit_fnstsw();
4152 }
4153
4154 static void bemit_fxch(const ir_node *node)
4155 {
4156         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
4157         bemit8(0xD9);
4158         bemit8(0xC8 + attr->x87[0]->index);
4159 }
4160
4161 /**
4162  * The type of a emitter function.
4163  */
4164 typedef void (*emit_func) (const ir_node *);
4165
4166 /**
4167  * Set a node emitter. Make it a bit more type safe.
4168  */
4169 static void register_emitter(ir_op *op, emit_func func)
4170 {
4171         op->ops.generic = (op_func) func;
4172 }
4173
4174 static void ia32_register_binary_emitters(void)
4175 {
4176         /* first clear the generic function pointer for all ops */
4177         clear_irp_opcodes_generic_func();
4178
4179         /* benode emitter */
4180         register_emitter(op_be_Copy,            bemit_copy);
4181         register_emitter(op_be_CopyKeep,        bemit_copy);
4182         register_emitter(op_be_IncSP,           bemit_incsp);
4183         register_emitter(op_be_Perm,            bemit_perm);
4184         register_emitter(op_be_Return,          bemit_return);
4185         register_emitter(op_ia32_Adc,           bemit_adc);
4186         register_emitter(op_ia32_Add,           bemit_add);
4187         register_emitter(op_ia32_AddMem,        bemit_addmem);
4188         register_emitter(op_ia32_AddMem8Bit,    bemit_addmem8bit);
4189         register_emitter(op_ia32_And,           bemit_and);
4190         register_emitter(op_ia32_AndMem,        bemit_andmem);
4191         register_emitter(op_ia32_AndMem8Bit,    bemit_andmem8bit);
4192         register_emitter(op_ia32_Breakpoint,    bemit_int3);
4193         register_emitter(op_ia32_CMovcc,        bemit_cmovcc);
4194         register_emitter(op_ia32_Call,          bemit_call);
4195         register_emitter(op_ia32_Cltd,          bemit_cltd);
4196         register_emitter(op_ia32_Cmc,           bemit_cmc);
4197         register_emitter(op_ia32_Cmp,           bemit_cmp);
4198         register_emitter(op_ia32_Cmp8Bit,       bemit_cmp8bit);
4199         register_emitter(op_ia32_Const,         bemit_mov_const);
4200         register_emitter(op_ia32_Conv_I2I,      bemit_conv_i2i);
4201         register_emitter(op_ia32_Conv_I2I8Bit,  bemit_conv_i2i);
4202         register_emitter(op_ia32_CopyB_i,       bemit_copybi);
4203         register_emitter(op_ia32_Cwtl,          bemit_cwtl);
4204         register_emitter(op_ia32_Dec,           bemit_dec);
4205         register_emitter(op_ia32_DecMem,        bemit_decmem);
4206         register_emitter(op_ia32_Div,           bemit_div);
4207         register_emitter(op_ia32_FldCW,         bemit_fldcw);
4208         register_emitter(op_ia32_FnstCW,        bemit_fnstcw);
4209         register_emitter(op_ia32_FtstFnstsw,    bemit_ftstfnstsw);
4210         register_emitter(op_ia32_FucomFnstsw,   bemit_fucomfnstsw);
4211         register_emitter(op_ia32_Fucomi,        bemit_fucomi);
4212         register_emitter(op_ia32_FucompFnstsw,  bemit_fucompfnstsw);
4213         register_emitter(op_ia32_Fucompi,       bemit_fucomip);
4214         register_emitter(op_ia32_FucomppFnstsw, bemit_fucomppfnstsw);
4215         register_emitter(op_ia32_IDiv,          bemit_idiv);
4216         register_emitter(op_ia32_IJmp,          bemit_ijmp);
4217         register_emitter(op_ia32_IMul,          bemit_imul);
4218         register_emitter(op_ia32_IMul1OP,       bemit_imul1op);
4219         register_emitter(op_ia32_Inc,           bemit_inc);
4220         register_emitter(op_ia32_IncMem,        bemit_incmem);
4221         register_emitter(op_ia32_Jcc,           bemit_ia32_jcc);
4222         register_emitter(op_ia32_Jmp,           bemit_jump);
4223         register_emitter(op_ia32_LdTls,         bemit_ldtls);
4224         register_emitter(op_ia32_Lea,           bemit_lea);
4225         register_emitter(op_ia32_Leave,         bemit_leave);
4226         register_emitter(op_ia32_Load,          bemit_load);
4227         register_emitter(op_ia32_Minus64Bit,    bemit_minus64bit);
4228         register_emitter(op_ia32_Mul,           bemit_mul);
4229         register_emitter(op_ia32_Neg,           bemit_neg);
4230         register_emitter(op_ia32_NegMem,        bemit_negmem);
4231         register_emitter(op_ia32_Not,           bemit_not);
4232         register_emitter(op_ia32_NotMem,        bemit_notmem);
4233         register_emitter(op_ia32_Or,            bemit_or);
4234         register_emitter(op_ia32_OrMem,         bemit_ormem);
4235         register_emitter(op_ia32_OrMem8Bit,     bemit_ormem8bit);
4236         register_emitter(op_ia32_Pop,           bemit_pop);
4237         register_emitter(op_ia32_PopEbp,        bemit_pop);
4238         register_emitter(op_ia32_PopMem,        bemit_popmem);
4239         register_emitter(op_ia32_Push,          bemit_push);
4240         register_emitter(op_ia32_RepPrefix,     bemit_rep);
4241         register_emitter(op_ia32_Rol,           bemit_rol);
4242         register_emitter(op_ia32_RolMem,        bemit_rolmem);
4243         register_emitter(op_ia32_Ror,           bemit_ror);
4244         register_emitter(op_ia32_RorMem,        bemit_rormem);
4245         register_emitter(op_ia32_Sahf,          bemit_sahf);
4246         register_emitter(op_ia32_Sar,           bemit_sar);
4247         register_emitter(op_ia32_SarMem,        bemit_sarmem);
4248         register_emitter(op_ia32_Sbb,           bemit_sbb);
4249         register_emitter(op_ia32_Setcc,         bemit_setcc);
4250         register_emitter(op_ia32_Shl,           bemit_shl);
4251         register_emitter(op_ia32_ShlD,          bemit_shld);
4252         register_emitter(op_ia32_ShlMem,        bemit_shlmem);
4253         register_emitter(op_ia32_Shr,           bemit_shr);
4254         register_emitter(op_ia32_ShrD,          bemit_shrd);
4255         register_emitter(op_ia32_ShrMem,        bemit_shrmem);
4256         register_emitter(op_ia32_Stc,           bemit_stc);
4257         register_emitter(op_ia32_Store,         bemit_store);
4258         register_emitter(op_ia32_Store8Bit,     bemit_store);
4259         register_emitter(op_ia32_Sub,           bemit_sub);
4260         register_emitter(op_ia32_SubMem,        bemit_submem);
4261         register_emitter(op_ia32_SubMem8Bit,    bemit_submem8bit);
4262         register_emitter(op_ia32_SubSP,         bemit_subsp);
4263         register_emitter(op_ia32_SwitchJmp,     bemit_switchjmp);
4264         register_emitter(op_ia32_Test,          bemit_test);
4265         register_emitter(op_ia32_Test8Bit,      bemit_test8bit);
4266         register_emitter(op_ia32_Xor,           bemit_xor);
4267         register_emitter(op_ia32_Xor0,          bemit_xor0);
4268         register_emitter(op_ia32_XorMem,        bemit_xormem);
4269         register_emitter(op_ia32_XorMem8Bit,    bemit_xormem8bit);
4270         register_emitter(op_ia32_fabs,          bemit_fabs);
4271         register_emitter(op_ia32_fadd,          bemit_fadd);
4272         register_emitter(op_ia32_faddp,         bemit_faddp);
4273         register_emitter(op_ia32_fchs,          bemit_fchs);
4274         register_emitter(op_ia32_fdiv,          bemit_fdiv);
4275         register_emitter(op_ia32_fdivp,         bemit_fdivp);
4276         register_emitter(op_ia32_fdivr,         bemit_fdivr);
4277         register_emitter(op_ia32_fdivrp,        bemit_fdivrp);
4278         register_emitter(op_ia32_fild,          bemit_fild);
4279         register_emitter(op_ia32_fist,          bemit_fist);
4280         register_emitter(op_ia32_fistp,         bemit_fistp);
4281         register_emitter(op_ia32_fld,           bemit_fld);
4282         register_emitter(op_ia32_fld1,          bemit_fld1);
4283         register_emitter(op_ia32_fldz,          bemit_fldz);
4284         register_emitter(op_ia32_fmul,          bemit_fmul);
4285         register_emitter(op_ia32_fmulp,         bemit_fmulp);
4286         register_emitter(op_ia32_fpop,          bemit_fpop);
4287         register_emitter(op_ia32_fpush,         bemit_fpush);
4288         register_emitter(op_ia32_fpushCopy,     bemit_fpushcopy);
4289         register_emitter(op_ia32_fst,           bemit_fst);
4290         register_emitter(op_ia32_fstp,          bemit_fstp);
4291         register_emitter(op_ia32_fsub,          bemit_fsub);
4292         register_emitter(op_ia32_fsubp,         bemit_fsubp);
4293         register_emitter(op_ia32_fsubr,         bemit_fsubr);
4294         register_emitter(op_ia32_fsubrp,        bemit_fsubrp);
4295         register_emitter(op_ia32_fxch,          bemit_fxch);
4296
4297         /* ignore the following nodes */
4298         register_emitter(op_ia32_ProduceVal,   emit_Nothing);
4299         register_emitter(op_be_Barrier,        emit_Nothing);
4300         register_emitter(op_be_Keep,           emit_Nothing);
4301         register_emitter(op_be_Start,          emit_Nothing);
4302         register_emitter(op_Phi,               emit_Nothing);
4303         register_emitter(op_Start,             emit_Nothing);
4304 }
4305
4306 static void gen_binary_block(ir_node *block)
4307 {
4308         ir_node *node;
4309
4310         ia32_emit_block_header(block);
4311
4312         /* emit the contents of the block */
4313         sched_foreach(block, node) {
4314                 ia32_emit_node(node);
4315         }
4316 }
4317
4318 void ia32_gen_binary_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
4319 {
4320         ir_entity *entity     = get_irg_entity(irg);
4321         int i, n;
4322
4323         cg  = ia32_cg;
4324         isa = cg->isa;
4325
4326         ia32_register_binary_emitters();
4327
4328         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
4329
4330         /* we use links to point to target blocks */
4331         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
4332         irg_block_walk_graph(irg, ia32_gen_labels, NULL, NULL);
4333
4334         /* initialize next block links */
4335         n = ARR_LEN(cg->blk_sched);
4336         for (i = 0; i < n; ++i) {
4337                 ir_node *block = cg->blk_sched[i];
4338                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
4339
4340                 set_irn_link(block, prev);
4341         }
4342
4343         for (i = 0; i < n; ++i) {
4344                 ir_node *block = cg->blk_sched[i];
4345                 gen_binary_block(block);
4346         }
4347
4348         be_gas_emit_function_epilog(entity);
4349         be_dbg_method_end();
4350         be_emit_char('\n');
4351         be_emit_write_line();
4352
4353         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
4354 }
4355
4356
4357
4358
4359 void ia32_init_emitter(void)
4360 {
4361         lc_opt_entry_t *be_grp;
4362         lc_opt_entry_t *ia32_grp;
4363
4364         be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
4365         ia32_grp = lc_opt_get_grp(be_grp, "ia32");
4366
4367         lc_opt_add_table(ia32_grp, ia32_emitter_options);
4368
4369         build_reg_map();
4370
4371         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
4372 }