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