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