Let foreach_out_edge_kind() and foreach_out_edge_kind_safe() declare their iterator...
[libfirm] / ir / be / ia32 / ia32_x87.c
1 /*
2  * Copyright (C) 1995-2010 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 x87 support and virtual to stack
23  *              register translation for the ia32 backend.
24  * @author      Michael Beck
25  */
26 #include "config.h"
27
28 #include <assert.h>
29
30 #include "irnode_t.h"
31 #include "irop_t.h"
32 #include "irprog.h"
33 #include "iredges_t.h"
34 #include "irgmod.h"
35 #include "ircons.h"
36 #include "irgwalk.h"
37 #include "obst.h"
38 #include "pmap.h"
39 #include "array_t.h"
40 #include "pdeq.h"
41 #include "irprintf.h"
42 #include "debug.h"
43 #include "error.h"
44
45 #include "belive_t.h"
46 #include "besched.h"
47 #include "benode.h"
48 #include "bearch_ia32_t.h"
49 #include "ia32_new_nodes.h"
50 #include "gen_ia32_new_nodes.h"
51 #include "gen_ia32_regalloc_if.h"
52 #include "ia32_x87.h"
53 #include "ia32_architecture.h"
54
55 #define MASK_TOS(x)    ((x) & (N_ia32_st_REGS - 1))
56
57 /** the debug handle */
58 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
59
60 /* Forward declaration. */
61 typedef struct x87_simulator x87_simulator;
62
63 /**
64  * An exchange template.
65  * Note that our virtual functions have the same inputs
66  * and attributes as the real ones, so we can simple exchange
67  * their opcodes!
68  * Further, x87 supports inverse instructions, so we can handle them.
69  */
70 typedef struct exchange_tmpl {
71         ir_op *normal_op;       /**< the normal one */
72         ir_op *reverse_op;      /**< the reverse one if exists */
73         ir_op *normal_pop_op;   /**< the normal one with tos pop */
74         ir_op *reverse_pop_op;  /**< the reverse one with tos pop */
75 } exchange_tmpl;
76
77 /**
78  * An entry on the simulated x87 stack.
79  */
80 typedef struct st_entry {
81         int     reg_idx;        /**< the virtual register index of this stack value */
82         ir_node *node;          /**< the node that produced this value */
83 } st_entry;
84
85 /**
86  * The x87 state.
87  */
88 typedef struct x87_state {
89         st_entry st[N_ia32_st_REGS]; /**< the register stack */
90         int depth;                   /**< the current stack depth */
91         int tos;                     /**< position of the tos */
92         x87_simulator *sim;          /**< The simulator. */
93 } x87_state;
94
95 /** An empty state, used for blocks without fp instructions. */
96 static x87_state _empty = { { {0, NULL}, }, 0, 0, NULL };
97 static x87_state *empty = (x87_state *)&_empty;
98
99 /**
100  * Return values of the instruction simulator functions.
101  */
102 enum {
103         NO_NODE_ADDED = 0,  /**< No node that needs simulation was added. */
104         NODE_ADDED    = 1   /**< A node that must be simulated was added by the simulator
105                                  in the schedule AFTER the current node. */
106 };
107
108 /**
109  * The type of an instruction simulator function.
110  *
111  * @param state  the x87 state
112  * @param n      the node to be simulated
113  *
114  * @return NODE_ADDED    if a node was added AFTER n in schedule that MUST be
115  *                       simulated further
116  *         NO_NODE_ADDED otherwise
117  */
118 typedef int (*sim_func)(x87_state *state, ir_node *n);
119
120 /**
121  * A block state: Every block has a x87 state at the beginning and at the end.
122  */
123 typedef struct blk_state {
124         x87_state *begin;   /**< state at the begin or NULL if not assigned */
125         x87_state *end;     /**< state at the end or NULL if not assigned */
126 } blk_state;
127
128 /** liveness bitset for vfp registers. */
129 typedef unsigned char vfp_liveness;
130
131 /**
132  * The x87 simulator.
133  */
134 struct x87_simulator {
135         struct obstack obst;        /**< An obstack for fast allocating. */
136         pmap *blk_states;           /**< Map blocks to states. */
137         be_lv_t *lv;                /**< intrablock liveness. */
138         vfp_liveness *live;         /**< Liveness information. */
139         unsigned n_idx;             /**< The cached get_irg_last_idx() result. */
140         waitq *worklist;            /**< Worklist of blocks that must be processed. */
141         ia32_isa_t *isa;            /**< the ISA object */
142 };
143
144 /**
145  * Returns the current stack depth.
146  *
147  * @param state  the x87 state
148  *
149  * @return the x87 stack depth
150  */
151 static int x87_get_depth(const x87_state *state)
152 {
153         return state->depth;
154 }
155
156 /**
157  * Return the virtual register index at st(pos).
158  *
159  * @param state  the x87 state
160  * @param pos    a stack position
161  *
162  * @return the vfp register index that produced the value at st(pos)
163  */
164 static int x87_get_st_reg(const x87_state *state, int pos)
165 {
166         assert(pos < state->depth);
167         return state->st[MASK_TOS(state->tos + pos)].reg_idx;
168 }
169
170 #ifdef DEBUG_libfirm
171 /**
172  * Return the node at st(pos).
173  *
174  * @param state  the x87 state
175  * @param pos    a stack position
176  *
177  * @return the IR node that produced the value at st(pos)
178  */
179 static ir_node *x87_get_st_node(const x87_state *state, int pos)
180 {
181         assert(pos < state->depth);
182         return state->st[MASK_TOS(state->tos + pos)].node;
183 }
184
185 /**
186  * Dump the stack for debugging.
187  *
188  * @param state  the x87 state
189  */
190 static void x87_dump_stack(const x87_state *state)
191 {
192         int i;
193
194         for (i = state->depth - 1; i >= 0; --i) {
195                 DB((dbg, LEVEL_2, "vf%d(%+F) ", x87_get_st_reg(state, i),
196                     x87_get_st_node(state, i)));
197         }
198         DB((dbg, LEVEL_2, "<-- TOS\n"));
199 }
200 #endif /* DEBUG_libfirm */
201
202 /**
203  * Set a virtual register to st(pos).
204  *
205  * @param state    the x87 state
206  * @param reg_idx  the vfp register index that should be set
207  * @param node     the IR node that produces the value of the vfp register
208  * @param pos      the stack position where the new value should be entered
209  */
210 static void x87_set_st(x87_state *state, int reg_idx, ir_node *node, int pos)
211 {
212         assert(0 < state->depth);
213         state->st[MASK_TOS(state->tos + pos)].reg_idx = reg_idx;
214         state->st[MASK_TOS(state->tos + pos)].node    = node;
215
216         DB((dbg, LEVEL_2, "After SET_REG: "));
217         DEBUG_ONLY(x87_dump_stack(state);)
218 }
219
220 /**
221  * Set the tos virtual register.
222  *
223  * @param state    the x87 state
224  * @param reg_idx  the vfp register index that should be set
225  * @param node     the IR node that produces the value of the vfp register
226  */
227 static void x87_set_tos(x87_state *state, int reg_idx, ir_node *node)
228 {
229         x87_set_st(state, reg_idx, node, 0);
230 }
231
232 /**
233  * Swap st(0) with st(pos).
234  *
235  * @param state    the x87 state
236  * @param pos      the stack position to change the tos with
237  */
238 static void x87_fxch(x87_state *state, int pos)
239 {
240         st_entry entry;
241         assert(pos < state->depth);
242
243         entry = state->st[MASK_TOS(state->tos + pos)];
244         state->st[MASK_TOS(state->tos + pos)] = state->st[MASK_TOS(state->tos)];
245         state->st[MASK_TOS(state->tos)] = entry;
246
247         DB((dbg, LEVEL_2, "After FXCH: "));
248         DEBUG_ONLY(x87_dump_stack(state);)
249 }
250
251 /**
252  * Convert a virtual register to the stack index.
253  *
254  * @param state    the x87 state
255  * @param reg_idx  the register vfp index
256  *
257  * @return the stack position where the register is stacked
258  *         or -1 if the virtual register was not found
259  */
260 static int x87_on_stack(const x87_state *state, int reg_idx)
261 {
262         int i, tos = state->tos;
263
264         for (i = 0; i < state->depth; ++i)
265                 if (state->st[MASK_TOS(tos + i)].reg_idx == reg_idx)
266                         return i;
267         return -1;
268 }
269
270 /**
271  * Push a virtual Register onto the stack, double pushed allowed.
272  *
273  * @param state     the x87 state
274  * @param reg_idx   the register vfp index
275  * @param node      the node that produces the value of the vfp register
276  */
277 static void x87_push_dbl(x87_state *state, int reg_idx, ir_node *node)
278 {
279         assert(state->depth < N_ia32_st_REGS && "stack overrun");
280
281         ++state->depth;
282         state->tos = MASK_TOS(state->tos - 1);
283         state->st[state->tos].reg_idx = reg_idx;
284         state->st[state->tos].node    = node;
285
286         DB((dbg, LEVEL_2, "After PUSH: ")); DEBUG_ONLY(x87_dump_stack(state);)
287 }
288
289 /**
290  * Push a virtual Register onto the stack, double pushes are NOT allowed.
291  *
292  * @param state     the x87 state
293  * @param reg_idx   the register vfp index
294  * @param node      the node that produces the value of the vfp register
295  * @param dbl_push  if != 0 double pushes are allowed
296  */
297 static void x87_push(x87_state *state, int reg_idx, ir_node *node)
298 {
299         assert(x87_on_stack(state, reg_idx) == -1 && "double push");
300
301         x87_push_dbl(state, reg_idx, node);
302 }
303
304 /**
305  * Pop a virtual Register from the stack.
306  *
307  * @param state     the x87 state
308  */
309 static void x87_pop(x87_state *state)
310 {
311         assert(state->depth > 0 && "stack underrun");
312
313         --state->depth;
314         state->tos = MASK_TOS(state->tos + 1);
315
316         DB((dbg, LEVEL_2, "After POP: ")); DEBUG_ONLY(x87_dump_stack(state);)
317 }
318
319 /**
320  * Empty the fpu stack
321  *
322  * @param state     the x87 state
323  */
324 static void x87_emms(x87_state *state)
325 {
326         state->depth = 0;
327         state->tos   = 0;
328 }
329
330 /**
331  * Returns the block state of a block.
332  *
333  * @param sim    the x87 simulator handle
334  * @param block  the current block
335  *
336  * @return the block state
337  */
338 static blk_state *x87_get_bl_state(x87_simulator *sim, ir_node *block)
339 {
340         blk_state *res = pmap_get(blk_state, sim->blk_states, block);
341
342         if (res == NULL) {
343                 res = OALLOC(&sim->obst, blk_state);
344                 res->begin = NULL;
345                 res->end   = NULL;
346
347                 pmap_insert(sim->blk_states, block, res);
348         }
349
350         return res;
351 }
352
353 /**
354  * Creates a new x87 state.
355  *
356  * @param sim    the x87 simulator handle
357  *
358  * @return a new x87 state
359  */
360 static x87_state *x87_alloc_state(x87_simulator *sim)
361 {
362         x87_state *res = OALLOC(&sim->obst, x87_state);
363
364         res->sim = sim;
365         return res;
366 }
367
368 /**
369  * Clone a x87 state.
370  *
371  * @param sim    the x87 simulator handle
372  * @param src    the x87 state that will be cloned
373  *
374  * @return a cloned copy of the src state
375  */
376 static x87_state *x87_clone_state(x87_simulator *sim, const x87_state *src)
377 {
378         x87_state *res = x87_alloc_state(sim);
379
380         *res = *src;
381         return res;
382 }
383
384 /**
385  * Patch a virtual instruction into a x87 one and return
386  * the node representing the result value.
387  *
388  * @param n   the IR node to patch
389  * @param op  the x87 opcode to patch in
390  */
391 static ir_node *x87_patch_insn(ir_node *n, ir_op *op)
392 {
393         ir_mode *mode = get_irn_mode(n);
394         ir_node *res = n;
395
396         set_irn_op(n, op);
397
398         if (mode == mode_T) {
399                 /* patch all Proj's */
400                 foreach_out_edge(n, edge) {
401                         ir_node *proj = get_edge_src_irn(edge);
402                         if (is_Proj(proj)) {
403                                 mode = get_irn_mode(proj);
404                                 if (mode_is_float(mode)) {
405                                         res = proj;
406                                         set_irn_mode(proj, ia32_reg_classes[CLASS_ia32_st].mode);
407                                 }
408                         }
409                 }
410         } else if (mode_is_float(mode))
411                 set_irn_mode(n, ia32_reg_classes[CLASS_ia32_st].mode);
412         return res;
413 }
414
415 /**
416  * Returns the first Proj of a mode_T node having a given mode.
417  *
418  * @param n  the mode_T node
419  * @param m  the desired mode of the Proj
420  * @return The first Proj of mode @p m found or NULL.
421  */
422 static ir_node *get_irn_Proj_for_mode(ir_node *n, ir_mode *m)
423 {
424         assert(get_irn_mode(n) == mode_T && "Need mode_T node");
425
426         foreach_out_edge(n, edge) {
427                 ir_node *proj = get_edge_src_irn(edge);
428                 if (get_irn_mode(proj) == m)
429                         return proj;
430         }
431
432         return NULL;
433 }
434
435 /**
436  * Wrap the arch_* function here so we can check for errors.
437  */
438 static inline const arch_register_t *x87_get_irn_register(const ir_node *irn)
439 {
440         const arch_register_t *res = arch_get_irn_register(irn);
441
442         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]);
443         return res;
444 }
445
446 static inline const arch_register_t *x87_irn_get_register(const ir_node *irn,
447                                                           int pos)
448 {
449         const arch_register_t *res = arch_get_irn_register_out(irn, pos);
450
451         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]);
452         return res;
453 }
454
455 static inline const arch_register_t *get_st_reg(int index)
456 {
457         return &ia32_registers[REG_ST0 + index];
458 }
459
460 /* -------------- x87 perm --------------- */
461
462 /**
463  * Creates a fxch for shuffle.
464  *
465  * @param state     the x87 state
466  * @param pos       parameter for fxch
467  * @param block     the block were fxch is inserted
468  *
469  * Creates a new fxch node and reroute the user of the old node
470  * to the fxch.
471  *
472  * @return the fxch node
473  */
474 static ir_node *x87_fxch_shuffle(x87_state *state, int pos, ir_node *block)
475 {
476         ir_node         *fxch;
477         ia32_x87_attr_t *attr;
478
479         fxch = new_bd_ia32_fxch(NULL, block);
480         attr = get_ia32_x87_attr(fxch);
481         attr->x87[0] = get_st_reg(pos);
482         attr->x87[2] = get_st_reg(0);
483
484         keep_alive(fxch);
485
486         x87_fxch(state, pos);
487         return fxch;
488 }
489
490 /**
491  * Calculate the necessary permutations to reach dst_state.
492  *
493  * These permutations are done with fxch instructions and placed
494  * at the end of the block.
495  *
496  * Note that critical edges are removed here, so we need only
497  * a shuffle if the current block has only one successor.
498  *
499  * @param sim        the simulator handle
500  * @param block      the current block
501  * @param state      the current x87 stack state, might be modified
502  * @param dst_block  the destination block
503  * @param dst_state  destination state
504  *
505  * @return state
506  */
507 static x87_state *x87_shuffle(x87_simulator *sim, ir_node *block,
508                               x87_state *state, ir_node *dst_block,
509                               const x87_state *dst_state)
510 {
511         int      i, n_cycles, k, ri;
512         unsigned cycles[4], all_mask;
513         char     cycle_idx[4][8];
514         ir_node  *fxch, *before, *after;
515         (void) sim;
516         (void) dst_block;
517
518         assert(state->depth == dst_state->depth);
519
520         /* Some mathematics here:
521            If we have a cycle of length n that includes the tos,
522            we need n-1 exchange operations.
523            We can always add the tos and restore it, so we need
524            n+1 exchange operations for a cycle not containing the tos.
525            So, the maximum of needed operations is for a cycle of 7
526            not including the tos == 8.
527            This is the same number of ops we would need for using stores,
528            so exchange is cheaper (we save the loads).
529            On the other hand, we might need an additional exchange
530            in the next block to bring one operand on top, so the
531            number of ops in the first case is identical.
532            Further, no more than 4 cycles can exists (4 x 2).
533         */
534         all_mask = (1 << (state->depth)) - 1;
535
536         for (n_cycles = 0; all_mask; ++n_cycles) {
537                 int src_idx, dst_idx;
538
539                 /* find the first free slot */
540                 for (i = 0; i < state->depth; ++i) {
541                         if (all_mask & (1 << i)) {
542                                 all_mask &= ~(1 << i);
543
544                                 /* check if there are differences here */
545                                 if (x87_get_st_reg(state, i) != x87_get_st_reg(dst_state, i))
546                                         break;
547                         }
548                 }
549
550                 if (! all_mask) {
551                         /* no more cycles found */
552                         break;
553                 }
554
555                 k = 0;
556                 cycles[n_cycles] = (1 << i);
557                 cycle_idx[n_cycles][k++] = i;
558                 for (src_idx = i; ; src_idx = dst_idx) {
559                         dst_idx = x87_on_stack(dst_state, x87_get_st_reg(state, src_idx));
560
561                         if ((all_mask & (1 << dst_idx)) == 0)
562                                 break;
563
564                         cycle_idx[n_cycles][k++] = dst_idx;
565                         cycles[n_cycles] |=  (1 << dst_idx);
566                         all_mask       &= ~(1 << dst_idx);
567                 }
568                 cycle_idx[n_cycles][k] = -1;
569         }
570
571         if (n_cycles <= 0) {
572                 /* no permutation needed */
573                 return state;
574         }
575
576         /* Hmm: permutation needed */
577         DB((dbg, LEVEL_2, "\n%+F needs permutation: from\n", block));
578         DEBUG_ONLY(x87_dump_stack(state);)
579         DB((dbg, LEVEL_2, "                  to\n"));
580         DEBUG_ONLY(x87_dump_stack(dst_state);)
581
582
583 #ifdef DEBUG_libfirm
584         DB((dbg, LEVEL_2, "Need %d cycles\n", n_cycles));
585         for (ri = 0; ri < n_cycles; ++ri) {
586                 DB((dbg, LEVEL_2, " Ring %d:\n ", ri));
587                 for (k = 0; cycle_idx[ri][k] != -1; ++k)
588                         DB((dbg, LEVEL_2, " st%d ->", cycle_idx[ri][k]));
589                 DB((dbg, LEVEL_2, "\n"));
590         }
591 #endif
592
593         after = NULL;
594
595         /*
596          * Find the place node must be insert.
597          * We have only one successor block, so the last instruction should
598          * be a jump.
599          */
600         before = sched_last(block);
601         assert(is_cfop(before));
602
603         /* now do the permutations */
604         for (ri = 0; ri < n_cycles; ++ri) {
605                 if ((cycles[ri] & 1) == 0) {
606                         /* this cycle does not include the tos */
607                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
608                         if (after)
609                                 sched_add_after(after, fxch);
610                         else
611                                 sched_add_before(before, fxch);
612                         after = fxch;
613                 }
614                 for (k = 1; cycle_idx[ri][k] != -1; ++k) {
615                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][k], block);
616                         if (after)
617                                 sched_add_after(after, fxch);
618                         else
619                                 sched_add_before(before, fxch);
620                         after = fxch;
621                 }
622                 if ((cycles[ri] & 1) == 0) {
623                         /* this cycle does not include the tos */
624                         fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
625                         sched_add_after(after, fxch);
626                 }
627         }
628         return state;
629 }
630
631 /**
632  * Create a fxch node before another node.
633  *
634  * @param state   the x87 state
635  * @param n       the node after the fxch
636  * @param pos     exchange st(pos) with st(0)
637  *
638  * @return the fxch
639  */
640 static ir_node *x87_create_fxch(x87_state *state, ir_node *n, int pos)
641 {
642         ir_node         *fxch;
643         ia32_x87_attr_t *attr;
644         ir_node         *block = get_nodes_block(n);
645
646         x87_fxch(state, pos);
647
648         fxch = new_bd_ia32_fxch(NULL, block);
649         attr = get_ia32_x87_attr(fxch);
650         attr->x87[0] = get_st_reg(pos);
651         attr->x87[2] = get_st_reg(0);
652
653         keep_alive(fxch);
654
655         sched_add_before(n, fxch);
656         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fxch), attr->x87[0]->name, attr->x87[2]->name));
657         return fxch;
658 }
659
660 /**
661  * Create a fpush before node n.
662  *
663  * @param state     the x87 state
664  * @param n         the node after the fpush
665  * @param pos       push st(pos) on stack
666  * @param op_idx    replace input op_idx of n with the fpush result
667  */
668 static void x87_create_fpush(x87_state *state, ir_node *n, int pos, int op_idx)
669 {
670         ir_node               *fpush, *pred = get_irn_n(n, op_idx);
671         ia32_x87_attr_t       *attr;
672         const arch_register_t *out = x87_get_irn_register(pred);
673
674         x87_push_dbl(state, arch_register_get_index(out), pred);
675
676         fpush = new_bd_ia32_fpush(NULL, get_nodes_block(n));
677         attr  = get_ia32_x87_attr(fpush);
678         attr->x87[0] = get_st_reg(pos);
679         attr->x87[2] = get_st_reg(0);
680
681         keep_alive(fpush);
682         sched_add_before(n, fpush);
683
684         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fpush), attr->x87[0]->name, attr->x87[2]->name));
685 }
686
687 /**
688  * Create a fpop before node n.
689  *
690  * @param state   the x87 state
691  * @param n       the node after the fpop
692  * @param num     pop 1 or 2 values
693  *
694  * @return the fpop node
695  */
696 static ir_node *x87_create_fpop(x87_state *state, ir_node *n, int num)
697 {
698         ir_node         *fpop = NULL;
699         ia32_x87_attr_t *attr;
700
701         assert(num > 0);
702         do {
703                 x87_pop(state);
704                 if (ia32_cg_config.use_ffreep)
705                         fpop = new_bd_ia32_ffreep(NULL, get_nodes_block(n));
706                 else
707                         fpop = new_bd_ia32_fpop(NULL, get_nodes_block(n));
708                 attr = get_ia32_x87_attr(fpop);
709                 attr->x87[0] = get_st_reg(0);
710                 attr->x87[1] = get_st_reg(0);
711                 attr->x87[2] = get_st_reg(0);
712
713                 keep_alive(fpop);
714                 sched_add_before(n, fpop);
715                 DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fpop), attr->x87[0]->name));
716         } while (--num > 0);
717         return fpop;
718 }
719
720 /* --------------------------------- liveness ------------------------------------------ */
721
722 /**
723  * The liveness transfer function.
724  * Updates a live set over a single step from a given node to its predecessor.
725  * Everything defined at the node is removed from the set, the uses of the node get inserted.
726  *
727  * @param irn      The node at which liveness should be computed.
728  * @param live     The bitset of registers live before @p irn. This set gets modified by updating it to
729  *                 the registers live after irn.
730  *
731  * @return The live bitset.
732  */
733 static vfp_liveness vfp_liveness_transfer(ir_node *irn, vfp_liveness live)
734 {
735         int i, n;
736         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
737
738         if (get_irn_mode(irn) == mode_T) {
739                 foreach_out_edge(irn, edge) {
740                         ir_node *proj = get_edge_src_irn(edge);
741
742                         if (arch_irn_consider_in_reg_alloc(cls, proj)) {
743                                 const arch_register_t *reg = x87_get_irn_register(proj);
744                                 live &= ~(1 << arch_register_get_index(reg));
745                         }
746                 }
747         } else if (arch_irn_consider_in_reg_alloc(cls, irn)) {
748                 const arch_register_t *reg = x87_get_irn_register(irn);
749                 live &= ~(1 << arch_register_get_index(reg));
750         }
751
752         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
753                 ir_node *op = get_irn_n(irn, i);
754
755                 if (mode_is_float(get_irn_mode(op)) &&
756                                 arch_irn_consider_in_reg_alloc(cls, op)) {
757                         const arch_register_t *reg = x87_get_irn_register(op);
758                         live |= 1 << arch_register_get_index(reg);
759                 }
760         }
761         return live;
762 }
763
764 /**
765  * Put all live virtual registers at the end of a block into a bitset.
766  *
767  * @param sim      the simulator handle
768  * @param lv       the liveness information
769  * @param bl       the block
770  *
771  * @return The live bitset at the end of this block
772  */
773 static vfp_liveness vfp_liveness_end_of_block(x87_simulator *sim, const ir_node *block)
774 {
775         int i;
776         vfp_liveness live = 0;
777         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
778         const be_lv_t *lv = sim->lv;
779
780         be_lv_foreach(lv, block, be_lv_state_end, i) {
781                 const arch_register_t *reg;
782                 const ir_node *node = be_lv_get_irn(lv, block, i);
783                 if (!arch_irn_consider_in_reg_alloc(cls, node))
784                         continue;
785
786                 reg = x87_get_irn_register(node);
787                 live |= 1 << arch_register_get_index(reg);
788         }
789
790         return live;
791 }
792
793 /** get the register mask from an arch_register */
794 #define REGMASK(reg)    (1 << (arch_register_get_index(reg)))
795
796 /**
797  * Return a bitset of argument registers which are live at the end of a node.
798  *
799  * @param sim    the simulator handle
800  * @param pos    the node
801  * @param kill   kill mask for the output registers
802  *
803  * @return The live bitset.
804  */
805 static unsigned vfp_live_args_after(x87_simulator *sim, const ir_node *pos, unsigned kill)
806 {
807         unsigned idx = get_irn_idx(pos);
808
809         assert(idx < sim->n_idx);
810         return sim->live[idx] & ~kill;
811 }
812
813 /**
814  * Calculate the liveness for a whole block and cache it.
815  *
816  * @param sim   the simulator handle
817  * @param lv    the liveness handle
818  * @param block the block
819  */
820 static void update_liveness(x87_simulator *sim, ir_node *block)
821 {
822         vfp_liveness live = vfp_liveness_end_of_block(sim, block);
823         unsigned idx;
824         ir_node *irn;
825
826         /* now iterate through the block backward and cache the results */
827         sched_foreach_reverse(block, irn) {
828                 /* stop at the first Phi: this produces the live-in */
829                 if (is_Phi(irn))
830                         break;
831
832                 idx = get_irn_idx(irn);
833                 sim->live[idx] = live;
834
835                 live = vfp_liveness_transfer(irn, live);
836         }
837         idx = get_irn_idx(block);
838         sim->live[idx] = live;
839 }
840
841 /**
842  * Returns true if a register is live in a set.
843  *
844  * @param reg_idx  the vfp register index
845  * @param live     a live bitset
846  */
847 #define is_vfp_live(reg_idx, live) ((live) & (1 << (reg_idx)))
848
849 #ifdef DEBUG_libfirm
850 /**
851  * Dump liveness info.
852  *
853  * @param live  the live bitset
854  */
855 static void vfp_dump_live(vfp_liveness live)
856 {
857         int i;
858
859         DB((dbg, LEVEL_2, "Live after: "));
860         for (i = 0; i < 8; ++i) {
861                 if (live & (1 << i)) {
862                         DB((dbg, LEVEL_2, "vf%d ", i));
863                 }
864         }
865         DB((dbg, LEVEL_2, "\n"));
866 }
867 #endif /* DEBUG_libfirm */
868
869 /* --------------------------------- simulators ---------------------------------------- */
870
871 /**
872  * Simulate a virtual binop.
873  *
874  * @param state  the x87 state
875  * @param n      the node that should be simulated (and patched)
876  * @param tmpl   the template containing the 4 possible x87 opcodes
877  *
878  * @return NO_NODE_ADDED
879  */
880 static int sim_binop(x87_state *state, ir_node *n, const exchange_tmpl *tmpl)
881 {
882         int op2_idx = 0, op1_idx;
883         int out_idx, do_pop = 0;
884         ia32_x87_attr_t *attr;
885         int permuted;
886         ir_node *patched_insn;
887         ir_op *dst;
888         x87_simulator         *sim     = state->sim;
889         ir_node               *op1     = get_irn_n(n, n_ia32_binary_left);
890         ir_node               *op2     = get_irn_n(n, n_ia32_binary_right);
891         const arch_register_t *op1_reg = x87_get_irn_register(op1);
892         const arch_register_t *op2_reg = x87_get_irn_register(op2);
893         const arch_register_t *out     = x87_irn_get_register(n, pn_ia32_res);
894         int reg_index_1                = arch_register_get_index(op1_reg);
895         int reg_index_2                = arch_register_get_index(op2_reg);
896         vfp_liveness           live    = vfp_live_args_after(sim, n, REGMASK(out));
897         int                    op1_live_after;
898         int                    op2_live_after;
899
900         DB((dbg, LEVEL_1, ">>> %+F %s, %s -> %s\n", n,
901                 arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
902                 arch_register_get_name(out)));
903         DEBUG_ONLY(vfp_dump_live(live);)
904         DB((dbg, LEVEL_1, "Stack before: "));
905         DEBUG_ONLY(x87_dump_stack(state);)
906
907         op1_idx = x87_on_stack(state, reg_index_1);
908         assert(op1_idx >= 0);
909         op1_live_after = is_vfp_live(reg_index_1, live);
910
911         attr     = get_ia32_x87_attr(n);
912         permuted = attr->attr.data.ins_permuted;
913
914         if (reg_index_2 != REG_VFP_VFP_NOREG) {
915                 assert(!permuted);
916
917                 /* second operand is a vfp register */
918                 op2_idx = x87_on_stack(state, reg_index_2);
919                 assert(op2_idx >= 0);
920                 op2_live_after = is_vfp_live(reg_index_2, live);
921
922                 if (op2_live_after) {
923                         /* Second operand is live. */
924
925                         if (op1_live_after) {
926                                 /* Both operands are live: push the first one.
927                                    This works even for op1 == op2. */
928                                 x87_create_fpush(state, n, op1_idx, n_ia32_binary_right);
929                                 /* now do fxxx (tos=tos X op) */
930                                 op1_idx = 0;
931                                 op2_idx += 1;
932                                 out_idx = 0;
933                                 dst = tmpl->normal_op;
934                         } else {
935                                 /* Second live, first operand is dead here, bring it to tos. */
936                                 if (op1_idx != 0) {
937                                         x87_create_fxch(state, n, op1_idx);
938                                         if (op2_idx == 0)
939                                                 op2_idx = op1_idx;
940                                         op1_idx = 0;
941                                 }
942                                 /* now do fxxx (tos=tos X op) */
943                                 out_idx = 0;
944                                 dst = tmpl->normal_op;
945                         }
946                 } else {
947                         /* Second operand is dead. */
948                         if (op1_live_after) {
949                                 /* First operand is live: bring second to tos. */
950                                 if (op2_idx != 0) {
951                                         x87_create_fxch(state, n, op2_idx);
952                                         if (op1_idx == 0)
953                                                 op1_idx = op2_idx;
954                                         op2_idx = 0;
955                                 }
956                                 /* now do fxxxr (tos = op X tos) */
957                                 out_idx = 0;
958                                 dst = tmpl->reverse_op;
959                         } else {
960                                 /* Both operands are dead here, pop them from the stack. */
961                                 if (op2_idx == 0) {
962                                         if (op1_idx == 0) {
963                                                 /* Both are identically and on tos, no pop needed. */
964                                                 /* here fxxx (tos = tos X tos) */
965                                                 dst = tmpl->normal_op;
966                                                 out_idx = 0;
967                                         } else {
968                                                 /* now do fxxxp (op = op X tos, pop) */
969                                                 dst = tmpl->normal_pop_op;
970                                                 do_pop = 1;
971                                                 out_idx = op1_idx;
972                                         }
973                                 } else if (op1_idx == 0) {
974                                         assert(op1_idx != op2_idx);
975                                         /* now do fxxxrp (op = tos X op, pop) */
976                                         dst = tmpl->reverse_pop_op;
977                                         do_pop = 1;
978                                         out_idx = op2_idx;
979                                 } else {
980                                         /* Bring the second on top. */
981                                         x87_create_fxch(state, n, op2_idx);
982                                         if (op1_idx == op2_idx) {
983                                                 /* Both are identically and on tos now, no pop needed. */
984                                                 op1_idx = 0;
985                                                 op2_idx = 0;
986                                                 /* use fxxx (tos = tos X tos) */
987                                                 dst = tmpl->normal_op;
988                                                 out_idx = 0;
989                                         } else {
990                                                 /* op2 is on tos now */
991                                                 op2_idx = 0;
992                                                 /* use fxxxp (op = op X tos, pop) */
993                                                 dst = tmpl->normal_pop_op;
994                                                 out_idx = op1_idx;
995                                                 do_pop = 1;
996                                         }
997                                 }
998                         }
999                 }
1000         } else {
1001                 /* second operand is an address mode */
1002                 if (op1_live_after) {
1003                         /* first operand is live: push it here */
1004                         x87_create_fpush(state, n, op1_idx, n_ia32_binary_left);
1005                         op1_idx = 0;
1006                 } else {
1007                         /* first operand is dead: bring it to tos */
1008                         if (op1_idx != 0) {
1009                                 x87_create_fxch(state, n, op1_idx);
1010                                 op1_idx = 0;
1011                         }
1012                 }
1013
1014                 /* use fxxx (tos = tos X mem) */
1015                 dst = permuted ? tmpl->reverse_op : tmpl->normal_op;
1016                 out_idx = 0;
1017         }
1018
1019         patched_insn = x87_patch_insn(n, dst);
1020         x87_set_st(state, arch_register_get_index(out), patched_insn, out_idx);
1021         if (do_pop) {
1022                 x87_pop(state);
1023         }
1024
1025         /* patch the operation */
1026         attr->x87[0] = op1_reg = get_st_reg(op1_idx);
1027         if (reg_index_2 != REG_VFP_VFP_NOREG) {
1028                 attr->x87[1] = op2_reg = get_st_reg(op2_idx);
1029         }
1030         attr->x87[2] = out = get_st_reg(out_idx);
1031
1032         if (reg_index_2 != REG_VFP_VFP_NOREG) {
1033                 DB((dbg, LEVEL_1, "<<< %s %s, %s -> %s\n", get_irn_opname(n),
1034                         arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
1035                         arch_register_get_name(out)));
1036         } else {
1037                 DB((dbg, LEVEL_1, "<<< %s %s, [AM] -> %s\n", get_irn_opname(n),
1038                         arch_register_get_name(op1_reg),
1039                         arch_register_get_name(out)));
1040         }
1041
1042         return NO_NODE_ADDED;
1043 }
1044
1045 /**
1046  * Simulate a virtual Unop.
1047  *
1048  * @param state  the x87 state
1049  * @param n      the node that should be simulated (and patched)
1050  * @param op     the x87 opcode that will replace n's opcode
1051  *
1052  * @return NO_NODE_ADDED
1053  */
1054 static int sim_unop(x87_state *state, ir_node *n, ir_op *op)
1055 {
1056         int op1_idx;
1057         x87_simulator         *sim = state->sim;
1058         const arch_register_t *op1 = x87_get_irn_register(get_irn_n(n, 0));
1059         const arch_register_t *out = x87_get_irn_register(n);
1060         ia32_x87_attr_t *attr;
1061         unsigned live = vfp_live_args_after(sim, n, REGMASK(out));
1062
1063         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, out->name));
1064         DEBUG_ONLY(vfp_dump_live(live);)
1065
1066         op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1067
1068         if (is_vfp_live(arch_register_get_index(op1), live)) {
1069                 /* push the operand here */
1070                 x87_create_fpush(state, n, op1_idx, 0);
1071                 op1_idx = 0;
1072         }
1073         else {
1074                 /* operand is dead, bring it to tos */
1075                 if (op1_idx != 0) {
1076                         x87_create_fxch(state, n, op1_idx);
1077                         op1_idx = 0;
1078                 }
1079         }
1080
1081         x87_set_tos(state, arch_register_get_index(out), x87_patch_insn(n, op));
1082         attr = get_ia32_x87_attr(n);
1083         attr->x87[0] = op1 = get_st_reg(0);
1084         attr->x87[2] = out = get_st_reg(0);
1085         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), out->name));
1086
1087         return NO_NODE_ADDED;
1088 }
1089
1090 /**
1091  * Simulate a virtual Load instruction.
1092  *
1093  * @param state  the x87 state
1094  * @param n      the node that should be simulated (and patched)
1095  * @param op     the x87 opcode that will replace n's opcode
1096  *
1097  * @return NO_NODE_ADDED
1098  */
1099 static int sim_load(x87_state *state, ir_node *n, ir_op *op, int res_pos)
1100 {
1101         const arch_register_t *out = x87_irn_get_register(n, res_pos);
1102         ia32_x87_attr_t *attr;
1103
1104         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, arch_register_get_name(out)));
1105         x87_push(state, arch_register_get_index(out), x87_patch_insn(n, op));
1106         assert(out == x87_irn_get_register(n, res_pos));
1107         attr = get_ia32_x87_attr(n);
1108         attr->x87[2] = out = get_st_reg(0);
1109         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), arch_register_get_name(out)));
1110
1111         return NO_NODE_ADDED;
1112 }
1113
1114 /**
1115  * Rewire all users of @p old_val to @new_val iff they are scheduled after @p store.
1116  *
1117  * @param store   The store
1118  * @param old_val The former value
1119  * @param new_val The new value
1120  */
1121 static void collect_and_rewire_users(ir_node *store, ir_node *old_val, ir_node *new_val)
1122 {
1123         foreach_out_edge_safe(old_val, edge) {
1124                 ir_node *user = get_edge_src_irn(edge);
1125
1126                 if (! user || user == store)
1127                         continue;
1128
1129                 /* if the user is scheduled after the store: rewire */
1130                 if (sched_is_scheduled(user) && sched_comes_after(store, user)) {
1131                         int i;
1132                         /* find the input of the user pointing to the old value */
1133                         for (i = get_irn_arity(user) - 1; i >= 0; i--) {
1134                                 if (get_irn_n(user, i) == old_val)
1135                                         set_irn_n(user, i, new_val);
1136                         }
1137                 }
1138         }
1139 }
1140
1141 /**
1142  * Simulate a virtual Store.
1143  *
1144  * @param state  the x87 state
1145  * @param n      the node that should be simulated (and patched)
1146  * @param op     the x87 store opcode
1147  * @param op_p   the x87 store and pop opcode
1148  */
1149 static int sim_store(x87_state *state, ir_node *n, ir_op *op, ir_op *op_p)
1150 {
1151         ir_node               *val = get_irn_n(n, n_ia32_vfst_val);
1152         const arch_register_t *op2 = x87_get_irn_register(val);
1153         unsigned              live = vfp_live_args_after(state->sim, n, 0);
1154         int                   insn = NO_NODE_ADDED;
1155         ia32_x87_attr_t *attr;
1156         int op2_reg_idx, op2_idx, depth;
1157         int live_after_node;
1158         ir_mode *mode;
1159
1160         op2_reg_idx = arch_register_get_index(op2);
1161         op2_idx = x87_on_stack(state, op2_reg_idx);
1162         live_after_node = is_vfp_live(arch_register_get_index(op2), live);
1163         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1164         assert(op2_idx >= 0);
1165
1166         mode  = get_ia32_ls_mode(n);
1167         depth = x87_get_depth(state);
1168
1169         if (live_after_node) {
1170                 /*
1171                         Problem: fst doesn't support 96bit modes (spills), only fstp does
1172                                  fist doesn't support 64bit mode, only fistp
1173                         Solution:
1174                                 - stack not full: push value and fstp
1175                                 - stack full: fstp value and load again
1176                         Note that we cannot test on mode_E, because floats might be 96bit ...
1177                 */
1178                 if (get_mode_size_bits(mode) > 64 || (mode_is_int(mode) && get_mode_size_bits(mode) > 32)) {
1179                         if (depth < N_ia32_st_REGS) {
1180                                 /* ok, we have a free register: push + fstp */
1181                                 x87_create_fpush(state, n, op2_idx, n_ia32_vfst_val);
1182                                 x87_pop(state);
1183                                 x87_patch_insn(n, op_p);
1184                         } else {
1185                                 ir_node  *vfld, *mem, *block, *rproj, *mproj;
1186                                 ir_graph *irg   = get_irn_irg(n);
1187                                 ir_node  *nomem = get_irg_no_mem(irg);
1188
1189                                 /* stack full here: need fstp + load */
1190                                 x87_pop(state);
1191                                 x87_patch_insn(n, op_p);
1192
1193                                 block = get_nodes_block(n);
1194                                 vfld  = new_bd_ia32_vfld(NULL, block, get_irn_n(n, 0), get_irn_n(n, 1), nomem, get_ia32_ls_mode(n));
1195
1196                                 /* copy all attributes */
1197                                 set_ia32_frame_ent(vfld, get_ia32_frame_ent(n));
1198                                 if (is_ia32_use_frame(n))
1199                                         set_ia32_use_frame(vfld);
1200                                 set_ia32_op_type(vfld, ia32_AddrModeS);
1201                                 add_ia32_am_offs_int(vfld, get_ia32_am_offs_int(n));
1202                                 set_ia32_am_sc(vfld, get_ia32_am_sc(n));
1203                                 set_ia32_ls_mode(vfld, get_ia32_ls_mode(n));
1204
1205                                 rproj = new_r_Proj(vfld, get_ia32_ls_mode(vfld), pn_ia32_vfld_res);
1206                                 mproj = new_r_Proj(vfld, mode_M, pn_ia32_vfld_M);
1207                                 mem   = get_irn_Proj_for_mode(n, mode_M);
1208
1209                                 assert(mem && "Store memory not found");
1210
1211                                 arch_set_irn_register(rproj, op2);
1212
1213                                 /* reroute all former users of the store memory to the load memory */
1214                                 edges_reroute(mem, mproj);
1215                                 /* set the memory input of the load to the store memory */
1216                                 set_irn_n(vfld, n_ia32_vfld_mem, mem);
1217
1218                                 sched_add_after(n, vfld);
1219                                 sched_add_after(vfld, rproj);
1220
1221                                 /* rewire all users, scheduled after the store, to the loaded value */
1222                                 collect_and_rewire_users(n, val, rproj);
1223
1224                                 insn = NODE_ADDED;
1225                         }
1226                 } else {
1227                         /* we can only store the tos to memory */
1228                         if (op2_idx != 0)
1229                                 x87_create_fxch(state, n, op2_idx);
1230
1231                         /* mode size 64 or smaller -> use normal fst */
1232                         x87_patch_insn(n, op);
1233                 }
1234         } else {
1235                 /* we can only store the tos to memory */
1236                 if (op2_idx != 0)
1237                         x87_create_fxch(state, n, op2_idx);
1238
1239                 x87_pop(state);
1240                 x87_patch_insn(n, op_p);
1241         }
1242
1243         attr = get_ia32_x87_attr(n);
1244         attr->x87[1] = op2 = get_st_reg(0);
1245         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(op2)));
1246
1247         return insn;
1248 }
1249
1250 #define _GEN_BINOP(op, rev) \
1251 static int sim_##op(x87_state *state, ir_node *n) { \
1252         exchange_tmpl tmpl = { op_ia32_##op, op_ia32_##rev, op_ia32_##op##p, op_ia32_##rev##p }; \
1253         return sim_binop(state, n, &tmpl); \
1254 }
1255
1256 #define GEN_BINOP(op)   _GEN_BINOP(op, op)
1257 #define GEN_BINOPR(op)  _GEN_BINOP(op, op##r)
1258
1259 #define GEN_LOAD(op)                                              \
1260 static int sim_##op(x87_state *state, ir_node *n) {               \
1261         return sim_load(state, n, op_ia32_##op, pn_ia32_v##op##_res); \
1262 }
1263
1264 #define GEN_UNOP(op) \
1265 static int sim_##op(x87_state *state, ir_node *n) { \
1266         return sim_unop(state, n, op_ia32_##op); \
1267 }
1268
1269 #define GEN_STORE(op) \
1270 static int sim_##op(x87_state *state, ir_node *n) { \
1271         return sim_store(state, n, op_ia32_##op, op_ia32_##op##p); \
1272 }
1273
1274 /* all stubs */
1275 GEN_BINOP(fadd)
1276 GEN_BINOPR(fsub)
1277 GEN_BINOP(fmul)
1278 GEN_BINOPR(fdiv)
1279 GEN_BINOP(fprem)
1280
1281 GEN_UNOP(fabs)
1282 GEN_UNOP(fchs)
1283
1284 GEN_LOAD(fld)
1285 GEN_LOAD(fild)
1286 GEN_LOAD(fldz)
1287 GEN_LOAD(fld1)
1288
1289 GEN_STORE(fst)
1290 GEN_STORE(fist)
1291
1292 /**
1293  * Simulate a virtual fisttp.
1294  *
1295  * @param state  the x87 state
1296  * @param n      the node that should be simulated (and patched)
1297  *
1298  * @return NO_NODE_ADDED
1299  */
1300 static int sim_fisttp(x87_state *state, ir_node *n)
1301 {
1302         ir_node               *val = get_irn_n(n, n_ia32_vfst_val);
1303         const arch_register_t *op2 = x87_get_irn_register(val);
1304         ia32_x87_attr_t *attr;
1305         int op2_reg_idx, op2_idx;
1306
1307         op2_reg_idx = arch_register_get_index(op2);
1308         op2_idx     = x87_on_stack(state, op2_reg_idx);
1309         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1310         assert(op2_idx >= 0);
1311
1312         /* Note: although the value is still live here, it is destroyed because
1313            of the pop. The register allocator is aware of that and introduced a copy
1314            if the value must be alive. */
1315
1316         /* we can only store the tos to memory */
1317         if (op2_idx != 0)
1318                 x87_create_fxch(state, n, op2_idx);
1319
1320         x87_pop(state);
1321         x87_patch_insn(n, op_ia32_fisttp);
1322
1323         attr = get_ia32_x87_attr(n);
1324         attr->x87[1] = op2 = get_st_reg(0);
1325         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(op2)));
1326
1327         return NO_NODE_ADDED;
1328 }
1329
1330 /**
1331  * Simulate a virtual FtstFnstsw.
1332  *
1333  * @param state  the x87 state
1334  * @param n      the node that should be simulated (and patched)
1335  *
1336  * @return NO_NODE_ADDED
1337  */
1338 static int sim_FtstFnstsw(x87_state *state, ir_node *n)
1339 {
1340         x87_simulator         *sim         = state->sim;
1341         ia32_x87_attr_t       *attr        = get_ia32_x87_attr(n);
1342         ir_node               *op1_node    = get_irn_n(n, n_ia32_vFtstFnstsw_left);
1343         const arch_register_t *reg1        = x87_get_irn_register(op1_node);
1344         int                    reg_index_1 = arch_register_get_index(reg1);
1345         int                    op1_idx     = x87_on_stack(state, reg_index_1);
1346         unsigned               live        = vfp_live_args_after(sim, n, 0);
1347
1348         DB((dbg, LEVEL_1, ">>> %+F %s\n", n, arch_register_get_name(reg1)));
1349         DEBUG_ONLY(vfp_dump_live(live);)
1350         DB((dbg, LEVEL_1, "Stack before: "));
1351         DEBUG_ONLY(x87_dump_stack(state);)
1352         assert(op1_idx >= 0);
1353
1354         if (op1_idx != 0) {
1355                 /* bring the value to tos */
1356                 x87_create_fxch(state, n, op1_idx);
1357                 op1_idx = 0;
1358         }
1359
1360         /* patch the operation */
1361         x87_patch_insn(n, op_ia32_FtstFnstsw);
1362         reg1 = get_st_reg(op1_idx);
1363         attr->x87[0] = reg1;
1364         attr->x87[1] = NULL;
1365         attr->x87[2] = NULL;
1366
1367         if (!is_vfp_live(reg_index_1, live))
1368                 x87_create_fpop(state, sched_next(n), 1);
1369
1370         return NO_NODE_ADDED;
1371 }
1372
1373 /**
1374  * Simulate a Fucom
1375  *
1376  * @param state  the x87 state
1377  * @param n      the node that should be simulated (and patched)
1378  *
1379  * @return NO_NODE_ADDED
1380  */
1381 static int sim_Fucom(x87_state *state, ir_node *n)
1382 {
1383         int op1_idx;
1384         int op2_idx = -1;
1385         ia32_x87_attr_t *attr = get_ia32_x87_attr(n);
1386         ir_op *dst;
1387         x87_simulator         *sim        = state->sim;
1388         ir_node               *op1_node   = get_irn_n(n, n_ia32_vFucomFnstsw_left);
1389         ir_node               *op2_node   = get_irn_n(n, n_ia32_vFucomFnstsw_right);
1390         const arch_register_t *op1        = x87_get_irn_register(op1_node);
1391         const arch_register_t *op2        = x87_get_irn_register(op2_node);
1392         int reg_index_1 = arch_register_get_index(op1);
1393         int                    reg_index_2 = arch_register_get_index(op2);
1394         unsigned               live       = vfp_live_args_after(sim, n, 0);
1395         bool                   permuted   = attr->attr.data.ins_permuted;
1396         bool                   xchg       = false;
1397         int                    pops       = 0;
1398
1399         DB((dbg, LEVEL_1, ">>> %+F %s, %s\n", n,
1400                 arch_register_get_name(op1), arch_register_get_name(op2)));
1401         DEBUG_ONLY(vfp_dump_live(live);)
1402         DB((dbg, LEVEL_1, "Stack before: "));
1403         DEBUG_ONLY(x87_dump_stack(state);)
1404
1405         op1_idx = x87_on_stack(state, reg_index_1);
1406         assert(op1_idx >= 0);
1407
1408         /* BEWARE: check for comp a,a cases, they might happen */
1409         if (reg_index_2 != REG_VFP_VFP_NOREG) {
1410                 /* second operand is a vfp register */
1411                 op2_idx = x87_on_stack(state, reg_index_2);
1412                 assert(op2_idx >= 0);
1413
1414                 if (is_vfp_live(reg_index_2, live)) {
1415                         /* second operand is live */
1416
1417                         if (is_vfp_live(reg_index_1, live)) {
1418                                 /* both operands are live */
1419
1420                                 if (op1_idx == 0) {
1421                                         /* res = tos X op */
1422                                 } else if (op2_idx == 0) {
1423                                         /* res = op X tos */
1424                                         permuted = !permuted;
1425                                         xchg     = true;
1426                                 } else {
1427                                         /* bring the first one to tos */
1428                                         x87_create_fxch(state, n, op1_idx);
1429                                         if (op1_idx == op2_idx) {
1430                                                 op2_idx = 0;
1431                                         } else if (op2_idx == 0) {
1432                                                 op2_idx = op1_idx;
1433                                         }
1434                                         op1_idx = 0;
1435                                         /* res = tos X op */
1436                                 }
1437                         } else {
1438                                 /* second live, first operand is dead here, bring it to tos.
1439                                    This means further, op1_idx != op2_idx. */
1440                                 assert(op1_idx != op2_idx);
1441                                 if (op1_idx != 0) {
1442                                         x87_create_fxch(state, n, op1_idx);
1443                                         if (op2_idx == 0)
1444                                                 op2_idx = op1_idx;
1445                                         op1_idx = 0;
1446                                 }
1447                                 /* res = tos X op, pop */
1448                                 pops = 1;
1449                         }
1450                 } else {
1451                         /* second operand is dead */
1452                         if (is_vfp_live(reg_index_1, live)) {
1453                                 /* first operand is live: bring second to tos.
1454                                    This means further, op1_idx != op2_idx. */
1455                                 assert(op1_idx != op2_idx);
1456                                 if (op2_idx != 0) {
1457                                         x87_create_fxch(state, n, op2_idx);
1458                                         if (op1_idx == 0)
1459                                                 op1_idx = op2_idx;
1460                                         op2_idx = 0;
1461                                 }
1462                                 /* res = op X tos, pop */
1463                                 pops     = 1;
1464                                 permuted = !permuted;
1465                                 xchg     = true;
1466                         } else {
1467                                 /* both operands are dead here, check first for identity. */
1468                                 if (op1_idx == op2_idx) {
1469                                         /* identically, one pop needed */
1470                                         if (op1_idx != 0) {
1471                                                 x87_create_fxch(state, n, op1_idx);
1472                                                 op1_idx = 0;
1473                                                 op2_idx = 0;
1474                                         }
1475                                         /* res = tos X op, pop */
1476                                         pops    = 1;
1477                                 }
1478                                 /* different, move them to st and st(1) and pop both.
1479                                    The tricky part is to get one into st(1).*/
1480                                 else if (op2_idx == 1) {
1481                                         /* good, second operand is already in the right place, move the first */
1482                                         if (op1_idx != 0) {
1483                                                 /* bring the first on top */
1484                                                 x87_create_fxch(state, n, op1_idx);
1485                                                 assert(op2_idx != 0);
1486                                                 op1_idx = 0;
1487                                         }
1488                                         /* res = tos X op, pop, pop */
1489                                         pops = 2;
1490                                 } else if (op1_idx == 1) {
1491                                         /* good, first operand is already in the right place, move the second */
1492                                         if (op2_idx != 0) {
1493                                                 /* bring the first on top */
1494                                                 x87_create_fxch(state, n, op2_idx);
1495                                                 assert(op1_idx != 0);
1496                                                 op2_idx = 0;
1497                                         }
1498                                         /* res = op X tos, pop, pop */
1499                                         permuted = !permuted;
1500                                         xchg     = true;
1501                                         pops     = 2;
1502                                 } else {
1503                                         /* if one is already the TOS, we need two fxch */
1504                                         if (op1_idx == 0) {
1505                                                 /* first one is TOS, move to st(1) */
1506                                                 x87_create_fxch(state, n, 1);
1507                                                 assert(op2_idx != 1);
1508                                                 op1_idx = 1;
1509                                                 x87_create_fxch(state, n, op2_idx);
1510                                                 op2_idx = 0;
1511                                                 /* res = op X tos, pop, pop */
1512                                                 pops     = 2;
1513                                                 permuted = !permuted;
1514                                                 xchg     = true;
1515                                         } else if (op2_idx == 0) {
1516                                                 /* second one is TOS, move to st(1) */
1517                                                 x87_create_fxch(state, n, 1);
1518                                                 assert(op1_idx != 1);
1519                                                 op2_idx = 1;
1520                                                 x87_create_fxch(state, n, op1_idx);
1521                                                 op1_idx = 0;
1522                                                 /* res = tos X op, pop, pop */
1523                                                 pops    = 2;
1524                                         } else {
1525                                                 /* none of them is either TOS or st(1), 3 fxch needed */
1526                                                 x87_create_fxch(state, n, op2_idx);
1527                                                 assert(op1_idx != 0);
1528                                                 x87_create_fxch(state, n, 1);
1529                                                 op2_idx = 1;
1530                                                 x87_create_fxch(state, n, op1_idx);
1531                                                 op1_idx = 0;
1532                                                 /* res = tos X op, pop, pop */
1533                                                 pops    = 2;
1534                                         }
1535                                 }
1536                         }
1537                 }
1538         } else {
1539                 /* second operand is an address mode */
1540                 if (is_vfp_live(reg_index_1, live)) {
1541                         /* first operand is live: bring it to TOS */
1542                         if (op1_idx != 0) {
1543                                 x87_create_fxch(state, n, op1_idx);
1544                                 op1_idx = 0;
1545                         }
1546                 } else {
1547                         /* first operand is dead: bring it to tos */
1548                         if (op1_idx != 0) {
1549                                 x87_create_fxch(state, n, op1_idx);
1550                                 op1_idx = 0;
1551                         }
1552                         pops = 1;
1553                 }
1554         }
1555
1556         /* patch the operation */
1557         if (is_ia32_vFucomFnstsw(n)) {
1558                 int i;
1559
1560                 switch (pops) {
1561                 case 0: dst = op_ia32_FucomFnstsw;   break;
1562                 case 1: dst = op_ia32_FucompFnstsw;  break;
1563                 case 2: dst = op_ia32_FucomppFnstsw; break;
1564                 default: panic("invalid popcount in sim_Fucom");
1565                 }
1566
1567                 for (i = 0; i < pops; ++i) {
1568                         x87_pop(state);
1569                 }
1570         } else if (is_ia32_vFucomi(n)) {
1571                 switch (pops) {
1572                 case 0: dst = op_ia32_Fucomi;                  break;
1573                 case 1: dst = op_ia32_Fucompi; x87_pop(state); break;
1574                 case 2:
1575                         dst = op_ia32_Fucompi;
1576                         x87_pop(state);
1577                         x87_create_fpop(state, sched_next(n), 1);
1578                         break;
1579                 default: panic("invalid popcount in sim_Fucom");
1580                 }
1581         } else {
1582                 panic("invalid operation %+F in sim_FucomFnstsw", n);
1583         }
1584
1585         x87_patch_insn(n, dst);
1586         if (xchg) {
1587                 int tmp = op1_idx;
1588                 op1_idx = op2_idx;
1589                 op2_idx = tmp;
1590         }
1591
1592         op1 = get_st_reg(op1_idx);
1593         attr->x87[0] = op1;
1594         if (op2_idx >= 0) {
1595                 op2 = get_st_reg(op2_idx);
1596                 attr->x87[1] = op2;
1597         }
1598         attr->x87[2] = NULL;
1599         attr->attr.data.ins_permuted = permuted;
1600
1601         if (op2_idx >= 0) {
1602                 DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(n),
1603                         arch_register_get_name(op1), arch_register_get_name(op2)));
1604         } else {
1605                 DB((dbg, LEVEL_1, "<<< %s %s, [AM]\n", get_irn_opname(n),
1606                         arch_register_get_name(op1)));
1607         }
1608
1609         return NO_NODE_ADDED;
1610 }
1611
1612 /**
1613  * Simulate a Keep.
1614  *
1615  * @param state  the x87 state
1616  * @param n      the node that should be simulated (and patched)
1617  *
1618  * @return NO_NODE_ADDED
1619  */
1620 static int sim_Keep(x87_state *state, ir_node *node)
1621 {
1622         const ir_node         *op;
1623         const arch_register_t *op_reg;
1624         int                    reg_id;
1625         int                    op_stack_idx;
1626         unsigned               live;
1627         int                    i, arity;
1628
1629         DB((dbg, LEVEL_1, ">>> %+F\n", node));
1630
1631         arity = get_irn_arity(node);
1632         for (i = 0; i < arity; ++i) {
1633                 op      = get_irn_n(node, i);
1634                 op_reg  = arch_get_irn_register(op);
1635                 if (arch_register_get_class(op_reg) != &ia32_reg_classes[CLASS_ia32_vfp])
1636                         continue;
1637
1638                 reg_id = arch_register_get_index(op_reg);
1639                 live   = vfp_live_args_after(state->sim, node, 0);
1640
1641                 op_stack_idx = x87_on_stack(state, reg_id);
1642                 if (op_stack_idx >= 0 && !is_vfp_live(reg_id, live))
1643                         x87_create_fpop(state, sched_next(node), 1);
1644         }
1645
1646         DB((dbg, LEVEL_1, "Stack after: "));
1647         DEBUG_ONLY(x87_dump_stack(state);)
1648
1649         return NO_NODE_ADDED;
1650 }
1651
1652 /**
1653  * Keep the given node alive by adding a be_Keep.
1654  *
1655  * @param node  the node to kept alive
1656  */
1657 static void keep_float_node_alive(ir_node *node)
1658 {
1659         ir_node *block = get_nodes_block(node);
1660         ir_node *keep  = be_new_Keep(block, 1, &node);
1661
1662         assert(sched_is_scheduled(node));
1663         sched_add_after(node, keep);
1664 }
1665
1666 /**
1667  * Create a copy of a node. Recreate the node if it's a constant.
1668  *
1669  * @param state  the x87 state
1670  * @param n      the node to be copied
1671  *
1672  * @return the copy of n
1673  */
1674 static ir_node *create_Copy(x87_state *state, ir_node *n)
1675 {
1676         dbg_info *n_dbg = get_irn_dbg_info(n);
1677         ir_mode *mode = get_irn_mode(n);
1678         ir_node *block = get_nodes_block(n);
1679         ir_node *pred = get_irn_n(n, 0);
1680         ir_node *(*cnstr)(dbg_info *, ir_node *, ir_mode *) = NULL;
1681         ir_node *res;
1682         const arch_register_t *out;
1683         const arch_register_t *op1;
1684         ia32_x87_attr_t *attr;
1685
1686         /* Do not copy constants, recreate them. */
1687         switch (get_ia32_irn_opcode(pred)) {
1688         case iro_ia32_fldz:
1689                 cnstr = new_bd_ia32_fldz;
1690                 break;
1691         case iro_ia32_fld1:
1692                 cnstr = new_bd_ia32_fld1;
1693                 break;
1694         case iro_ia32_fldpi:
1695                 cnstr = new_bd_ia32_fldpi;
1696                 break;
1697         case iro_ia32_fldl2e:
1698                 cnstr = new_bd_ia32_fldl2e;
1699                 break;
1700         case iro_ia32_fldl2t:
1701                 cnstr = new_bd_ia32_fldl2t;
1702                 break;
1703         case iro_ia32_fldlg2:
1704                 cnstr = new_bd_ia32_fldlg2;
1705                 break;
1706         case iro_ia32_fldln2:
1707                 cnstr = new_bd_ia32_fldln2;
1708                 break;
1709         default:
1710                 break;
1711         }
1712
1713         out = x87_get_irn_register(n);
1714         op1 = x87_get_irn_register(pred);
1715
1716         if (cnstr != NULL) {
1717                 /* copy a constant */
1718                 res = (*cnstr)(n_dbg, block, mode);
1719
1720                 x87_push(state, arch_register_get_index(out), res);
1721
1722                 attr = get_ia32_x87_attr(res);
1723                 attr->x87[2] = get_st_reg(0);
1724         } else {
1725                 int op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1726
1727                 res = new_bd_ia32_fpushCopy(n_dbg, block, pred, mode);
1728
1729                 x87_push(state, arch_register_get_index(out), res);
1730
1731                 attr = get_ia32_x87_attr(res);
1732                 attr->x87[0] = get_st_reg(op1_idx);
1733                 attr->x87[2] = get_st_reg(0);
1734         }
1735         arch_set_irn_register(res, out);
1736
1737         return res;
1738 }
1739
1740 /**
1741  * Simulate a be_Copy.
1742  *
1743  * @param state  the x87 state
1744  * @param n      the node that should be simulated (and patched)
1745  *
1746  * @return NO_NODE_ADDED
1747  */
1748 static int sim_Copy(x87_state *state, ir_node *n)
1749 {
1750         ir_node                     *pred;
1751         const arch_register_t       *out;
1752         const arch_register_t       *op1;
1753         const arch_register_class_t *cls;
1754         ir_node                     *node, *next;
1755         int                         op1_idx, out_idx;
1756         unsigned                    live;
1757
1758         cls = arch_get_irn_reg_class(n);
1759         if (cls != &ia32_reg_classes[CLASS_ia32_vfp])
1760                 return 0;
1761
1762         pred = get_irn_n(n, 0);
1763         out  = x87_get_irn_register(n);
1764         op1  = x87_get_irn_register(pred);
1765         live = vfp_live_args_after(state->sim, n, REGMASK(out));
1766
1767         DB((dbg, LEVEL_1, ">>> %+F %s -> %s\n", n,
1768                 arch_register_get_name(op1), arch_register_get_name(out)));
1769         DEBUG_ONLY(vfp_dump_live(live);)
1770
1771         op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1772
1773         if (is_vfp_live(arch_register_get_index(op1), live)) {
1774                 /* Operand is still live, a real copy. We need here an fpush that can
1775                    hold a a register, so use the fpushCopy or recreate constants */
1776                 node = create_Copy(state, n);
1777
1778                 /* We have to make sure the old value doesn't go dead (which can happen
1779                  * when we recreate constants). As the simulator expected that value in
1780                  * the pred blocks. This is unfortunate as removing it would save us 1
1781                  * instruction, but we would have to rerun all the simulation to get
1782                  * this correct...
1783                  */
1784                 next = sched_next(n);
1785                 sched_remove(n);
1786                 exchange(n, node);
1787                 sched_add_before(next, node);
1788
1789                 if (get_irn_n_edges(pred) == 0) {
1790                         keep_float_node_alive(pred);
1791                 }
1792
1793                 DB((dbg, LEVEL_1, "<<< %+F %s -> ?\n", node, op1->name));
1794         } else {
1795                 out_idx = x87_on_stack(state, arch_register_get_index(out));
1796
1797                 if (out_idx >= 0 && out_idx != op1_idx) {
1798                         /* Matze: out already on stack? how can this happen? */
1799                         panic("invalid stack state in x87 simulator");
1800
1801 #if 0
1802                         /* op1 must be killed and placed where out is */
1803                         if (out_idx == 0) {
1804                                 ia32_x87_attr_t *attr;
1805                                 /* best case, simple remove and rename */
1806                                 x87_patch_insn(n, op_ia32_Pop);
1807                                 attr = get_ia32_x87_attr(n);
1808                                 attr->x87[0] = op1 = get_st_reg(0);
1809
1810                                 x87_pop(state);
1811                                 x87_set_st(state, arch_register_get_index(out), n, op1_idx - 1);
1812                         } else {
1813                                 ia32_x87_attr_t *attr;
1814                                 /* move op1 to tos, store and pop it */
1815                                 if (op1_idx != 0) {
1816                                         x87_create_fxch(state, n, op1_idx);
1817                                         op1_idx = 0;
1818                                 }
1819                                 x87_patch_insn(n, op_ia32_Pop);
1820                                 attr = get_ia32_x87_attr(n);
1821                                 attr->x87[0] = op1 = get_st_reg(out_idx);
1822
1823                                 x87_pop(state);
1824                                 x87_set_st(state, arch_register_get_index(out), n, out_idx - 1);
1825                         }
1826                         DB((dbg, LEVEL_1, "<<< %+F %s\n", n, op1->name));
1827 #endif
1828                 } else {
1829                         /* just a virtual copy */
1830                         x87_set_st(state, arch_register_get_index(out), get_unop_op(n), op1_idx);
1831                         /* don't remove the node to keep the verifier quiet :),
1832                            the emitter won't emit any code for the node */
1833 #if 0
1834                         sched_remove(n);
1835                         DB((dbg, LEVEL_1, "<<< KILLED %s\n", get_irn_opname(n)));
1836                         exchange(n, get_unop_op(n));
1837 #endif
1838                 }
1839         }
1840         return NO_NODE_ADDED;
1841 }
1842
1843 /**
1844  * Returns the vf0 result Proj of a Call.
1845  *
1846  * @para call  the Call node
1847  */
1848 static ir_node *get_call_result_proj(ir_node *call)
1849 {
1850         /* search the result proj */
1851         foreach_out_edge(call, edge) {
1852                 ir_node *proj = get_edge_src_irn(edge);
1853                 long pn = get_Proj_proj(proj);
1854
1855                 if (pn == pn_ia32_Call_vf0)
1856                         return proj;
1857         }
1858
1859         return NULL;
1860 }
1861
1862 /**
1863  * Simulate a ia32_Call.
1864  *
1865  * @param state      the x87 state
1866  * @param n          the node that should be simulated (and patched)
1867  *
1868  * @return NO_NODE_ADDED
1869  */
1870 static int sim_Call(x87_state *state, ir_node *n)
1871 {
1872         ir_type *call_tp = get_ia32_call_attr_const(n)->call_tp;
1873         ir_type *res_type;
1874         ir_mode *mode;
1875         ir_node *resproj;
1876         const arch_register_t *reg;
1877
1878         DB((dbg, LEVEL_1, ">>> %+F\n", n));
1879
1880         /* at the begin of a call the x87 state should be empty */
1881         assert(state->depth == 0 && "stack not empty before call");
1882
1883         if (get_method_n_ress(call_tp) <= 0)
1884                 goto end_call;
1885
1886         /*
1887          * If the called function returns a float, it is returned in st(0).
1888          * This even happens if the return value is NOT used.
1889          * Moreover, only one return result is supported.
1890          */
1891         res_type = get_method_res_type(call_tp, 0);
1892         mode     = get_type_mode(res_type);
1893
1894         if (mode == NULL || !mode_is_float(mode))
1895                 goto end_call;
1896
1897         resproj = get_call_result_proj(n);
1898         assert(resproj != NULL);
1899
1900         reg = x87_get_irn_register(resproj);
1901         x87_push(state, arch_register_get_index(reg), resproj);
1902
1903 end_call:
1904         DB((dbg, LEVEL_1, "Stack after: "));
1905         DEBUG_ONLY(x87_dump_stack(state);)
1906
1907         return NO_NODE_ADDED;
1908 }
1909
1910 /**
1911  * Simulate a be_Return.
1912  *
1913  * @param state  the x87 state
1914  * @param n      the node that should be simulated (and patched)
1915  *
1916  * @return NO_NODE_ADDED
1917  */
1918 static int sim_Return(x87_state *state, ir_node *n)
1919 {
1920         int n_res = be_Return_get_n_rets(n);
1921         int i, n_float_res = 0;
1922
1923         /* only floating point return values must reside on stack */
1924         for (i = 0; i < n_res; ++i) {
1925                 ir_node *res = get_irn_n(n, n_be_Return_val + i);
1926
1927                 if (mode_is_float(get_irn_mode(res)))
1928                         ++n_float_res;
1929         }
1930         assert(x87_get_depth(state) == n_float_res);
1931
1932         /* pop them virtually */
1933         for (i = n_float_res - 1; i >= 0; --i)
1934                 x87_pop(state);
1935
1936         return NO_NODE_ADDED;
1937 }
1938
1939 typedef struct perm_data_t {
1940         const arch_register_t *in;
1941         const arch_register_t *out;
1942 } perm_data_t;
1943
1944 /**
1945  * Simulate a be_Perm.
1946  *
1947  * @param state  the x87 state
1948  * @param irn    the node that should be simulated (and patched)
1949  *
1950  * @return NO_NODE_ADDED
1951  */
1952 static int sim_Perm(x87_state *state, ir_node *irn)
1953 {
1954         int      i, n;
1955         ir_node *pred = get_irn_n(irn, 0);
1956         int     *stack_pos;
1957
1958         /* handle only floating point Perms */
1959         if (! mode_is_float(get_irn_mode(pred)))
1960                 return NO_NODE_ADDED;
1961
1962         DB((dbg, LEVEL_1, ">>> %+F\n", irn));
1963
1964         /* Perm is a pure virtual instruction on x87.
1965            All inputs must be on the FPU stack and are pairwise
1966            different from each other.
1967            So, all we need to do is to permutate the stack state. */
1968         n = get_irn_arity(irn);
1969         NEW_ARR_A(int, stack_pos, n);
1970
1971         /* collect old stack positions */
1972         for (i = 0; i < n; ++i) {
1973                 const arch_register_t *inreg = x87_get_irn_register(get_irn_n(irn, i));
1974                 int idx = x87_on_stack(state, arch_register_get_index(inreg));
1975
1976                 assert(idx >= 0 && "Perm argument not on x87 stack");
1977
1978                 stack_pos[i] = idx;
1979         }
1980         /* now do the permutation */
1981         foreach_out_edge(irn, edge) {
1982                 ir_node               *proj = get_edge_src_irn(edge);
1983                 const arch_register_t *out  = x87_get_irn_register(proj);
1984                 long                  num   = get_Proj_proj(proj);
1985
1986                 assert(0 <= num && num < n && "More Proj's than Perm inputs");
1987                 x87_set_st(state, arch_register_get_index(out), proj, stack_pos[(unsigned)num]);
1988         }
1989         DB((dbg, LEVEL_1, "<<< %+F\n", irn));
1990
1991         return NO_NODE_ADDED;
1992 }
1993
1994 /**
1995  * Kill any dead registers at block start by popping them from the stack.
1996  *
1997  * @param sim          the simulator handle
1998  * @param block        the current block
1999  * @param start_state  the x87 state at the begin of the block
2000  *
2001  * @return the x87 state after dead register killed
2002  */
2003 static x87_state *x87_kill_deads(x87_simulator *sim, ir_node *block, x87_state *start_state)
2004 {
2005         x87_state *state = start_state;
2006         ir_node *first_insn = sched_first(block);
2007         ir_node *keep = NULL;
2008         unsigned live = vfp_live_args_after(sim, block, 0);
2009         unsigned kill_mask;
2010         int i, depth, num_pop;
2011
2012         kill_mask = 0;
2013         depth = x87_get_depth(state);
2014         for (i = depth - 1; i >= 0; --i) {
2015                 int reg = x87_get_st_reg(state, i);
2016
2017                 if (! is_vfp_live(reg, live))
2018                         kill_mask |= (1 << i);
2019         }
2020
2021         if (kill_mask) {
2022                 /* create a new state, will be changed */
2023                 state = x87_clone_state(sim, state);
2024
2025                 DB((dbg, LEVEL_1, "Killing deads:\n"));
2026                 DEBUG_ONLY(vfp_dump_live(live);)
2027                 DEBUG_ONLY(x87_dump_stack(state);)
2028
2029                 if (kill_mask != 0 && live == 0) {
2030                         /* special case: kill all registers */
2031                         if (ia32_cg_config.use_femms || ia32_cg_config.use_emms) {
2032                                 if (ia32_cg_config.use_femms) {
2033                                         /* use FEMMS on AMD processors to clear all */
2034                                         keep = new_bd_ia32_femms(NULL, block);
2035                                 } else {
2036                                         /* use EMMS to clear all */
2037                                         keep = new_bd_ia32_emms(NULL, block);
2038                                 }
2039                                 sched_add_before(first_insn, keep);
2040                                 keep_alive(keep);
2041                                 x87_emms(state);
2042                                 return state;
2043                         }
2044                 }
2045                 /* now kill registers */
2046                 while (kill_mask) {
2047                         /* we can only kill from TOS, so bring them up */
2048                         if (! (kill_mask & 1)) {
2049                                 /* search from behind, because we can to a double-pop */
2050                                 for (i = depth - 1; i >= 0; --i) {
2051                                         if (kill_mask & (1 << i)) {
2052                                                 kill_mask &= ~(1 << i);
2053                                                 kill_mask |= 1;
2054                                                 break;
2055                                         }
2056                                 }
2057
2058                                 if (keep)
2059                                         x87_set_st(state, -1, keep, i);
2060                                 x87_create_fxch(state, first_insn, i);
2061                         }
2062
2063                         if ((kill_mask & 3) == 3) {
2064                                 /* we can do a double-pop */
2065                                 num_pop = 2;
2066                         }
2067                         else {
2068                                 /* only a single pop */
2069                                 num_pop = 1;
2070                         }
2071
2072                         depth -= num_pop;
2073                         kill_mask >>= num_pop;
2074                         keep = x87_create_fpop(state, first_insn, num_pop);
2075                 }
2076                 keep_alive(keep);
2077         }
2078         return state;
2079 }
2080
2081 /**
2082  * Run a simulation and fix all virtual instructions for a block.
2083  *
2084  * @param sim          the simulator handle
2085  * @param block        the current block
2086  */
2087 static void x87_simulate_block(x87_simulator *sim, ir_node *block)
2088 {
2089         ir_node *n, *next;
2090         blk_state *bl_state = x87_get_bl_state(sim, block);
2091         x87_state *state = bl_state->begin;
2092         ir_node *start_block;
2093
2094         assert(state != NULL);
2095         /* already processed? */
2096         if (bl_state->end != NULL)
2097                 return;
2098
2099         DB((dbg, LEVEL_1, "Simulate %+F\n", block));
2100         DB((dbg, LEVEL_2, "State at Block begin:\n "));
2101         DEBUG_ONLY(x87_dump_stack(state);)
2102
2103         /* at block begin, kill all dead registers */
2104         state = x87_kill_deads(sim, block, state);
2105         /* create a new state, will be changed */
2106         state = x87_clone_state(sim, state);
2107
2108         /* beware, n might change */
2109         for (n = sched_first(block); !sched_is_end(n); n = next) {
2110                 int node_inserted;
2111                 sim_func func;
2112                 ir_op *op = get_irn_op(n);
2113
2114                 /*
2115                  * get the next node to be simulated here.
2116                  * n might be completely removed from the schedule-
2117                  */
2118                 next = sched_next(n);
2119                 if (op->ops.generic != NULL) {
2120                         func = (sim_func)op->ops.generic;
2121
2122                         /* simulate it */
2123                         node_inserted = (*func)(state, n);
2124
2125                         /*
2126                          * sim_func might have added an additional node after n,
2127                          * so update next node
2128                          * beware: n must not be changed by sim_func
2129                          * (i.e. removed from schedule) in this case
2130                          */
2131                         if (node_inserted != NO_NODE_ADDED)
2132                                 next = sched_next(n);
2133                 }
2134         }
2135
2136         start_block = get_irg_start_block(get_irn_irg(block));
2137
2138         DB((dbg, LEVEL_2, "State at Block end:\n ")); DEBUG_ONLY(x87_dump_stack(state);)
2139
2140         /* check if the state must be shuffled */
2141         foreach_block_succ(block, edge) {
2142                 ir_node *succ = get_edge_src_irn(edge);
2143                 blk_state *succ_state;
2144
2145                 if (succ == start_block)
2146                         continue;
2147
2148                 succ_state = x87_get_bl_state(sim, succ);
2149
2150                 if (succ_state->begin == NULL) {
2151                         DB((dbg, LEVEL_2, "Set begin state for succ %+F:\n", succ));
2152                         DEBUG_ONLY(x87_dump_stack(state);)
2153                         succ_state->begin = state;
2154
2155                         waitq_put(sim->worklist, succ);
2156                 } else {
2157                         DB((dbg, LEVEL_2, "succ %+F already has a state, shuffling\n", succ));
2158                         /* There is already a begin state for the successor, bad.
2159                            Do the necessary permutations.
2160                            Note that critical edges are removed, so this is always possible:
2161                            If the successor has more than one possible input, then it must
2162                            be the only one.
2163                          */
2164                         x87_shuffle(sim, block, state, succ, succ_state->begin);
2165                 }
2166         }
2167         bl_state->end = state;
2168 }
2169
2170 /**
2171  * Register a simulator function.
2172  *
2173  * @param op    the opcode to simulate
2174  * @param func  the simulator function for the opcode
2175  */
2176 static void register_sim(ir_op *op, sim_func func)
2177 {
2178         assert(op->ops.generic == NULL);
2179         op->ops.generic = (op_func) func;
2180 }
2181
2182 /**
2183  * Create a new x87 simulator.
2184  *
2185  * @param sim       a simulator handle, will be initialized
2186  * @param irg       the current graph
2187  */
2188 static void x87_init_simulator(x87_simulator *sim, ir_graph *irg)
2189 {
2190         obstack_init(&sim->obst);
2191         sim->blk_states = pmap_create();
2192         sim->n_idx      = get_irg_last_idx(irg);
2193         sim->live       = OALLOCN(&sim->obst, vfp_liveness, sim->n_idx);
2194
2195         DB((dbg, LEVEL_1, "--------------------------------\n"
2196                 "x87 Simulator started for %+F\n", irg));
2197
2198         /* set the generic function pointer of instruction we must simulate */
2199         ir_clear_opcodes_generic_func();
2200
2201         register_sim(op_ia32_Call,         sim_Call);
2202         register_sim(op_ia32_vfld,         sim_fld);
2203         register_sim(op_ia32_vfild,        sim_fild);
2204         register_sim(op_ia32_vfld1,        sim_fld1);
2205         register_sim(op_ia32_vfldz,        sim_fldz);
2206         register_sim(op_ia32_vfadd,        sim_fadd);
2207         register_sim(op_ia32_vfsub,        sim_fsub);
2208         register_sim(op_ia32_vfmul,        sim_fmul);
2209         register_sim(op_ia32_vfdiv,        sim_fdiv);
2210         register_sim(op_ia32_vfprem,       sim_fprem);
2211         register_sim(op_ia32_vfabs,        sim_fabs);
2212         register_sim(op_ia32_vfchs,        sim_fchs);
2213         register_sim(op_ia32_vfist,        sim_fist);
2214         register_sim(op_ia32_vfisttp,      sim_fisttp);
2215         register_sim(op_ia32_vfst,         sim_fst);
2216         register_sim(op_ia32_vFtstFnstsw,  sim_FtstFnstsw);
2217         register_sim(op_ia32_vFucomFnstsw, sim_Fucom);
2218         register_sim(op_ia32_vFucomi,      sim_Fucom);
2219         register_sim(op_be_Copy,           sim_Copy);
2220         register_sim(op_be_Return,         sim_Return);
2221         register_sim(op_be_Perm,           sim_Perm);
2222         register_sim(op_be_Keep,           sim_Keep);
2223 }
2224
2225 /**
2226  * Destroy a x87 simulator.
2227  *
2228  * @param sim  the simulator handle
2229  */
2230 static void x87_destroy_simulator(x87_simulator *sim)
2231 {
2232         pmap_destroy(sim->blk_states);
2233         obstack_free(&sim->obst, NULL);
2234         DB((dbg, LEVEL_1, "x87 Simulator stopped\n\n"));
2235 }
2236
2237 /**
2238  * Pre-block walker: calculate the liveness information for the block
2239  * and store it into the sim->live cache.
2240  */
2241 static void update_liveness_walker(ir_node *block, void *data)
2242 {
2243         x87_simulator *sim = (x87_simulator*)data;
2244         update_liveness(sim, block);
2245 }
2246
2247 /*
2248  * Run a simulation and fix all virtual instructions for a graph.
2249  * Replaces all virtual floating point instructions and registers
2250  * by real ones.
2251  */
2252 void ia32_x87_simulate_graph(ir_graph *irg)
2253 {
2254         /* TODO improve code quality (less executed fxch) by using execfreqs */
2255
2256         ir_node       *block, *start_block;
2257         blk_state     *bl_state;
2258         x87_simulator sim;
2259
2260         /* create the simulator */
2261         x87_init_simulator(&sim, irg);
2262
2263         start_block = get_irg_start_block(irg);
2264         bl_state    = x87_get_bl_state(&sim, start_block);
2265
2266         /* start with the empty state */
2267         bl_state->begin = empty;
2268         empty->sim      = &sim;
2269
2270         sim.worklist = new_waitq();
2271         waitq_put(sim.worklist, start_block);
2272
2273         be_assure_live_sets(irg);
2274         sim.lv = be_get_irg_liveness(irg);
2275
2276         /* Calculate the liveness for all nodes. We must precalculate this info,
2277          * because the simulator adds new nodes (possible before Phi nodes) which
2278          * would let a lazy calculation fail.
2279          * On the other hand we reduce the computation amount due to
2280          * precaching from O(n^2) to O(n) at the expense of O(n) cache memory.
2281          */
2282         irg_block_walk_graph(irg, update_liveness_walker, NULL, &sim);
2283
2284         /* iterate */
2285         do {
2286                 block = (ir_node*)waitq_get(sim.worklist);
2287                 x87_simulate_block(&sim, block);
2288         } while (! waitq_empty(sim.worklist));
2289
2290         /* kill it */
2291         del_waitq(sim.worklist);
2292         x87_destroy_simulator(&sim);
2293 }
2294
2295 /* Initializes the x87 simulator. */
2296 void ia32_init_x87(void)
2297 {
2298         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.x87");
2299 }