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