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