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