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