908e68194c2a9f826b053c54e23e5d0a2f468b08
[libfirm] / ir / be / bespillremat.c
1 /** vim: set sw=4 ts=4:
2  * @file   bespillremat.c
3  * @date   2006-04-06
4  * @author Adam M. Szalkowski & Sebastian Hack
5  *
6  * ILP based spilling & rematerialization
7  *
8  * Copyright (C) 2006 Universitaet Karlsruhe
9  * Released under the GPL
10  */
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #ifdef WITH_ILP
16
17 #include <math.h>
18
19 #include "hashptr.h"
20 #include "debug.h"
21 #include "obst.h"
22 #include "set.h"
23 #include "list.h"
24 #include "pmap.h"
25
26 #include "irprintf.h"
27 #include "irgwalk.h"
28 #include "irdump_t.h"
29 #include "irnode_t.h"
30 #include "ircons_t.h"
31 #include "irloop_t.h"
32 #include "phiclass.h"
33 #include "iredges.h"
34 #include "execfreq.h"
35
36 #include <lpp/lpp.h>
37 #include <lpp/lpp_net.h>
38 #include <lpp/lpp_cplex.h>
39 //#include <lc_pset.h>
40 #include <libcore/lc_bitset.h>
41
42 #include "be_t.h"
43 #include "belive_t.h"
44 #include "besched_t.h"
45 #include "beirgmod.h"
46 #include "bearch.h"
47 #include "benode_t.h"
48 #include "beutil.h"
49 #include "bespillremat.h"
50 #include "bespill.h"
51 #include "bepressurestat.h"
52
53 #include "bechordal_t.h"
54
55 #define BIGM 100000.0
56
57 #define DUMP_SOLUTION
58 #define DUMP_ILP
59 //#define KEEPALIVE /* keep alive all inserted remats and dump graph with remats */
60 #define COLLECT_REMATS /* enable rematerialization */
61 #define COLLECT_INVERSE_REMATS /* enable placement of inverse remats */
62 #define REMAT_WHILE_LIVE /* only remat values that are live */
63 //#define NO_ENLARGE_L1V3N355 /* do not remat after the death of some operand */
64 //#define EXECFREQ_LOOPDEPH /* compute execution frequency from loop depth only */
65 //#define MAY_DIE_AT_PRE_REMAT /* allow values to die after a pre remat */
66 #define CHECK_POST_REMAT /* check pressure after post remats (conservative but otherwise we can temporarily exceed the register pressure) */
67 #define NO_SINGLE_USE_REMATS /* do not repair schedule */
68 //#define KEEPALIVE_SPILLS
69 //#define KEEPALIVE_RELOADS
70 #define GOODWIN_REDUCTION
71
72 #define  SOLVE
73 //#define  SOLVE_LOCAL
74 #define LPP_SERVER "i44pc52"
75 #define LPP_SOLVER "cplex"
76
77 #define COST_LOAD      10
78 #define COST_STORE     50
79 #define COST_REMAT     1
80
81 #define ILP_TIMEOUT    120
82
83 #define ILP_UNDEF               -1
84
85 typedef struct _spill_ilp_t {
86         const arch_register_class_t  *cls;
87         int                           n_regs;
88         const be_chordal_env_t       *chordal_env;
89         lpp_t                        *lpp;
90         struct obstack               *obst;
91         set                          *remat_info;
92         pset                         *all_possible_remats;
93         pset                         *inverse_ops;
94 #ifdef KEEPALIVE
95         ir_node                      *keep;
96 #endif
97         set                          *values; /**< for collecting all definitions of values before running ssa-construction */
98         set                          *execfreqs;
99         pset                         *spills;
100         ir_node                      *m_unknown;
101         DEBUG_ONLY(firm_dbg_module_t * dbg);
102 } spill_ilp_t;
103
104 typedef int ilp_var_t;
105 typedef int ilp_cst_t;
106
107 typedef struct _spill_bb_t {
108         set          *ilp;
109         pset         *copys_needed;
110         ilp_var_t    *reloads;
111 } spill_bb_t;
112
113 typedef struct _remat_t {
114         const ir_node        *op;      /**< for copy_irn */
115         const ir_node        *value;   /**< the value which is being recomputed by this remat */
116         ir_node              *proj;    /**< not NULL if the above op produces a tuple */
117         int                   cost;    /**< cost of this remat */
118         int                   inverse; /**< nonzero if this is an inverse remat */
119 } remat_t;
120
121 /**
122  * Data to be attached to each IR node. For remats this contains the ilp_var
123  * for this remat and for normal ops this contains the ilp_vars for
124  * reloading each operand
125  */
126 typedef struct _op_t {
127         int             is_remat;
128         union {
129                 struct {
130                         ilp_var_t       ilp;
131                         remat_t        *remat; /** the remat this op belongs to */
132                         int             pre; /** 1, if this is a pressure-increasing remat */
133                 } remat;
134                 struct {
135                         ilp_var_t       ilp;
136                         ir_node        *op; /** the operation this live range belongs to */
137                         ilp_var_t      *reloads;
138                 } live_range;
139         } attr;
140 } op_t;
141
142 typedef struct _defs_t {
143         ir_node   *value;
144         ir_node   *spills;  /**< points to the first spill for this value (linked by link field) */
145         ir_node   *remats;  /**< points to the first definition for this value (linked by link field) */
146 } defs_t;
147
148 typedef struct _remat_info_t {
149         const ir_node       *irn; /**< the irn to which these remats belong */
150         pset                *remats; /**< possible remats for this value */
151         pset                *remats_by_operand; /**< remats with this value as operand */
152 } remat_info_t;
153
154 typedef struct _keyval_t {
155         const void          *key;
156         const void          *val;
157 } keyval_t;
158
159 typedef struct _spill_t {
160         ir_node      *irn;
161         ilp_var_t     reg_in;
162         ilp_var_t     mem_in;
163         ilp_var_t     reg_out;
164         ilp_var_t     mem_out;
165         ilp_var_t     spill;
166 } spill_t;
167
168 static INLINE int
169 has_reg_class(const spill_ilp_t * si, const ir_node * irn)
170 {
171         return chordal_has_class(si->chordal_env, irn);
172 }
173
174 #if 0
175 static int
176 cmp_remat(const void *a, const void *b)
177 {
178         const keyval_t *p = a;
179         const keyval_t *q = b;
180         const remat_t  *r = p->val;
181         const remat_t  *s = q->val;
182
183         assert(r && s);
184
185         return !(r == s || r->op == s->op);
186 }
187 #endif
188 static int
189 cmp_remat(const void *a, const void *b)
190 {
191         const remat_t  *r = a;
192         const remat_t  *s = a;
193
194         return !(r == s || r->op == s->op);
195 }
196
197 static int
198 cmp_spill(const void *a, const void *b, size_t size)
199 {
200         const spill_t *p = a;
201         const spill_t *q = b;
202
203 //      return !(p->irn == q->irn && p->bb == q->bb);
204         return !(p->irn == q->irn);
205 }
206
207 static keyval_t *
208 set_find_keyval(set * set, void * key)
209 {
210         keyval_t     query;
211
212         query.key = key;
213         return set_find(set, &query, sizeof(query), HASH_PTR(key));
214 }
215
216 static keyval_t *
217 set_insert_keyval(set * set, void * key, void * val)
218 {
219         keyval_t     query;
220
221         query.key = key;
222         query.val = val;
223         return set_insert(set, &query, sizeof(query), HASH_PTR(key));
224 }
225
226 static defs_t *
227 set_find_def(set * set, ir_node * value)
228 {
229         defs_t     query;
230
231         query.value = value;
232         return set_find(set, &query, sizeof(query), HASH_PTR(value));
233 }
234
235 static defs_t *
236 set_insert_def(set * set, ir_node * value)
237 {
238         defs_t     query;
239
240         query.value = value;
241         query.spills = NULL;
242         query.remats = NULL;
243         return set_insert(set, &query, sizeof(query), HASH_PTR(value));
244 }
245
246 static spill_t *
247 set_find_spill(set * set, ir_node * value)
248 {
249         spill_t     query;
250
251         query.irn = value;
252         return set_find(set, &query, sizeof(query), HASH_PTR(value));
253 }
254
255 #define pset_foreach(s,i) for((i)=pset_first((s)); (i); (i)=pset_next((s)))
256 #define set_foreach(s,i) for((i)=set_first((s)); (i); (i)=set_next((s)))
257 #define foreach_post_remat(s,i) for((i)=next_post_remat((s)); (i); (i)=next_post_remat((i)))
258 #define foreach_pre_remat(si,s,i) for((i)=next_pre_remat((si),(s)); (i); (i)=next_pre_remat((si),(i)))
259 #define sched_foreach_op(s,i) for((i)=sched_next_op((s));!sched_is_end((i));(i)=sched_next_op((i)))
260
261 static int
262 cmp_remat_info(const void *a, const void *b, size_t size)
263 {
264         const remat_info_t *p = a;
265         const remat_info_t *q = b;
266
267         return !(p->irn == q->irn);
268 }
269
270 static int
271 cmp_defs(const void *a, const void *b, size_t size)
272 {
273         const defs_t *p = a;
274         const defs_t *q = b;
275
276         return !(p->value == q->value);
277 }
278
279 static int
280 cmp_keyval(const void *a, const void *b, size_t size)
281 {
282         const keyval_t *p = a;
283         const keyval_t *q = b;
284
285         return !(p->key == q->key);
286 }
287
288 static double
289 execution_frequency(const spill_ilp_t * si, const ir_node * irn)
290 {
291 #define FUDGE 0.001
292         if(si->execfreqs) {
293                 if(is_Block(irn)) {
294                         return get_block_execfreq(si->execfreqs, irn) + FUDGE;
295                 } else {
296                         return get_block_execfreq(si->execfreqs, get_nodes_block(irn)) + FUDGE;
297                 }
298         } else {
299                 if(is_Block(irn))
300                         return exp(get_loop_depth(get_irn_loop(irn)) * log(10)) + FUDGE;
301                 else
302                         return exp(get_loop_depth(get_irn_loop(get_nodes_block(irn))) * log(10)) + FUDGE;
303         }
304 }
305
306 static double
307 get_cost(const spill_ilp_t * si, const ir_node * irn)
308 {
309         if(be_is_Spill(irn)) {
310                 return COST_STORE;
311         } else if(be_is_Reload(irn)){
312                 return COST_LOAD;
313         } else {
314                 return arch_get_op_estimated_cost(si->chordal_env->birg->main_env->arch_env, irn);
315         }
316
317 }
318
319 /**
320  * Checks, whether node and its operands have suitable reg classes
321  */
322 static INLINE int
323 is_rematerializable(const spill_ilp_t * si, const ir_node * irn)
324 {
325         int             i,
326                         n;
327         const arch_env_t *arch_env = si->chordal_env->birg->main_env->arch_env;
328         int               remat = (arch_irn_get_flags(arch_env, irn) & arch_irn_flags_rematerializable) != 0;
329
330 #if 0
331         if(!remat)
332                 ir_fprintf(stderr, "  Node %+F is not rematerializable\n", irn);
333 #endif
334
335         for (i = 0, n = get_irn_arity(irn); i < n && remat; ++i) {
336                 ir_node        *op = get_irn_n(irn, i);
337                 remat &= has_reg_class(si, op) || arch_irn_get_flags(arch_env, op) & arch_irn_flags_ignore || (get_irn_op(op) == op_NoMem);
338
339 //              if(!remat)
340 //                      ir_fprintf(stderr, "  Argument %d (%+F) of Node %+F has wrong regclass\n", i, op, irn);
341         }
342
343         return remat;
344 }
345
346 /**
347  * Try to create a remat from @p op with destination value @p dest_value
348  */
349 static INLINE remat_t *
350 get_remat_from_op(spill_ilp_t * si, const ir_node * dest_value, const ir_node * op)
351 {
352         remat_t  *remat = NULL;
353
354 //      if(!mode_is_datab(get_irn_mode(dest_value)))
355 //              return NULL;
356
357         if(dest_value == op) {
358                 const ir_node *proj = NULL;
359
360                 if(is_Proj(dest_value)) {
361                         op = get_irn_n(op, 0);
362                         proj = dest_value;
363                 }
364
365                 if(!is_rematerializable(si, op))
366                         return NULL;
367
368                 remat = obstack_alloc(si->obst, sizeof(*remat));
369                 remat->op = op;
370                 remat->cost = get_cost(si, op);
371                 remat->value = dest_value;
372                 remat->proj = proj;
373                 remat->inverse = 0;
374         } else {
375                 arch_inverse_t     inverse;
376                 int                i,
377                                                    n;
378
379                 /* get the index of the operand we want to retrieve by the inverse op */
380                 for (i = 0, n = get_irn_arity(op); i < n; ++i) {
381                         ir_node        *arg = get_irn_n(op, i);
382
383                         if(arg == dest_value) break;
384                 }
385                 if(i == n) return NULL;
386
387                 DBG((si->dbg, LEVEL_5, "\t  requesting inverse op for argument %d of op %+F\n", i, op));
388
389                 /* else ask the backend to give an inverse op */
390                 if(arch_get_inverse(si->chordal_env->birg->main_env->arch_env, op, i, &inverse, si->obst)) {
391                         int   i;
392
393                         DBG((si->dbg, LEVEL_4, "\t  backend gave us an inverse op with %d nodes and cost %d\n", inverse.n, inverse.costs));
394
395                         assert(inverse.n > 0 && "inverse op should have at least one node");
396
397                         for(i=0; i<inverse.n; ++i) {
398                                 pset_insert_ptr(si->inverse_ops, inverse.nodes[i]);
399                         }
400
401                         if(inverse.n <= 2) {
402                                 remat = obstack_alloc(si->obst, sizeof(*remat));
403                                 remat->op = inverse.nodes[0];
404                                 remat->cost = inverse.costs;
405                                 remat->value = dest_value;
406                                 remat->proj = (inverse.n==2)?inverse.nodes[1]:NULL;
407                                 remat->inverse = 1;
408
409                                 assert(is_Proj(remat->proj));
410                         } else {
411                                 assert(0 && "I can not handle remats with more than 2 nodes");
412                         }
413                 }
414         }
415
416         if(remat) {
417                 if(remat->proj) {
418                         DBG((si->dbg, LEVEL_3, "\t >Found remat %+F for %+F from %+F with %+F\n", remat->op, dest_value, op, remat->proj));
419                 } else {
420                         DBG((si->dbg, LEVEL_3, "\t >Found remat %+F for %+F from %+F\n", remat->op, dest_value, op));
421                 }
422         }
423         return remat;
424 }
425
426
427 static INLINE void
428 add_remat(const spill_ilp_t * si, const remat_t * remat)
429 {
430         remat_info_t    *remat_info,
431                      query;
432         int              i,
433                                          n;
434
435         assert(remat->op);
436         assert(remat->value);
437
438         query.irn = remat->value;
439         query.remats = NULL;
440         query.remats_by_operand = NULL;
441         remat_info = set_insert(si->remat_info, &query, sizeof(query), HASH_PTR(remat->value));
442
443         if(remat_info->remats == NULL) {
444                 remat_info->remats = new_pset(cmp_remat, 4096);
445         }
446         pset_insert(remat_info->remats, remat, HASH_PTR(remat->op));
447
448         /* insert the remat into the remats_be_operand set of each argument of the remat op */
449         for (i = 0, n = get_irn_arity(remat->op); i < n; ++i) {
450                 ir_node        *arg = get_irn_n(remat->op, i);
451
452                 query.irn = arg;
453                 query.remats = NULL;
454                 query.remats_by_operand = NULL;
455                 remat_info = set_insert(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
456
457                 if(remat_info->remats_by_operand == NULL) {
458                         remat_info->remats_by_operand = new_pset(cmp_remat, 4096);
459                 }
460                 pset_insert(remat_info->remats_by_operand, remat, HASH_PTR(remat->op));
461         }
462 }
463
464 static int
465 get_irn_n_nonremat_edges(const spill_ilp_t * si, const ir_node * irn)
466 {
467         const ir_edge_t   *edge = get_irn_out_edge_first(irn);
468         int                i = 0;
469
470         while(edge) {
471                 if(!pset_find_ptr(si->inverse_ops, edge->src)) {
472                         ++i;
473                 }
474                 edge = get_irn_out_edge_next(irn, edge);
475         }
476
477         return i;
478 }
479
480 static INLINE void
481 get_remats_from_op(spill_ilp_t * si, const ir_node * op)
482 {
483         int       i,
484                       n;
485         remat_t *remat;
486
487 #ifdef NO_SINGLE_USE_REMATS
488         if(has_reg_class(si, op) && (get_irn_n_nonremat_edges(si, op) > 1)) {
489 #else
490         if(has_reg_class(si, op)) {
491 #endif
492                 remat = get_remat_from_op(si, op, op);
493                 if(remat) {
494                         add_remat(si, remat);
495                 }
496         }
497
498 #ifdef COLLECT_INVERSE_REMATS
499         /* repeat the whole stuff for each remat retrieved by get_remat_from_op(op, arg)
500            for each arg */
501         for (i = 0, n = get_irn_arity(op); i < n; ++i) {
502                 ir_node        *arg = get_irn_n(op, i);
503
504                 if(has_reg_class(si, arg)) {
505                         /* try to get an inverse remat */
506                         remat = get_remat_from_op(si, arg, op);
507                         if(remat) {
508                                 add_remat(si, remat);
509                         }
510                 }
511         }
512 #endif
513
514 }
515
516 static INLINE int
517 value_is_defined_before(const spill_ilp_t * si, const ir_node * pos, const ir_node * val)
518 {
519         ir_node *block;
520         ir_node *def_block = get_nodes_block(val);
521         int      ret;
522
523         if(val == pos)
524                 return 0;
525
526         /* if pos is at end of a basic block */
527         if(is_Block(pos)) {
528                 ret = (pos == def_block || block_dominates(def_block, pos));
529 //              ir_fprintf(stderr, "(def(bb)=%d) ", ret);
530                 return ret;
531         }
532
533         /* else if this is a normal operation */
534         block = get_nodes_block(pos);
535         if(block == def_block) {
536                 if(!sched_is_scheduled(val)) return 1;
537
538                 ret = sched_comes_after(val, pos);
539 //              ir_fprintf(stderr, "(def(same block)=%d) ",ret);
540                 return ret;
541         }
542
543         ret = block_dominates(def_block, block);
544 //      ir_fprintf(stderr, "(def(other block)=%d) ", ret);
545         return ret;
546 }
547
548 static INLINE ir_node *
549 sched_block_last_noncf(const spill_ilp_t * si, const ir_node * bb)
550 {
551     return sched_skip((ir_node*)bb, 0, sched_skip_cf_predicator, (void *) si->chordal_env->birg->main_env->arch_env);
552 }
553
554 /**
555  * Returns first non-Phi node of block @p bb
556  */
557 static INLINE ir_node *
558 sched_block_first_nonphi(const ir_node * bb)
559 {
560         return sched_skip((ir_node*)bb, 1, sched_skip_phi_predicator, NULL);
561 }
562
563 static int
564 sched_skip_proj_predicator(const ir_node * irn, void * data)
565 {
566         return (is_Proj(irn));
567 }
568
569 static INLINE ir_node *
570 sched_next_nonproj(const ir_node * irn, int forward)
571 {
572         return sched_skip((ir_node*)irn, forward, sched_skip_proj_predicator, NULL);
573 }
574
575 /**
576  * Returns next operation node (non-Proj) after @p irn
577  * or the basic block of this node
578  */
579 static INLINE ir_node *
580 sched_next_op(const ir_node * irn)
581 {
582         ir_node *next = sched_next(irn);
583
584         if(is_Block(next))
585                 return next;
586
587         return sched_next_nonproj(next, 1);
588 }
589
590 /**
591  * Returns previous operation node (non-Proj) before @p irn
592  * or the basic block of this node
593  */
594 static INLINE ir_node *
595 sched_prev_op(const ir_node * irn)
596 {
597         ir_node *prev = sched_prev(irn);
598
599         if(is_Block(prev))
600                 return prev;
601
602         return sched_next_nonproj(prev, 0);
603 }
604
605 static void
606 sched_put_after(ir_node * insert, ir_node * irn)
607 {
608         if(is_Block(insert)) {
609                 insert = sched_block_first_nonphi(insert);
610         } else {
611                 insert = sched_next_op(insert);
612         }
613         sched_add_before(insert, irn);
614 }
615
616 static void
617 sched_put_before(const spill_ilp_t * si, ir_node * insert, ir_node * irn)
618 {
619   if(is_Block(insert)) {
620           insert = sched_block_last_noncf(si, insert);
621   } else {
622           insert = sched_next_nonproj(insert, 0);
623           insert = sched_prev(insert);
624   }
625   sched_add_after(insert, irn);
626 }
627
628 /**
629  * Tells you whether a @p remat can be placed before the irn @p pos
630  */
631 static INLINE int
632 can_remat_before(const spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
633 {
634         const ir_node   *op = remat->op;
635         const ir_node   *prev;
636         int        i,
637                            n,
638                            res = 1;
639
640         if(is_Block(pos)) {
641                 prev = sched_block_last_noncf(si, pos);
642                 prev = sched_next_nonproj(prev, 0);
643         } else {
644                 prev = sched_prev_op(pos);
645         }
646         /* do not remat if the rematted value is defined immediately before this op */
647         if(prev == remat->op) {
648                 return 0;
649         }
650
651 #if 0
652         /* this should be just fine, the following OP will be using this value, right? */
653
654         /* only remat AFTER the real definition of a value (?) */
655         if(!value_is_defined_before(si, pos, remat->value)) {
656 //              ir_fprintf(stderr, "error(not defined)");
657                 return 0;
658         }
659 #endif
660
661         for(i=0, n=get_irn_arity(op); i<n && res; ++i) {
662                 const ir_node   *arg = get_irn_n(op, i);
663
664 #ifdef NO_ENLARGE_L1V3N355
665                 if(has_reg_class(si, arg) && live) {
666                         res &= pset_find_ptr(live, arg)?1:0;
667                 } else {
668                         res &= value_is_defined_before(si, pos, arg);
669                 }
670 #else
671                 res &= value_is_defined_before(si, pos, arg);
672 #endif
673         }
674
675         return res;
676 }
677
678 /**
679  * Tells you whether a @p remat can be placed after the irn @p pos
680  */
681 static INLINE int
682 can_remat_after(const spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
683 {
684         if(is_Block(pos)) {
685                 pos = sched_block_first_nonphi(pos);
686         } else {
687                 pos = sched_next_op(pos);
688         }
689
690         /* only remat AFTER the real definition of a value (?) */
691         if(!value_is_defined_before(si, pos, remat->value)) {
692                 return 0;
693         }
694
695         return can_remat_before(si, remat, pos, live);
696 }
697
698 /**
699  * Collect potetially rematerializable OPs
700  */
701 static void
702 walker_remat_collector(ir_node * irn, void * data)
703 {
704         spill_ilp_t    *si = data;
705
706         if(!is_Block(irn) && !is_Phi(irn)) {
707                 DBG((si->dbg, LEVEL_4, "\t  Processing %+F\n", irn));
708                 get_remats_from_op(si, irn);
709         }
710 }
711
712 /**
713  * Inserts a copy of @p irn before @p pos
714  */
715 static ir_node *
716 insert_copy_before(const spill_ilp_t * si, const ir_node * irn, ir_node * pos)
717 {
718         ir_node     *bb;
719         ir_node     *copy;
720
721         bb = is_Block(pos)?pos:get_nodes_block(pos);
722         copy = exact_copy(irn);
723         set_nodes_block(copy, bb);
724         sched_put_before(si, pos, copy);
725
726         return copy;
727 }
728
729 /**
730  * Inserts a copy of @p irn after @p pos
731  */
732 static ir_node *
733 insert_copy_after(const spill_ilp_t * si, const ir_node * irn, ir_node * pos)
734 {
735         ir_node     *bb;
736         ir_node     *copy;
737
738         bb = is_Block(pos)?pos:get_nodes_block(pos);
739         copy = exact_copy(irn);
740         set_nodes_block(copy, bb);
741         sched_put_after(pos, copy);
742
743         return copy;
744 }
745
746 static void
747 insert_remat_after(spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
748 {
749         char     buf[256];
750
751         if(can_remat_after(si, remat, pos, live)) {
752                 ir_node         *copy,
753                                                 *proj_copy;
754                 op_t            *op;
755
756                 DBG((si->dbg, LEVEL_3, "\t  >inserting remat %+F\n", remat->op));
757
758                 copy = insert_copy_after(si, remat->op, pos);
759
760 //              ir_snprintf(buf, sizeof(buf), "remat2_%N_%N", remat->value, pos);
761                 ir_snprintf(buf, sizeof(buf), "remat2_%N_%N", copy, pos);
762                 op = obstack_alloc(si->obst, sizeof(*op));
763                 op->is_remat = 1;
764                 op->attr.remat.remat = remat;
765                 op->attr.remat.pre = 0;
766                 op->attr.remat.ilp = lpp_add_var(si->lpp, buf, lpp_binary, remat->cost*execution_frequency(si, pos));
767
768                 set_irn_link(copy, op);
769                 pset_insert_ptr(si->all_possible_remats, copy);
770                 if(remat->proj) {
771                         proj_copy = insert_copy_after(si, remat->proj, copy);
772                         set_irn_n(proj_copy, 0, copy);
773                         set_irn_link(proj_copy, op);
774                         pset_insert_ptr(si->all_possible_remats, proj_copy);
775                 } else {
776                         proj_copy = NULL;
777                 }
778         }
779 }
780
781 static void
782 insert_remat_before(spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
783 {
784         char     buf[256];
785
786         if(can_remat_before(si, remat, pos, live)) {
787                 ir_node         *copy,
788                                                 *proj_copy;
789                 op_t            *op;
790
791                 DBG((si->dbg, LEVEL_3, "\t  >inserting remat %+F\n", remat->op));
792
793                 copy = insert_copy_before(si, remat->op, pos);
794
795 //              ir_snprintf(buf, sizeof(buf), "remat_%N_%N", remat->value, pos);
796                 ir_snprintf(buf, sizeof(buf), "remat_%N_%N", copy, pos);
797                 op = obstack_alloc(si->obst, sizeof(*op));
798                 op->is_remat = 1;
799                 op->attr.remat.remat = remat;
800                 op->attr.remat.pre = 1;
801                 op->attr.remat.ilp = lpp_add_var(si->lpp, buf, lpp_binary, remat->cost*execution_frequency(si, pos));
802
803                 set_irn_link(copy, op);
804                 pset_insert_ptr(si->all_possible_remats, copy);
805                 if(remat->proj) {
806                         proj_copy = insert_copy_after(si, remat->proj, copy);
807                         set_irn_n(proj_copy, 0, copy);
808                         set_irn_link(proj_copy, op);
809                         pset_insert_ptr(si->all_possible_remats, proj_copy);
810                 } else {
811                         proj_copy = NULL;
812                 }
813         }
814 }
815
816 static int
817 get_block_n_succs(const ir_node *block) {
818         const ir_edge_t *edge;
819
820         assert(edges_activated(current_ir_graph));
821
822         edge = get_block_succ_first(block);
823         if (! edge)
824                 return 0;
825
826         edge = get_block_succ_next(block, edge);
827         return edge ? 2 : 1;
828 }
829
830 static int
831 is_merge_edge(const ir_node * bb)
832 {
833 #ifdef GOODWIN_REDUCTION
834         return get_block_n_succs(bb) == 1;
835 #else
836         return 1;
837 #endif
838 }
839
840 static int
841 is_diverge_edge(const ir_node * bb)
842 {
843 #ifdef GOODWIN_REDUCTION
844         return get_Block_n_cfgpreds(bb) == 1;
845 #else
846         return 1;
847 #endif
848 }
849
850 /**
851  * Insert (so far unused) remats into the irg to
852  * recompute the potential liveness of all values
853  */
854 static void
855 walker_remat_insertor(ir_node * bb, void * data)
856 {
857         spill_ilp_t    *si = data;
858         spill_bb_t     *spill_bb;
859         ir_node        *irn;
860         int             i,
861                                         n;
862         irn_live_t     *li;
863         pset           *live = pset_new_ptr_default();
864
865         DBG((si->dbg, LEVEL_3, "\t Entering %+F\n\n", bb));
866
867         live_foreach(bb, li) {
868                 ir_node        *value = (ir_node *) li->irn;
869
870                 /* add remats at end of block */
871                 if (live_is_end(li) && has_reg_class(si, value)) {
872                         pset_insert_ptr(live, value);
873                 }
874         }
875
876         spill_bb = obstack_alloc(si->obst, sizeof(*spill_bb));
877         set_irn_link(bb, spill_bb);
878
879         irn = sched_last(bb);
880         while(!sched_is_end(irn)) {
881                 ir_node   *next;
882                 op_t      *op;
883                 pset      *args;
884                 ir_node   *arg;
885
886                 next = sched_prev(irn);
887
888                 DBG((si->dbg, LEVEL_5, "\t at %+F (next: %+F)\n", irn, next));
889
890                 if(is_Phi(irn) || is_Proj(irn)) {
891                         op_t      *op;
892
893                         if(has_reg_class(si, irn)) {
894                                 pset_remove_ptr(live, irn);
895                         }
896
897                         op = obstack_alloc(si->obst, sizeof(*op));
898                         op->is_remat = 0;
899                         op->attr.live_range.reloads = NULL;
900                         op->attr.live_range.ilp = ILP_UNDEF;
901                         set_irn_link(irn, op);
902
903                         irn = next;
904                         continue;
905                 }
906
907                 op = obstack_alloc(si->obst, sizeof(*op));
908                 op->is_remat = 0;
909                 op->attr.live_range.ilp = ILP_UNDEF;
910                 op->attr.live_range.reloads = obstack_alloc(si->obst, sizeof(*op->attr.live_range.reloads) * get_irn_arity(irn));
911                 memset(op->attr.live_range.reloads, 0xFF, sizeof(*op->attr.live_range.reloads) * get_irn_arity(irn));
912                 set_irn_link(irn, op);
913
914                 args = pset_new_ptr_default();
915
916                 /* collect arguments of op */
917                 for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
918                         ir_node        *arg = get_irn_n(irn, i);
919
920                         pset_insert_ptr(args, arg);
921                 }
922
923                 /* set args of op live in epilog */
924                 pset_foreach(args, arg) {
925                         if(has_reg_class(si, arg)) {
926                                 pset_insert_ptr(live, arg);
927                         }
928                 }
929
930                 /* insert all possible remats after irn */
931                 pset_foreach(args, arg) {
932                         remat_info_t   *remat_info,
933                                                     query;
934                         remat_t        *remat;
935
936                         /* continue if the operand has the wrong reg class
937                          */
938                         if(!has_reg_class(si, arg))
939                                 continue;
940
941                         query.irn = arg;
942                         query.remats = NULL;
943                         query.remats_by_operand = NULL;
944                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
945
946                         if(!remat_info) {
947                                 continue;
948                         }
949
950                         /* do not place post remats after jumps */
951                         if(sched_skip_cf_predicator(irn, si->chordal_env->birg->main_env->arch_env)) continue;
952
953                         if(remat_info->remats_by_operand) {
954                                 pset_foreach(remat_info->remats_by_operand, remat) {
955                                         /* do not insert remats producing the same value as one of the operands */
956                                         if(!pset_find_ptr(args, remat->value)) {
957                                                 DBG((si->dbg, LEVEL_4, "\t  considering remat %+F with arg %+F\n", remat->op, arg));
958 #ifdef REMAT_WHILE_LIVE
959                                                 if(pset_find_ptr(live, remat->value)) {
960                                                         insert_remat_after(si, remat, irn, live);
961                                                 }
962 #else
963                                                 insert_remat_after(si, remat, irn, live);
964 #endif
965                                         }
966                                 }
967                         }
968                 }
969
970                 /* delete defined value from live set */
971                 if(has_reg_class(si, irn)) {
972                         pset_remove_ptr(live, irn);
973                 }
974
975                 /* insert all possible remats before irn */
976                 pset_foreach(args, arg) {
977                         remat_info_t   *remat_info,
978                                                     query;
979                         remat_t        *remat;
980
981                         /* continue if the operand has the wrong reg class
982                          */
983                         if(!has_reg_class(si, arg))
984                                 continue;
985
986                         query.irn = arg;
987                         query.remats = NULL;
988                         query.remats_by_operand = NULL;
989                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
990
991                         if(!remat_info) {
992                                 continue;
993                         }
994
995                         if(remat_info->remats) {
996                                 pset_foreach(remat_info->remats, remat) {
997                                         DBG((si->dbg, LEVEL_4, "\t  considering remat %+F for arg %+F\n", remat->op, arg));
998 #ifdef REMAT_WHILE_LIVE
999                                         if(pset_find_ptr(live, remat->value)) {
1000                                                 insert_remat_before(si, remat, irn, live);
1001                                         }
1002 #else
1003                                         insert_remat_before(si, remat, irn, live);
1004 #endif
1005                                 }
1006                         }
1007                 }
1008
1009                 del_pset(args);
1010                 irn = next;
1011         }
1012
1013         live_foreach(bb, li) {
1014                 ir_node        *value = (ir_node *) li->irn;
1015
1016                 /* add remats at end if successor has multiple predecessors */
1017                 if(is_merge_edge(bb)) {
1018                         /* add remats at end of block */
1019                         if (live_is_end(li) && has_reg_class(si, value)) {
1020                                 remat_info_t   *remat_info,
1021                                                            query;
1022                                 remat_t        *remat;
1023
1024                                 query.irn = value;
1025                                 query.remats = NULL;
1026                                 query.remats_by_operand = NULL;
1027                                 remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(value));
1028
1029                                 if(remat_info && remat_info->remats) {
1030                                         pset_foreach(remat_info->remats, remat) {
1031                                                 DBG((si->dbg, LEVEL_4, "\t  considering remat %+F at end of block %+F\n", remat->op, bb));
1032
1033                                                 insert_remat_before(si, remat, bb, NULL);
1034                                         }
1035                                 }
1036                         }
1037                 }
1038                 if(is_diverge_edge(bb)) {
1039                         /* add remat2s at beginning of block */
1040                         if ((live_is_in(li) || (is_Phi(value) && get_nodes_block(value)==bb)) && has_reg_class(si, value)) {
1041                                 remat_info_t   *remat_info,
1042                                                            query;
1043                                 remat_t        *remat;
1044
1045                                 query.irn = value;
1046                                 query.remats = NULL;
1047                                 query.remats_by_operand = NULL;
1048                                 remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(value));
1049
1050                                 if(remat_info && remat_info->remats) {
1051                                         pset_foreach(remat_info->remats, remat) {
1052                                                 DBG((si->dbg, LEVEL_4, "\t  considering remat %+F at beginning of block %+F\n", remat->op, bb));
1053
1054                                                 /* put the remat here if all its args are available */
1055                                                 insert_remat_after(si, remat, bb, NULL);
1056
1057                                         }
1058                                 }
1059                         }
1060                 }
1061         }
1062 }
1063
1064 /**
1065  * Preparation of blocks' ends for Luke Blockwalker(tm)(R)
1066  */
1067 static void
1068 luke_endwalker(ir_node * bb, void * data)
1069 {
1070         spill_ilp_t    *si = (spill_ilp_t*)data;
1071         irn_live_t     *li;
1072         pset           *live;
1073         pset           *use_end;
1074         char            buf[256];
1075         ilp_cst_t       cst;
1076         ir_node        *irn;
1077         spill_bb_t     *spill_bb = get_irn_link(bb);
1078
1079
1080         live = pset_new_ptr_default();
1081         use_end = pset_new_ptr_default();
1082
1083         live_foreach(bb, li) {
1084                 irn = (ir_node *) li->irn;
1085                 if (live_is_end(li) && has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1086                         op_t      *op;
1087
1088                         pset_insert_ptr(live, irn);
1089                         op = get_irn_link(irn);
1090                         assert(!op->is_remat);
1091                 }
1092         }
1093
1094         /* collect values used by cond jumps etc. at bb end (use_end) -> always live */
1095         /* their reg_out is unimportant because it can always be set */
1096         sched_foreach_reverse(bb, irn) {
1097                 int   i,
1098                           n;
1099
1100                 if(!sched_skip_cf_predicator(irn, si->chordal_env->birg->main_env->arch_env)) break;
1101
1102                 for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
1103                         ir_node        *irn_arg = get_irn_n(irn, i);
1104                         if(has_reg_class(si, irn_arg)) {
1105                                 pset_insert_ptr(use_end, irn);
1106                         }
1107                 }
1108         }
1109
1110         ir_snprintf(buf, sizeof(buf), "check_end_%N", bb);
1111         cst = lpp_add_cst(si->lpp, buf, lpp_less, si->n_regs - pset_count(use_end));
1112
1113         spill_bb->ilp = new_set(cmp_spill, 16);
1114
1115         live_foreach(bb, li) {
1116                 irn = (ir_node *) li->irn;
1117                 if (live_is_end(li) && has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1118                         spill_t     query,
1119                                    *spill;
1120                         double      spill_cost;
1121
1122                         query.irn = irn;
1123                         spill = set_insert(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1124
1125                         spill_cost = is_Unknown(irn)?0.0001:COST_STORE*execution_frequency(si, bb);
1126
1127                         ir_snprintf(buf, sizeof(buf), "reg_out_%N_%N", irn, bb);
1128                         spill->reg_out = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1129                         /* if irn is used at the end of the block, then it is live anyway */
1130                         if(!pset_find_ptr(use_end, irn))
1131                                 lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1132
1133                         ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", irn, bb);
1134                         spill->mem_out = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1135
1136                         ir_snprintf(buf, sizeof(buf), "spill_%N_%N", irn, bb);
1137                         spill->spill = lpp_add_var(si->lpp, buf, lpp_binary, spill_cost);
1138
1139                         spill->reg_in = ILP_UNDEF;
1140                         spill->mem_in = ILP_UNDEF;
1141                 }
1142         }
1143
1144         del_pset(live);
1145         del_pset(use_end);
1146 }
1147
1148 static ir_node *
1149 next_post_remat(const ir_node * irn)
1150 {
1151         op_t      *op;
1152
1153         if(is_Block(irn)) {
1154                 irn = sched_block_first_nonphi(irn);
1155         } else {
1156                 irn = sched_next_op(irn);
1157         }
1158
1159         if(sched_is_end(irn))
1160                 return NULL;
1161
1162         op = (op_t*)get_irn_link(irn);
1163         if(op->is_remat && !op->attr.remat.pre) {
1164                 return irn;
1165         }
1166
1167         return NULL;
1168 }
1169
1170
1171 static ir_node *
1172 next_pre_remat(const spill_ilp_t * si, const ir_node * irn)
1173 {
1174         op_t      *op;
1175         ir_node   *ret;
1176
1177         if(is_Block(irn)) {
1178                 ret = sched_block_last_noncf(si, irn);
1179                 ret = sched_next(ret);
1180                 ret = sched_prev_op(ret);
1181         } else {
1182                 ret = sched_prev_op(irn);
1183         }
1184
1185         if(sched_is_end(ret) || is_Phi(ret))
1186                 return NULL;
1187
1188         op = (op_t*)get_irn_link(ret);
1189         if(op->is_remat && op->attr.remat.pre) {
1190                 return ret;
1191         }
1192
1193         return NULL;
1194 }
1195
1196 /**
1197  * Find a remat of value @p value in the epilog of @p pos
1198  */
1199 static ir_node *
1200 find_post_remat(const ir_node * value, const ir_node * pos)
1201 {
1202         while((pos = next_post_remat(pos)) != NULL) {
1203                 op_t   *op;
1204
1205                 op = get_irn_link(pos);
1206                 assert(op->is_remat && !op->attr.remat.pre);
1207
1208                 if(op->attr.remat.remat->value == value)
1209                         return (ir_node*)pos;
1210
1211 #if 0
1212         const ir_edge_t *edge;
1213                 foreach_out_edge(pos, edge) {
1214                         ir_node   *proj = get_edge_src_irn(edge);
1215                         assert(is_Proj(proj));
1216                 }
1217 #endif
1218
1219         }
1220
1221         return NULL;
1222 }
1223
1224 /**
1225  * Find a remat of value @p value in the prolog of @p pos
1226  */
1227 static ir_node *
1228 find_pre_remat(const spill_ilp_t * si, const ir_node * value, const ir_node * pos)
1229 {
1230         while((pos = next_pre_remat(si,pos)) != NULL) {
1231                 op_t   *op;
1232
1233                 op = get_irn_link(pos);
1234                 assert(op->is_remat && op->attr.remat.pre);
1235
1236                 if(op->attr.remat.remat->value == value)
1237                         return (ir_node*)pos;
1238         }
1239
1240         return NULL;
1241 }
1242
1243 static spill_t *
1244 add_to_spill_bb(spill_ilp_t * si, ir_node * bb, ir_node * irn)
1245 {
1246         spill_bb_t  *spill_bb = get_irn_link(bb);
1247         spill_t     *spill,
1248                                  query;
1249         char         buf[256];
1250
1251         query.irn = irn;
1252         spill = set_find(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1253         if(!spill) {
1254                 double   spill_cost = is_Unknown(irn)?0.0001:COST_STORE*execution_frequency(si, bb);
1255
1256                 spill = set_insert(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1257
1258                 spill->reg_out = ILP_UNDEF;
1259                 spill->reg_in  = ILP_UNDEF;
1260                 spill->mem_in  = ILP_UNDEF;
1261
1262                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", irn, bb);
1263                 spill->mem_out = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1264
1265                 ir_snprintf(buf, sizeof(buf), "spill_%N_%N", irn, bb);
1266                 spill->spill = lpp_add_var(si->lpp, buf, lpp_binary, spill_cost);
1267         }
1268
1269         return spill;
1270 }
1271
1272 /**
1273  * Walk all irg blocks and emit this ILP
1274  */
1275 static void
1276 luke_blockwalker(ir_node * bb, void * data)
1277 {
1278         spill_ilp_t    *si = (spill_ilp_t*)data;
1279         ir_node        *irn;
1280         irn_live_t     *li;
1281         pset           *live;
1282         char            buf[256];
1283         ilp_cst_t       cst;
1284         spill_bb_t     *spill_bb = get_irn_link(bb);
1285         int             i;
1286         ir_node        *tmp;
1287         spill_t        *spill;
1288
1289
1290         live = pset_new_ptr_default();
1291
1292         /* do something at the end of the block */
1293
1294         /* init live values at end of block */
1295         live_foreach(bb, li) {
1296                 ir_node        *irn = (ir_node *) li->irn;
1297
1298                 if (live_is_end(li) && has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1299                         pset_insert_ptr(live, irn);
1300                 }
1301         }
1302
1303         if(is_merge_edge(bb)) {
1304                 spill_bb->reloads = obstack_alloc(si->obst, pset_count(live) * sizeof(*spill_bb->reloads));
1305                 memset(spill_bb->reloads, 0xFF, pset_count(live) * sizeof(*spill_bb->reloads));
1306         } else {
1307                 spill_bb->reloads = NULL;
1308         }
1309
1310         i=0;
1311         live_foreach(bb, li) {
1312                 ir_node        *irn = (ir_node *) li->irn;
1313                 op_t           *op;
1314
1315                 if (live_is_end(li) && has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1316                         spill = set_find_spill(spill_bb->ilp, irn);
1317                         assert(spill);
1318
1319                         if(spill_bb->reloads) {
1320                                 ir_snprintf(buf, sizeof(buf), "reload_%N_%N", bb, irn);
1321                                 spill_bb->reloads[i] = lpp_add_var(si->lpp, buf, lpp_binary, COST_LOAD*execution_frequency(si, bb));
1322
1323                                 /* reload <= mem_out */
1324                                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1325                                 lpp_set_factor_fast(si->lpp, cst, spill_bb->reloads[i], 1.0);
1326                                 lpp_set_factor_fast(si->lpp, cst, spill->mem_out, -1.0);
1327                         }
1328
1329                         op = get_irn_link(irn);
1330                         assert(!op->is_remat);
1331
1332                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", irn, bb);
1333                         op->attr.live_range.ilp = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1334                         op->attr.live_range.op = bb;
1335
1336                         ir_snprintf(buf, sizeof(buf), "reg_out_%N_%N", bb, irn);
1337                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1338
1339                         /* reg_out - reload - remat - live_range <= 0 */
1340                         lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1341                         if(spill_bb->reloads) lpp_set_factor_fast(si->lpp, cst, spill_bb->reloads[i], -1.0);
1342                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, -1.0);
1343                         foreach_pre_remat(si, bb, tmp) {
1344                                 op_t     *remat_op = get_irn_link(tmp);
1345                                 if(remat_op->attr.remat.remat->value == irn) {
1346                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1347                                 }
1348                         }
1349
1350                         ++i;
1351                 }
1352         }
1353         DBG((si->dbg, LEVEL_4, "\t   %d values live at end of block %+F\n", pset_count(live), bb));
1354
1355         sched_foreach_reverse(bb, irn) {
1356                 op_t       *op;
1357                 op_t       *tmp_op;
1358                 int         n,
1359                                         k,
1360                                         d = 0;
1361                 ilp_cst_t       check_pre,
1362                                         check_post;
1363 #ifdef CHECK_POST_REMAT
1364                 ilp_cst_t       check_post_remat;
1365 #endif
1366                 set        *args = new_set(cmp_keyval, get_irn_arity(irn));
1367                 keyval_t   *keyval;
1368
1369                 if(is_Phi(irn))
1370                         break;
1371
1372                 op = get_irn_link(irn);
1373                 /* skip remats */
1374                 if(op->is_remat) continue;
1375                 DBG((si->dbg, LEVEL_4, "\t  at node %+F\n", irn));
1376
1377                 if(has_reg_class(si, irn)) {
1378                         assert(pset_find_ptr(live, irn));
1379                         pset_remove_ptr(live, irn);
1380                 }
1381
1382                 if(is_Proj(irn)) continue;
1383
1384                 /* init set of irn's arguments */
1385                 for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
1386                         ir_node        *irn_arg = get_irn_n(irn, i);
1387                         if(has_reg_class(si, irn_arg)) {
1388                                 set_insert_keyval(args, irn_arg, (void*)i);
1389                         }
1390                 }
1391
1392 #ifdef CHECK_POST_REMAT
1393                 /* check the register pressure after the epilog */
1394                 ir_snprintf(buf, sizeof(buf), "check_post_remat_%N", irn);
1395                 check_post_remat = lpp_add_cst(si->lpp, buf, lpp_less, si->n_regs);
1396
1397                 /* iterate over L\U */
1398                 pset_foreach(live, tmp) {
1399                         if(!set_find_keyval(args, tmp)) {
1400                                 /* if a live value is not used by irn */
1401                                 tmp_op = get_irn_link(tmp);
1402 //                              assert(tmp_op->attr.live_range.op != irn);
1403                                 lpp_set_factor_fast(si->lpp, check_post_remat, tmp_op->attr.live_range.ilp, 1.0);
1404                         }
1405                 }
1406                 /* iterate over following remats and remove possibly defined values again from check_post_remat */
1407                 foreach_post_remat(irn, tmp) {
1408                         op_t           *remat_op = get_irn_link(tmp);
1409                         const ir_node  *value = remat_op->attr.remat.remat->value;
1410                         op_t           *val_op = get_irn_link(value);
1411
1412                         assert(remat_op->is_remat && !remat_op->attr.remat.pre);
1413
1414                         /* values that are defined by remat2s are not counted */
1415 #ifdef REMAT_WHILE_LIVE
1416                         assert(val_op->attr.live_range.ilp);
1417                         lpp_set_factor_fast(si->lpp, check_post_remat, val_op->attr.live_range.ilp, 0.0);
1418 #else
1419                         if(val_op->attr.live_range.ilp != ILP_UNDEF) {
1420                                 lpp_set_factor_fast(si->lpp, check_post_remat, val_op->attr.live_range.ilp, 0.0);
1421                         }
1422 #endif /* REMAT_WHILE_LIVE */
1423                 }
1424 #endif /* CHECK_POST_REMAT */
1425
1426
1427                 /* new live ranges for values from L\U defined by remat2s or used by remats */
1428                 pset_foreach(live, tmp) {
1429                         ir_node     *value = tmp;//remat_op->attr.remat.remat->value;
1430                         op_t        *value_op = get_irn_link(value);
1431
1432                         if(!set_find_keyval(args, value)) {
1433                                 ilp_var_t    prev_lr = ILP_UNDEF;
1434                                 ir_node     *remat;
1435                                 cst = ILP_UNDEF;
1436
1437                                 foreach_post_remat(irn, remat) {
1438                                         op_t        *remat_op = get_irn_link(remat);
1439
1440                                         /* if value is being rematerialized by this remat */
1441                                         if(value == remat_op->attr.remat.remat->value) {
1442                                                 if(cst == ILP_UNDEF) {
1443                                                         /* next_live_range <= prev_live_range + sum remat2s */
1444                                                         ir_snprintf(buf, sizeof(buf), "next_lr_%N_%N", value, irn);
1445                                                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1446                                                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", value, irn);
1447                                                         prev_lr = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1448                                                         lpp_set_factor_fast(si->lpp, cst, value_op->attr.live_range.ilp, 1.0);
1449                                                         lpp_set_factor_fast(si->lpp, cst, prev_lr, -1.0);
1450                                                 }
1451
1452                                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1453                                         }
1454                                 }
1455
1456 #ifdef MAY_DIE_AT_PRE_REMAT
1457                                 if(cst == ILP_UNDEF) {
1458                                         foreach_pre_remat(si, irn, remat) {
1459                                                 int          i,
1460                                                                          n;
1461
1462                                                 for (i = 0, n = get_irn_arity(remat); i < n; ++i) {
1463                                                         ir_node        *remat_arg = get_irn_n(remat, i);
1464
1465                                                         /* if value is being used by this remat */
1466                                                         if(value == remat_arg) {
1467                                                                 /* next_live_range <= prev_live_range */
1468                                                                 ir_snprintf(buf, sizeof(buf), "lr_%N_%N", value, irn);
1469                                                                 prev_lr = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1470
1471                                                                 ir_snprintf(buf, sizeof(buf), "next_lr_%N_%N", value, irn);
1472                                                                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1473                                                                 lpp_set_factor_fast(si->lpp, cst, value_op->attr.live_range.ilp, 1.0);
1474                                                                 lpp_set_factor_fast(si->lpp, cst, prev_lr, -1.0);
1475                                                                 goto fertig;
1476                                                         }
1477                                                         /* TODO check afterwards whether lr dies after a pre-remat (should not happen) */
1478                                                 }
1479                                         }
1480                                 }
1481 fertig:
1482 #endif
1483
1484                                 if(prev_lr != ILP_UNDEF) {
1485                                         value_op->attr.live_range.ilp = prev_lr;
1486                                         value_op->attr.live_range.op = irn;
1487                                 }
1488                         }
1489                 }
1490
1491                 /* get count of values in my register class defined by irn */
1492                 /* also add defined values to check_post_remat; do this before iterating over args */
1493                 if(get_irn_mode(irn) == mode_T) {
1494                         ir_node  *proj = sched_next(irn);
1495                         op_t     *proj_op = get_irn_link(proj);
1496
1497                         while(is_Proj(proj)) {
1498                                 if(has_reg_class(si, proj)) {
1499                                         ++d;
1500 #ifdef CHECK_POST_REMAT
1501                                         lpp_set_factor_fast(si->lpp, check_post_remat, proj_op->attr.live_range.ilp, 1.0);
1502 #endif
1503                                 }
1504                                 proj = sched_next(proj);
1505                                 proj_op = get_irn_link(proj);
1506                         }
1507                 } else {
1508                         if(has_reg_class(si, irn)) {
1509                                  d = 1;
1510 #ifdef CHECK_POST_REMAT
1511                                  lpp_set_factor_fast(si->lpp, check_post_remat, op->attr.live_range.ilp, 1.0);
1512 #endif
1513                         }
1514                 }
1515                 DBG((si->dbg, LEVEL_4, "\t   %+F produces %d values in my register class\n", irn, d));
1516
1517                 /* count how many regs irn needs for arguments */
1518                 k = set_count(args);
1519
1520                 /* check the register pressure in the prolog */
1521                 /* sum_{L\U} lr <= n - |U| */
1522                 ir_snprintf(buf, sizeof(buf), "check_pre_%N", irn);
1523                 check_pre = lpp_add_cst(si->lpp, buf, lpp_less, si->n_regs - k);
1524
1525                 /* check the register pressure in the epilog */
1526                 ir_snprintf(buf, sizeof(buf), "check_post_%N", irn);
1527                 check_post = lpp_add_cst(si->lpp, buf, lpp_less, si->n_regs - d);
1528
1529                 set_foreach(args, keyval) {
1530                         ilp_var_t       next_lr;
1531                         op_t           *arg_op;
1532                         ilp_var_t       post_use;
1533                         int             p = 0;
1534                         spill_t        *spill;
1535                         ir_node        *arg = keyval->key;
1536
1537                         spill = add_to_spill_bb(si, bb, arg);
1538
1539                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", arg, irn);
1540                         next_lr = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1541
1542                         i = (int)keyval->val;
1543                         assert(i<n);
1544
1545                         ir_snprintf(buf, sizeof(buf), "reload_%N_%N", arg, irn);
1546                         op->attr.live_range.reloads[i] = lpp_add_var(si->lpp, buf, lpp_binary, COST_LOAD*execution_frequency(si, bb));
1547
1548                         /* reload <= mem_out */
1549                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1550                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.reloads[i], 1.0);
1551                         lpp_set_factor_fast(si->lpp, cst, spill->mem_out, -1.0);
1552
1553                         arg_op = get_irn_link(arg);
1554
1555                         /* requirement: arg must be in register for use */
1556                         /* reload + remat + live_range == 1 */
1557                         ir_snprintf(buf, sizeof(buf), "req_%N_%N", irn, arg);
1558                         cst = lpp_add_cst(si->lpp, buf, lpp_equal, 1.0);
1559
1560                         lpp_set_factor_fast(si->lpp, cst, next_lr, 1.0);
1561                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.reloads[i], 1.0);
1562                         foreach_pre_remat(si, irn, tmp) {
1563                                 op_t     *remat_op = get_irn_link(tmp);
1564                                 if(remat_op->attr.remat.remat->value == arg) {
1565                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
1566                                 }
1567                         }
1568
1569                         /* the epilog stuff - including post_use, post, post_remat */
1570                         ir_snprintf(buf, sizeof(buf), "post_use_%N_%N", arg, irn);
1571                         post_use = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1572
1573                         lpp_set_factor_fast(si->lpp, check_post, post_use, 1.0);
1574
1575                         /* arg is live throughout epilog if the next live_range is in a register */
1576                         if(pset_find_ptr(live, arg)) {
1577                                 DBG((si->dbg, LEVEL_3, "\t  arg %+F is possibly live in epilog of %+F\n", arg, irn));
1578
1579                                 ir_snprintf(buf, sizeof(buf), "post_use_%N_%N-%d", arg, irn, p++);
1580                                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1581                                 lpp_set_factor_fast(si->lpp, cst, post_use, -1.0);
1582                                 lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, 1.0);
1583
1584 #ifdef CHECK_POST_REMAT
1585                                 lpp_set_factor_fast(si->lpp, check_post_remat, arg_op->attr.live_range.ilp, 1.0);
1586 #endif
1587                         }
1588
1589                         /*forall remat2 which use arg add a similar cst*/
1590                         foreach_post_remat(irn, tmp) {
1591                                 int         i,
1592                                                         n;
1593
1594                                 for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1595                                         ir_node    *remat_arg = get_irn_n(tmp, i);
1596                                         op_t       *remat_op = get_irn_link(tmp);
1597
1598                                         if(remat_arg == arg) {
1599                                                 DBG((si->dbg, LEVEL_3, "\t  found remat with arg %+F in epilog of %+F\n", arg, irn));
1600
1601                                                 ir_snprintf(buf, sizeof(buf), "post_use_%N_%N-%d", arg, irn, p++);
1602                                                 cst = lpp_add_cst(si->lpp, buf, lpp_greater, 0.0);
1603                                                 lpp_set_factor_fast(si->lpp, cst, post_use, 1.0);
1604                                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1605                                         }
1606                                 }
1607                         }
1608
1609                         /* new live range begins for each argument */
1610                         arg_op->attr.live_range.ilp = next_lr;
1611                         arg_op->attr.live_range.op = irn;
1612
1613                         pset_insert_ptr(live, arg);
1614                 }
1615
1616                 /* start new live ranges for values used by remats */
1617                 foreach_pre_remat(si, irn, tmp) {
1618                         int          i,
1619                                                  n;
1620
1621                         for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1622                                 ir_node        *remat_arg = get_irn_n(tmp, i);
1623                                 op_t           *arg_op = get_irn_link(remat_arg);
1624                                 ilp_var_t       prev_lr;
1625
1626                                 if(!has_reg_class(si, remat_arg)) continue;
1627
1628                                 /* if value is becoming live through use by remat */
1629                                 if(!pset_find_ptr(live, remat_arg)) {
1630                                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", remat_arg, irn);
1631                                         prev_lr = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1632
1633                                         arg_op->attr.live_range.ilp = prev_lr;
1634                                         arg_op->attr.live_range.op = irn;
1635
1636                                         DBG((si->dbg, LEVEL_4, "  value %+F becoming live through use by remat %+F\n", remat_arg, tmp));
1637
1638                                         /* TODO ist das hier die richtige Stelle???? */
1639                                         pset_insert_ptr(live, remat_arg);
1640                                         add_to_spill_bb(si, bb, remat_arg);
1641                                 }
1642                                 /* TODO check afterwards whether lr dies after a pre-remat (should not happen) */
1643                         }
1644                 }
1645
1646                 /* iterate over L\U */
1647                 pset_foreach(live, tmp) {
1648                         if(!set_find_keyval(args, tmp)) {
1649                                 /* if a live value is not used by irn */
1650                                 tmp_op = get_irn_link(tmp);
1651 //                              assert(tmp_op->attr.live_range.op != irn);
1652                                 lpp_set_factor_fast(si->lpp, check_pre, tmp_op->attr.live_range.ilp, 1.0);
1653                                 lpp_set_factor_fast(si->lpp, check_post, tmp_op->attr.live_range.ilp, 1.0);
1654                         }
1655                 }
1656
1657                 /* requirements for remats */
1658                 foreach_pre_remat(si, irn, tmp) {
1659                         op_t        *remat_op = get_irn_link(tmp);
1660                         int          i,
1661                                                  n;
1662
1663                         for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1664                                 ir_node        *remat_arg = get_irn_n(tmp, i);
1665                                 op_t           *arg_op = get_irn_link(remat_arg);
1666
1667                                 if(!has_reg_class(si, remat_arg)) continue;
1668
1669                                 /* remat <= live_rang(remat_arg) [ + reload(remat_arg) ] */
1670                                 ir_snprintf(buf, sizeof(buf), "req_remat_%N_arg_%N", tmp, remat_arg);
1671                                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1672
1673                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
1674                                 lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, -1.0);
1675
1676                                 /* if remat arg is also used by current op then we can use reload placed for this argument */
1677                                 if((keyval = set_find_keyval(args, remat_arg)) != NULL) {
1678                                         int    index = (int)keyval->val;
1679
1680                                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.reloads[index], -1.0);
1681                                 }
1682                         }
1683                 }
1684
1685                 /* requirements for remats2
1686                  *
1687                  *  TODO unsure if this does the right thing.
1688                  *  should insert values into set if they do not become live through remat and
1689                  *  op
1690                  */
1691                 foreach_post_remat(irn, tmp) {
1692                         op_t        *remat_op = get_irn_link(tmp);
1693                         int          i,
1694                                                  n;
1695
1696                         for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1697                                 ir_node        *remat_arg = get_irn_n(tmp, i);
1698                                 op_t           *arg_op = get_irn_link(remat_arg);
1699
1700                                 if(!has_reg_class(si, remat_arg)) continue;
1701
1702                                 /* only for values in L\U, the others are handled with post_use */
1703                                 if(!set_find_keyval(args, remat_arg)) {
1704                                         /* remat <= live_rang(remat_arg) */
1705                                         ir_snprintf(buf, sizeof(buf), "req_remat2_%N_arg_%N", tmp, remat_arg);
1706                                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1707
1708                                         /* if value is becoming live through use by remat2 */
1709                                         if(!pset_find_ptr(live, remat_arg)) {
1710                                                 ilp_var_t     lr;
1711
1712                                                 ir_snprintf(buf, sizeof(buf), "lr_%N_%N", remat_arg, irn);
1713                                                 lr = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1714
1715                                                 arg_op->attr.live_range.ilp = lr;
1716                                                 arg_op->attr.live_range.op = irn;
1717
1718                                                 DBG((si->dbg, LEVEL_3, "  value %+F becoming live through use by remat2 %+F\n", remat_arg, tmp));
1719
1720                                                 pset_insert_ptr(live, remat_arg);
1721                                                 add_to_spill_bb(si, bb, remat_arg);
1722                                         }
1723
1724                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
1725                                         lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, -1.0);
1726                                 }
1727                         }
1728                 }
1729
1730 #ifdef CHECK_POST_REMAT
1731                 /* iterate over following remats and add them to check_post_remat */
1732                 foreach_post_remat(irn, tmp) {
1733                         op_t           *remat_op = get_irn_link(tmp);
1734
1735                         assert(remat_op->is_remat && !remat_op->attr.remat.pre);
1736
1737                         lpp_set_factor_fast(si->lpp, check_post_remat, remat_op->attr.remat.ilp, 1.0);
1738                 }
1739 #endif
1740
1741
1742
1743                 DBG((si->dbg, LEVEL_4, "\t   %d values live at %+F\n", pset_count(live), irn));
1744
1745                 pset_foreach(live, tmp) {
1746                         assert(has_reg_class(si, tmp));
1747                 }
1748
1749                 for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
1750                         ir_node        *arg = get_irn_n(irn, i);
1751
1752                         assert(!find_post_remat(arg, irn) && "there should be no post remat for an argument of an op");
1753                 }
1754
1755                 del_set(args);
1756         }
1757
1758
1759
1760         /* do something at the beginning of the block */
1761
1762         /* we are now at the beginning of the basic block, there are only \Phis in front of us */
1763         DBG((si->dbg, LEVEL_3, "\t   %d values live at beginning of block %+F\n", pset_count(live), bb));
1764
1765         pset_foreach(live, irn) {
1766                 assert(is_Phi(irn) || get_nodes_block(irn) != bb);
1767         }
1768
1769         /* construct mem_outs for all values */
1770
1771         set_foreach(spill_bb->ilp, spill) {
1772                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", spill->irn, bb);
1773                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1774
1775                 lpp_set_factor_fast(si->lpp, cst, spill->mem_out, 1.0);
1776                 lpp_set_factor_fast(si->lpp, cst, spill->spill, -1.0);
1777
1778                 if(pset_find_ptr(live, spill->irn)) {
1779                         DBG((si->dbg, LEVEL_5, "\t     %+F live at beginning of block %+F\n", spill->irn, bb));
1780
1781                         ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N", spill->irn, bb);
1782                         spill->mem_in = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1783
1784                         lpp_set_factor_fast(si->lpp, cst, spill->mem_in, -1.0);
1785                 }
1786         }
1787
1788
1789         /* L\U is empty at bb start */
1790         /* arg is live throughout epilog if it is reg_in into this block */
1791
1792         /* check the register pressure at the beginning of the block
1793          * including remats
1794          */
1795         ir_snprintf(buf, sizeof(buf), "check_start_%N", bb);
1796         cst = lpp_add_cst(si->lpp, buf, lpp_less, si->n_regs);
1797
1798         pset_foreach(live, irn) {
1799                         spill = set_find_spill(spill_bb->ilp, irn);
1800                         assert(spill);
1801
1802                         ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N", irn, bb);
1803                         spill->reg_in = lpp_add_var(si->lpp, buf, lpp_binary, 0.0);
1804
1805                         lpp_set_factor_fast(si->lpp, cst, spill->reg_in, 1.0);
1806         }
1807         foreach_post_remat(bb, irn) {
1808                 op_t     *remat_op = get_irn_link(irn);
1809
1810                 DBG((si->dbg, LEVEL_4, "\t  next post remat: %+F\n", irn));
1811                 assert(remat_op->is_remat && !remat_op->attr.remat.pre);
1812
1813                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
1814         }
1815
1816         /* forall remat2 add requirements */
1817         foreach_post_remat(bb, tmp) {
1818                 int         i,
1819                                         n;
1820
1821                 for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1822                         ir_node    *remat_arg = get_irn_n(tmp, i);
1823                         op_t       *remat_op = get_irn_link(tmp);
1824
1825                         if(!has_reg_class(si, remat_arg)) continue;
1826
1827                         spill = set_find_spill(spill_bb->ilp, remat_arg);
1828                         assert(spill);
1829
1830                         /* TODO verify this is placed correctly */
1831                         ir_snprintf(buf, sizeof(buf), "req_remat2_%N_%N_arg_%N", tmp, bb, remat_arg);
1832                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1833                         lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
1834                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
1835                 }
1836         }
1837
1838         /* mem_in/reg_in for live_in values, especially phis and their arguments */
1839         pset_foreach(live, irn) {
1840                 int          p = 0,
1841                                          i,
1842                                          n;
1843
1844                 spill = set_find_spill(spill_bb->ilp, irn);
1845                 assert(spill && spill->irn == irn);
1846
1847                 if(is_Phi(irn) && get_nodes_block(irn) == bb) {
1848                         for (i = 0, n = get_Phi_n_preds(irn); i < n; ++i) {
1849                                 ilp_cst_t       mem_in,
1850                                                                 reg_in;
1851                                 ir_node        *phi_arg = get_Phi_pred(irn, i);
1852                                 ir_node        *bb_p = get_Block_cfgpred_block(bb, i);
1853                                 spill_bb_t     *spill_bb_p = get_irn_link(bb_p);
1854                                 spill_t        *spill_p;
1855
1856                                 /* although the phi is in the right regclass one or more of
1857                                  * its arguments can be in a different one or at least to
1858                                  * ignore
1859                                  */
1860                                 if(has_reg_class(si, phi_arg)) {
1861                                         ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N-%d", irn, bb, p);
1862                                         mem_in = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1863                                         ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N-%d", irn, bb, p++);
1864                                         reg_in = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1865
1866                                         lpp_set_factor_fast(si->lpp, mem_in, spill->mem_in, 1.0);
1867                                         lpp_set_factor_fast(si->lpp, reg_in, spill->reg_in, 1.0);
1868
1869                                         spill_p = set_find_spill(spill_bb_p->ilp, phi_arg);
1870                                         assert(spill_p);
1871
1872                                         lpp_set_factor_fast(si->lpp, mem_in, spill_p->mem_out, -1.0);
1873                                         lpp_set_factor_fast(si->lpp, reg_in, spill_p->reg_out, -1.0);
1874                                 }
1875                         }
1876                 } else {
1877                         /* else assure the value arrives on all paths in the same resource */
1878
1879                         for (i = 0, n = get_Block_n_cfgpreds(bb); i < n; ++i) {
1880                                 ilp_cst_t       mem_in,
1881                                                                 reg_in;
1882                                 ir_node        *bb_p = get_Block_cfgpred_block(bb, i);
1883                                 spill_bb_t     *spill_bb_p = get_irn_link(bb_p);
1884                                 spill_t        *spill_p;
1885
1886                                 ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N-%d", irn, bb, p);
1887                                 mem_in = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1888                                 ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N-%d", irn, bb, p++);
1889                                 reg_in = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1890
1891                                 lpp_set_factor_fast(si->lpp, mem_in, spill->mem_in, 1.0);
1892                                 lpp_set_factor_fast(si->lpp, reg_in, spill->reg_in, 1.0);
1893
1894                                 spill_p = set_find_spill(spill_bb_p->ilp, irn);
1895                                 assert(spill_p);
1896
1897                                 lpp_set_factor_fast(si->lpp, mem_in, spill_p->mem_out, -1.0);
1898                                 lpp_set_factor_fast(si->lpp, reg_in, spill_p->reg_out, -1.0);
1899                         }
1900                 }
1901         }
1902
1903         /* first live ranges from reg_ins */
1904         pset_foreach(live, irn) {
1905                 op_t      *op = get_irn_link(irn);
1906
1907                 spill = set_find_spill(spill_bb->ilp, irn);
1908                 assert(spill && spill->irn == irn);
1909
1910                 ir_snprintf(buf, sizeof(buf), "first_lr_%N_%N", irn, bb);
1911                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1912                 lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, 1.0);
1913                 lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
1914
1915                 foreach_post_remat(bb, tmp) {
1916                         op_t     *remat_op = get_irn_link(tmp);
1917
1918                         if(remat_op->attr.remat.remat->value == irn) {
1919                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1920                         }
1921                 }
1922         }
1923
1924         /* walk forward now and compute constraints for placing spills */
1925         /* this must only be done for values that are not defined in this block */
1926         /* TODO are these values at start of block? if yes, just check whether this is a diverge edge and skip the loop */
1927         pset_foreach(live, irn) {
1928                 spill = set_find_spill(spill_bb->ilp, irn);
1929                 assert(spill);
1930
1931                 ir_snprintf(buf, sizeof(buf), "req_spill_%N_%N", irn, bb);
1932                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1933
1934                 lpp_set_factor_fast(si->lpp, cst, spill->spill, 1.0);
1935                 if(is_diverge_edge(bb)) lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
1936
1937                 sched_foreach_op(bb, tmp) {
1938                         op_t   *op = get_irn_link(tmp);
1939
1940                         if(is_Phi(tmp)) continue;
1941                         assert(!is_Proj(tmp));
1942
1943                         if(op->is_remat) {
1944                                 ir_node   *value = op->attr.remat.remat->value;
1945
1946                                 if(value == irn) {
1947                                         /* only collect remats up to the first use of a value */
1948                                         lpp_set_factor_fast(si->lpp, cst, op->attr.remat.ilp, -1.0);
1949                                 }
1950                         } else {
1951                                 int i,
1952                                         n;
1953
1954                                 for (i = 0, n = get_irn_arity(tmp); i < n; ++i) {
1955                                         ir_node    *arg = get_irn_n(tmp, i);
1956
1957                                         if(arg == irn) {
1958                                                 /* if a value is used stop collecting remats */
1959                                                 cst = ILP_UNDEF;
1960                                         }
1961                                         break;
1962                                 }
1963                         }
1964                         if(cst == ILP_UNDEF) break;
1965                 }
1966         }
1967
1968
1969         /* if a value is used by a mem-phi, then mem_in of this value is 0 (has to be spilled again into a different slot)
1970            mem_in(phi) -> not mem_in(orig_value) TODO: how does this depend on a certain predecessor?
1971          */
1972
1973         /* mem_in of mem-phi has associated costs (but first one is free) */
1974         /* define n_mem_copies as positive integer in each predecessor block,
1975            #mem_in into this block from predecessor block - 1 weighted with SPILL_COST*execfreq(predecessor)
1976            TODO
1977          */
1978
1979
1980         del_pset(live);
1981 }
1982
1983
1984 #if 0
1985          * Speicherkopienminimierung: teste Speicherwerte auf Interferenz
1986          * und weise Spillkontexte zu. Sorge bei Phis dafuer, dass gleiche
1987          * Kontexte zusammenfliessen (Operanden und Ergebnis hat gleichen
1988          * Kontext)
1989 #endif
1990
1991 static INLINE int
1992 is_zero(double x)
1993 {
1994         return fabs(x) < 0.00001;
1995 }
1996
1997 #if 0
1998 static int
1999 is_spilled(const spill_ilp_t * si, const live_range_t * lr)
2000 {
2001         return !is_zero(lpp_get_var_sol(si->lpp, lr->in_mem_var));
2002 }
2003 #endif
2004
2005 static int
2006 is_mem_phi(const ir_node * phi, void *data)
2007 {
2008         spill_ilp_t    *si = data;
2009 //      return is_spilled(si, get_use_head(si, phi)->closest_use);
2010         return 0;
2011 }
2012
2013 #ifdef KEEPALIVE
2014 static int mark_remat_nodes_hook(FILE *F, ir_node *n, ir_node *l)
2015 {
2016         spill_ilp_t *si = get_irg_link(current_ir_graph);
2017
2018         if(pset_find_ptr(si->all_possible_remats, n)) {
2019                 op_t   *op = (op_t*)get_irn_link(n);
2020                 assert(op && op->is_remat);
2021
2022                 if(!op->attr.remat.remat->inverse) {
2023                         if(op->attr.remat.pre) {
2024                                 ir_fprintf(F, "color:red info3:\"remat value: %+F\"", op->attr.remat.remat->value);
2025                         } else {
2026                                 ir_fprintf(F, "color:orange info3:\"remat2 value: %+F\"", op->attr.remat.remat->value);
2027                         }
2028
2029                         return 1;
2030                 } else {
2031                         op_t   *op = (op_t*)get_irn_link(n);
2032                         assert(op && op->is_remat);
2033
2034                         if(op->attr.remat.pre) {
2035                                 ir_fprintf(F, "color:cyan info3:\"remat inverse value: %+F\"", op->attr.remat.remat->value);
2036                         } else {
2037                                 ir_fprintf(F, "color:lightcyan info3:\"remat2 inverse value: %+F\"", op->attr.remat.remat->value);
2038                         }
2039
2040                         return 1;
2041                 }
2042         }
2043
2044         return 0;
2045 }
2046
2047 static void
2048 dump_graph_with_remats(ir_graph * irg, const char * suffix)
2049 {
2050         set_dump_node_vcgattr_hook(mark_remat_nodes_hook);
2051         be_dump(irg, suffix, dump_ir_block_graph_sched);
2052         set_dump_node_vcgattr_hook(NULL);
2053 }
2054 #endif
2055
2056 /**
2057  * Edge hook to dump the schedule edges with annotated register pressure.
2058  */
2059 static int
2060 sched_pressure_edge_hook(FILE *F, ir_node *irn)
2061 {
2062         if(sched_is_scheduled(irn) && sched_has_prev(irn)) {
2063                 ir_node *prev = sched_prev(irn);
2064                 fprintf(F, "edge:{sourcename:\"");
2065                 PRINT_NODEID(irn);
2066                 fprintf(F, "\" targetname:\"");
2067                 PRINT_NODEID(prev);
2068                 fprintf(F, "\" label:\"%d", (int)get_irn_link(irn));
2069                 fprintf(F, "\" color:magenta}\n");
2070         }
2071         return 1;
2072 }
2073
2074 static void
2075 dump_ir_block_graph_sched_pressure(ir_graph *irg, const char *suffix)
2076 {
2077         DUMP_NODE_EDGE_FUNC old = get_dump_node_edge_hook();
2078
2079         dump_consts_local(0);
2080         set_dump_node_edge_hook(sched_pressure_edge_hook);
2081         dump_ir_block_graph(irg, suffix);
2082         set_dump_node_edge_hook(old);
2083 }
2084
2085 static void
2086 walker_pressure_annotator(ir_node * bb, void * data)
2087 {
2088         spill_ilp_t  *si = data;
2089         ir_node      *irn;
2090         irn_live_t   *li;
2091         int           i,
2092                                   n;
2093         pset         *live = pset_new_ptr_default();
2094         int           projs = 0;
2095
2096         live_foreach(bb, li) {
2097                 irn = (ir_node *) li->irn;
2098
2099                 if (live_is_end(li) && has_reg_class(si, irn)) {
2100                         pset_insert_ptr(live, irn);
2101                 }
2102         }
2103
2104         set_irn_link(bb, INT_TO_PTR(pset_count(live)));
2105
2106         sched_foreach_reverse(bb, irn) {
2107                 if(is_Phi(irn)) {
2108                         set_irn_link(irn, INT_TO_PTR(pset_count(live)));
2109                         continue;
2110                 }
2111
2112                 if(has_reg_class(si, irn)) {
2113                         pset_remove_ptr(live, irn);
2114                         if(is_Proj(irn)) ++projs;
2115                 }
2116
2117                 if(!is_Proj(irn)) projs = 0;
2118
2119                 for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
2120                         ir_node    *arg = get_irn_n(irn, i);
2121
2122                         if(has_reg_class(si, arg)) pset_insert_ptr(live, arg);
2123                 }
2124                 set_irn_link(irn, INT_TO_PTR(pset_count(live)+projs));
2125         }
2126
2127         del_pset(live);
2128 }
2129
2130 static void
2131 dump_pressure_graph(spill_ilp_t * si, const char *suffix)
2132 {
2133         be_dump(si->chordal_env->irg, suffix, dump_ir_block_graph_sched_pressure);
2134 }
2135
2136 #ifdef KEEPALIVE
2137 static void
2138 connect_all_remats_with_keep(spill_ilp_t * si)
2139 {
2140         ir_node   *irn;
2141         ir_node  **ins,
2142                          **pos;
2143         int        n_remats;
2144
2145
2146         n_remats = pset_count(si->all_possible_remats);
2147         if(n_remats) {
2148                 ins = obstack_alloc(si->obst, n_remats * sizeof(*ins));
2149
2150                 pos = ins;
2151                 pset_foreach(si->all_possible_remats, irn) {
2152                         *pos = irn;
2153                         ++pos;
2154                 }
2155
2156                 si->keep = be_new_Keep(si->chordal_env->cls, si->chordal_env->irg, get_irg_end_block(si->chordal_env->irg), n_remats, ins);
2157
2158                 obstack_free(si->obst, ins);
2159         }
2160 }
2161 #endif
2162
2163 static void
2164 connect_all_spills_with_keep(spill_ilp_t * si)
2165 {
2166         ir_node   *irn;
2167         ir_node  **ins,
2168                          **pos;
2169         int        n_spills;
2170         ir_node   *keep;
2171
2172
2173         n_spills = pset_count(si->spills);
2174         if(n_spills) {
2175                 ins = obstack_alloc(si->obst, n_spills * sizeof(*ins));
2176
2177                 pos = ins;
2178                 pset_foreach(si->spills, irn) {
2179                         *pos = irn;
2180                         ++pos;
2181                 }
2182
2183                 keep = be_new_Keep(si->chordal_env->cls, si->chordal_env->irg, get_irg_end_block(si->chordal_env->irg), n_spills, ins);
2184
2185                 obstack_free(si->obst, ins);
2186         }
2187 }
2188
2189 /** insert a spill at an arbitrary position */
2190 ir_node *be_spill2(const arch_env_t *arch_env, ir_node *irn, ir_node *insert, ir_node *ctx)
2191 {
2192         ir_node *bl     = is_Block(insert)?insert:get_nodes_block(insert);
2193         ir_graph *irg   = get_irn_irg(bl);
2194         ir_node *frame  = get_irg_frame(irg);
2195         ir_node *spill;
2196         ir_node *next;
2197
2198         const arch_register_class_t *cls       = arch_get_irn_reg_class(arch_env, irn, -1);
2199         const arch_register_class_t *cls_frame = arch_get_irn_reg_class(arch_env, frame, -1);
2200
2201         spill = be_new_Spill(cls, cls_frame, irg, bl, frame, irn, ctx);
2202
2203         /*
2204          * search the right insertion point. a spill of a phi cannot be put
2205          * directly after the phi, if there are some phis behind the one which
2206          * is spilled. Also, a spill of a Proj must be after all Projs of the
2207          * same tuple node.
2208          *
2209          * Here's one special case:
2210          * If the spill is in the start block, the spill must be after the frame
2211          * pointer is set up. This is done by setting insert to the end of the block
2212          * which is its default initialization (see above).
2213          */
2214
2215         if(bl == get_irg_start_block(irg) && sched_get_time_step(frame) >= sched_get_time_step(insert))
2216                 insert = frame;
2217
2218         for (next = sched_next(insert); is_Phi(next) || is_Proj(next); next = sched_next(insert))
2219                 insert = next;
2220
2221         sched_add_after(insert, spill);
2222         return spill;
2223 }
2224
2225 static void
2226 delete_remat(spill_ilp_t * si, ir_node * remat) {
2227         int       i,
2228                       n;
2229         ir_node  *bad = get_irg_bad(si->chordal_env->irg);
2230
2231         sched_remove(remat);
2232
2233         /* kill links to operands */
2234         for (i = -1, n = get_irn_arity(remat); i < n; ++i) {
2235                 set_irn_n(remat, i, bad);
2236         }
2237 }
2238
2239 static void
2240 clean_remat_info(spill_ilp_t * si)
2241 {
2242         int            i,
2243                                n;
2244         remat_t       *remat;
2245         remat_info_t  *remat_info;
2246         ir_node       *bad = get_irg_bad(si->chordal_env->irg);
2247
2248         set_foreach(si->remat_info, remat_info) {
2249                 if(!remat_info->remats) continue;
2250
2251                 pset_foreach(remat_info->remats, remat)
2252                 {
2253                         if(remat->proj && get_irn_n_edges(remat->proj) == 0) {
2254                                 set_irn_n(remat->proj, -1, bad);
2255                                 set_irn_n(remat->proj, 0, bad);
2256                         }
2257
2258                         if(get_irn_n_edges(remat->op) == 0) {
2259                                 for (i = -1, n = get_irn_arity(remat->op); i < n; ++i) {
2260                                         set_irn_n(remat->op, i, bad);
2261                                 }
2262                         }
2263                 }
2264
2265                 if(remat_info->remats) del_pset(remat_info->remats);
2266                 if(remat_info->remats_by_operand) del_pset(remat_info->remats_by_operand);
2267         }
2268 }
2269
2270 static void
2271 delete_unnecessary_remats(spill_ilp_t * si)
2272 {
2273 #ifdef KEEPALIVE
2274         int       i,
2275                       n;
2276         ir_node  *bad = get_irg_bad(si->chordal_env->irg);
2277
2278         if(si->keep) {
2279                 ir_node   *end = get_irg_end(si->chordal_env->irg);
2280                 ir_node  **keeps;
2281
2282                 for (i = 0, n = get_irn_arity(si->keep); i < n; ++i) {
2283                         ir_node        *keep_arg = get_irn_n(si->keep, i);
2284                         op_t           *arg_op = get_irn_link(keep_arg);
2285                         lpp_name_t     *name;
2286
2287                         assert(arg_op->is_remat);
2288
2289                         name = si->lpp->vars[arg_op->attr.remat.ilp];
2290
2291                         if(is_zero(name->value)) {
2292                                 DBG((si->dbg, LEVEL_3, "\t  deleting remat %+F\n", keep_arg));
2293                                 /* TODO check whether reload is preferred over remat (could be bug) */
2294                                 delete_remat(si, keep_arg);
2295                         } else {
2296                                 if(!arg_op->attr.remat.remat->inverse) {
2297                                         if(arg_op->attr.remat.pre) {
2298                                                 DBG((si->dbg, LEVEL_2, "\t**remat kept: %+F\n", keep_arg));
2299                                         } else {
2300                                                 DBG((si->dbg, LEVEL_2, "\t%%%%remat2 kept: %+F\n", keep_arg));
2301                                         }
2302                                 } else {
2303                                         if(arg_op->attr.remat.pre) {
2304                                                 DBG((si->dbg, LEVEL_2, "\t**INVERSE remat kept: %+F\n", keep_arg));
2305                                         } else {
2306                                                 DBG((si->dbg, LEVEL_2, "\t%%%%INVERSE remat2 kept: %+F\n", keep_arg));
2307                                         }
2308                                 }
2309                         }
2310
2311                         set_irn_n(si->keep, i, bad);
2312                 }
2313 #if 0
2314                 for (i = 0, n = get_End_n_keepalives(end); i < n; ++i) {
2315                         ir_node        *end_arg = get_End_keepalive(end, i);
2316
2317                         if(end_arg != si->keep) {
2318                                 obstack_grow(si->obst, &end_arg, sizeof(end_arg));
2319                         }
2320                 }
2321                 keeps = obstack_finish(si->obst);
2322                 set_End_keepalives(end, n-1, keeps);
2323                 obstack_free(si->obst, keeps);
2324 #endif
2325         } else {
2326                 DBG((si->dbg, LEVEL_2, "\t  no remats to delete (none have been inserted)\n"));
2327         }
2328 #else
2329         ir_node  *remat;
2330
2331         pset_foreach(si->all_possible_remats, remat) {
2332                 op_t           *remat_op = get_irn_link(remat);
2333                 lpp_name_t     *name = si->lpp->vars[remat_op->attr.remat.ilp];
2334
2335                 if(is_zero(name->value)) {
2336                         DBG((si->dbg, LEVEL_3, "\t  deleting remat %+F\n", remat));
2337                         /* TODO check whether reload is preferred over remat (could be bug) */
2338                         delete_remat(si, remat);
2339                 } else {
2340                         if(!remat_op->attr.remat.remat->inverse) {
2341                                 if(remat_op->attr.remat.pre) {
2342                                         DBG((si->dbg, LEVEL_2, "\t**remat kept: %+F\n", remat));
2343                                 } else {
2344                                         DBG((si->dbg, LEVEL_2, "\t%%%%remat2 kept: %+F\n", remat));
2345                                 }
2346                         } else {
2347                                 if(remat_op->attr.remat.pre) {
2348                                         DBG((si->dbg, LEVEL_2, "\t**INVERSE remat kept: %+F\n", remat));
2349                                 } else {
2350                                         DBG((si->dbg, LEVEL_2, "\t%%%%INVERSE remat2 kept: %+F\n", remat));
2351                                 }
2352                         }
2353                 }
2354         }
2355 #endif
2356 }
2357
2358 /**
2359  * @param before   The node after which the spill will be placed in the schedule
2360  */
2361 /* TODO set context properly */
2362 static ir_node *
2363 insert_spill(spill_ilp_t * si, ir_node * irn, ir_node * value, ir_node * before)
2364 {
2365         defs_t   *defs;
2366         ir_node  *spill;
2367         const arch_env_t *arch_env = si->chordal_env->birg->main_env->arch_env;
2368
2369         DBG((si->dbg, LEVEL_3, "\t  inserting spill for value %+F after %+F\n", irn, before));
2370
2371         spill = be_spill2(arch_env, irn, before, irn);
2372
2373         defs = set_insert_def(si->values, value);
2374         assert(defs);
2375
2376         /* enter into the linked list */
2377         set_irn_link(spill, defs->spills);
2378         defs->spills = spill;
2379
2380 #ifdef KEEPALIVE_SPILLS
2381         pset_insert_ptr(si->spills, spill);
2382 #endif
2383
2384         return spill;
2385 }
2386
2387 /**
2388  * @param before   The Phi node which has to be spilled
2389  */
2390 static ir_node *
2391 insert_mem_phi(spill_ilp_t * si, const ir_node * phi)
2392 {
2393         ir_node   *mem_phi;
2394         ir_node  **ins;
2395         defs_t    *defs;
2396         int        i,
2397                            n;
2398
2399         NEW_ARR_A(ir_node*, ins, get_irn_arity(phi));
2400
2401         for(i=0,n=get_irn_arity(phi); i<n; ++i) {
2402                 ins[i] = si->m_unknown;
2403         }
2404
2405         mem_phi =  new_r_Phi(si->chordal_env->irg, get_nodes_block(phi), get_irn_arity(phi), ins, mode_M);
2406
2407         defs = set_insert_def(si->values, phi);
2408         assert(defs);
2409
2410         /* enter into the linked list */
2411         set_irn_link(mem_phi, defs->spills);
2412         defs->spills = mem_phi;
2413
2414         sched_add_after(phi, mem_phi);
2415
2416 #ifdef KEEPALIVE_SPILLS
2417         pset_insert_ptr(si->spills, mem_phi);
2418 #endif
2419
2420         return mem_phi;
2421 }
2422
2423 /**
2424  * Add remat to list of defs, destroys link field!
2425  */
2426 static void
2427 insert_remat(spill_ilp_t * si, ir_node * remat)
2428 {
2429         defs_t   *defs;
2430         op_t     *remat_op = get_irn_link(remat);
2431
2432         assert(remat_op->is_remat);
2433
2434         defs = set_insert_def(si->values, remat_op->attr.remat.remat->value);
2435         assert(defs);
2436
2437         /* enter into the linked list */
2438         set_irn_link(remat, defs->remats);
2439         defs->remats = remat;
2440 }
2441
2442 #if 0
2443 static void
2444 collect_spills(spill_ilp_t * si, ir_node * value, pset * spills, pset * visited)
2445 {
2446         ir_node  *next;
2447         defs_t   *defs;
2448
2449         defs = set_find_def(si->values, value);
2450
2451         if(defs && defs->spills) {
2452                 for(next = defs->spills; next; next = get_irn_link(next)) {
2453                         pset_insert_ptr(spills, next);
2454                 }
2455         } else if (is_Phi(value)) {
2456                 /* recursion */
2457                 if(!pset_find_ptr(visited, value)) {
2458                         int    i,
2459                                    n;
2460
2461                         pset_insert_ptr(visited, value);
2462                         for(i=0, n=get_irn_arity(value); i<n; ++i) {
2463                                 ir_node    *arg = get_irn_n(value, i);
2464
2465                                 collect_spills(si, arg, spills, visited);
2466                         }
2467                 }
2468         } else {
2469 //              assert(0 && "Phi operand not spilled");
2470         }
2471 }
2472 #endif
2473
2474 static pset *
2475 get_spills_for_value(spill_ilp_t * si, ir_node * value)
2476 {
2477         pset     *spills = pset_new_ptr_default();
2478 //      pset     *visited = pset_new_ptr_default();
2479
2480 //      collect_spills(si, value, spills, visited);
2481 //      del_pset(visited);
2482         ir_node  *next;
2483         defs_t   *defs;
2484
2485         defs = set_find_def(si->values, value);
2486
2487         if(defs && defs->spills) {
2488                 for(next = defs->spills; next; next = get_irn_link(next)) {
2489                         pset_insert_ptr(spills, next);
2490                 }
2491         }
2492
2493         return spills;
2494 }
2495
2496 /**
2497  * Add reload before operation and add to list of defs
2498  */
2499 static ir_node *
2500 insert_reload(spill_ilp_t * si, const ir_node * value, const ir_node * after)
2501 {
2502         defs_t   *defs;
2503         ir_node  *reload,
2504                          *spill;
2505         const arch_env_t *arch_env = si->chordal_env->birg->main_env->arch_env;
2506
2507         DBG((si->dbg, LEVEL_3, "\t  inserting reload for value %+F before %+F\n", value, after));
2508
2509         defs = set_find_def(si->values, value);
2510         /* get a spill of this value */
2511 #if 0
2512         if((!defs || !defs->spills) && is_Phi(value)) {
2513                 pset  *spills;
2514
2515                 spills = get_spills_for_value(si, value);
2516
2517                 spill = pset_first(spills);
2518                 del_pset(spills);
2519
2520                 if(!defs) {
2521                         defs = set_insert_def(si->values, value);
2522                 }
2523                 defs->spills = spill;
2524                 set_irn_link(spill, NULL);
2525         } else {
2526                 spill = defs->spills;
2527         }
2528 #endif
2529         spill = defs->spills;
2530         assert(spill && "no spill placed before reload");
2531
2532         reload = be_reload(arch_env, si->cls, after, get_irn_mode(value), spill);
2533
2534         /* enter into the linked list */
2535         set_irn_link(reload, defs->remats);
2536         defs->remats = reload;
2537
2538         return reload;
2539 }
2540
2541 static void
2542 walker_spill_placer(ir_node * bb, void * data) {
2543         spill_ilp_t   *si = (spill_ilp_t*)data;
2544         ir_node       *irn;
2545         spill_bb_t    *spill_bb = get_irn_link(bb);
2546         pset          *spills_to_do = pset_new_ptr_default();
2547         spill_t       *spill;
2548
2549         set_foreach(spill_bb->ilp, spill) {
2550                 lpp_name_t    *name;
2551
2552                 if(is_Phi(spill->irn) && get_nodes_block(spill->irn) == bb) {
2553                         name = si->lpp->vars[spill->mem_in];
2554                         if(!is_zero(name->value)) {
2555                                 ir_node   *mem_phi;
2556
2557                                 mem_phi = insert_mem_phi(si, spill->irn);
2558
2559                                 DBG((si->dbg, LEVEL_2, "\t >>spilled Phi %+F -> %+F\n", spill->irn, mem_phi));
2560                         }
2561                 }
2562
2563                 name = si->lpp->vars[spill->spill];
2564                 if(!is_zero(name->value)) {
2565                         if(spill->reg_in > 0) {
2566                                 name = si->lpp->vars[spill->reg_in];
2567                                 if(!is_zero(name->value)) {
2568                                         insert_spill(si, spill->irn, spill->irn, bb);
2569                                         continue;
2570                                 }
2571                         }
2572                         pset_insert_ptr(spills_to_do, spill->irn);
2573                 }
2574         }
2575         DBG((si->dbg, LEVEL_3, "\t  %d spills to do in block %+F\n", pset_count(spills_to_do), bb));
2576
2577
2578         for(irn = sched_block_first_nonphi(bb); !sched_is_end(irn); irn = sched_next(irn)) {
2579                 op_t     *op = get_irn_link(irn);
2580
2581                 if(be_is_Spill(irn)) continue;
2582
2583                 if(op->is_remat) {
2584                         /* TODO fix this if we want to support remats with more than two nodes */
2585                         if(get_irn_mode(irn) != mode_T && pset_find_ptr(spills_to_do, op->attr.remat.remat->value)) {
2586                                 pset_remove_ptr(spills_to_do, op->attr.remat.remat->value);
2587
2588                                 insert_spill(si, irn, op->attr.remat.remat->value, irn);
2589                         }
2590                 } else {
2591                         if(pset_find_ptr(spills_to_do, irn)) {
2592                                 pset_remove_ptr(spills_to_do, irn);
2593
2594                                 insert_spill(si, irn, irn, irn);
2595                         }
2596                 }
2597
2598         }
2599
2600         assert(pset_count(spills_to_do) == 0);
2601
2602         /* afterwards free data in block */
2603         del_pset(spills_to_do);
2604 }
2605
2606 static void
2607 phim_fixer(spill_ilp_t *si) {
2608         defs_t  *defs;
2609
2610         set_foreach(si->values, defs) {
2611                 const ir_node  *phi = defs->value;
2612                 ir_node  *phi_m = NULL;
2613                 ir_node  *next = defs->spills;
2614                 int       i,
2615                                   n;
2616
2617                 if(!is_Phi(phi)) continue;
2618
2619                 while(next) {
2620                         if(is_Phi(next) && get_irn_mode(next) == mode_M) {
2621                                 phi_m = next;
2622                                 break;
2623                         } else {
2624                                 next = get_irn_link(next);
2625                         }
2626                 }
2627                 if(!phi_m) continue;
2628
2629                 for(i=0,n=get_irn_arity(phi); i<n; ++i) {
2630                         const ir_node  *value = get_irn_n(phi, i);
2631                         defs_t         *val_defs = set_find_def(si->values, value);
2632
2633                         /* get a spill of this value */
2634                         ir_node      *spill = val_defs->spills;
2635
2636                         assert(spill && "no spill placed before PhiM");
2637
2638                         set_irn_n(phi_m, i, spill);
2639                 }
2640         }
2641 }
2642
2643 static void
2644 walker_reload_placer(ir_node * bb, void * data) {
2645         spill_ilp_t   *si = (spill_ilp_t*)data;
2646         ir_node       *irn;
2647         spill_bb_t    *spill_bb = get_irn_link(bb);
2648         int            i;
2649         irn_live_t    *li;
2650
2651         sched_foreach_reverse(bb, irn) {
2652                 op_t     *op = get_irn_link(irn);
2653
2654                 if(be_is_Reload(irn) || be_is_Spill(irn)) continue;
2655                 if(is_Phi(irn)) break;
2656
2657                 if(op->is_remat) {
2658                         if(get_irn_mode(irn) != mode_T) {
2659                                 insert_remat(si, irn);
2660                         }
2661                 } else {
2662                         int    n;
2663
2664                         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
2665                                 ir_node    *arg = get_irn_n(irn, i);
2666
2667                                 if(op->attr.live_range.reloads && op->attr.live_range.reloads[i] != ILP_UNDEF) {
2668                                         lpp_name_t    *name;
2669
2670                                         name = si->lpp->vars[op->attr.live_range.reloads[i]];
2671                                         if(!is_zero(name->value)) {
2672                                                 ir_node    *reload;
2673                                                 ir_node    *insert_pos = irn;
2674                                                 ir_node    *prev = insert_pos;
2675                                                 op_t       *prev_op;
2676
2677                                                 do {
2678                                                         prev = sched_prev(prev);
2679                                                 } while(be_is_Spill(prev));
2680
2681                                                 prev_op = get_irn_link(prev);
2682
2683                                                 /* insert reload before pre-remats */
2684                                                 while(!sched_is_end(prev) && !be_is_Reload(prev) && !is_Phi(prev)
2685                                                                 && prev_op->is_remat && prev_op->attr.remat.pre) {
2686                                                         insert_pos = prev;
2687
2688                                                         do {
2689                                                                 prev = sched_prev(prev);
2690                                                         } while(be_is_Spill(prev));
2691
2692                                                         prev_op = get_irn_link(prev);
2693
2694                                                 }
2695
2696                                                 reload = insert_reload(si, arg, insert_pos);
2697
2698                                                 set_irn_n(irn, i, reload);
2699
2700 #ifdef KEEPALIVE_RELOADS
2701                                                 pset_insert_ptr(si->spills, reload);
2702 #endif
2703                                         }
2704                                 }
2705                         }
2706                 }
2707         }
2708
2709         /* reloads at end of block */
2710         if(spill_bb->reloads) {
2711                 i=0;
2712                 live_foreach(bb, li) {
2713                         ir_node        *irn = (ir_node *) li->irn;
2714
2715                         if (live_is_end(li) && has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
2716                                 lpp_name_t    *name;
2717
2718                                 name = si->lpp->vars[spill_bb->reloads[i]];
2719                                 if(!is_zero(name->value)) {
2720                                         ir_node    *reload;
2721                                         ir_node    *insert_pos = bb;
2722                                         ir_node    *prev = sched_prev(insert_pos);
2723                                         op_t       *prev_op = get_irn_link(prev);
2724
2725                                         /* insert reload before pre-remats */
2726                                         while(!sched_is_end(prev) && !be_is_Reload(prev) && !be_is_Spill(prev)
2727                                                         && prev_op->is_remat && prev_op->attr.remat.pre) {
2728                                                 insert_pos = prev;
2729
2730                                                 prev = sched_prev(insert_pos);
2731                                                 prev_op = get_irn_link(prev);
2732                                         }
2733
2734                                         reload = insert_reload(si, irn, insert_pos);
2735
2736 #ifdef KEEPALIVE_RELOADS
2737                                         pset_insert_ptr(si->spills, reload);
2738 #endif
2739                                 }
2740                                 ++i;
2741                         }
2742                 }
2743         }
2744
2745         del_set(spill_bb->ilp);
2746 }
2747
2748 static void
2749 walker_collect_used(ir_node * irn, void * data)
2750 {
2751         lc_bitset_t   *used = data;
2752
2753         lc_bitset_set(used, get_irn_idx(irn));
2754 }
2755
2756 struct kill_helper {
2757         lc_bitset_t  *used;
2758         spill_ilp_t  *si;
2759 };
2760
2761 static void
2762 walker_kill_unused(ir_node * bb, void * data)
2763 {
2764         struct kill_helper *kh = data;
2765         const ir_node      *bad = get_irg_bad(get_irn_irg(bb));
2766         ir_node            *irn;
2767
2768
2769         for(irn=sched_first(bb); !sched_is_end(irn);) {
2770                 ir_node     *next = sched_next(irn);
2771                 int          i,
2772                                          n;
2773
2774                 if(!lc_bitset_is_set(kh->used, get_irn_idx(irn))) {
2775                         if(be_is_Spill(irn) || be_is_Reload(irn)) {
2776                                 DBG((kh->si->dbg, LEVEL_1, "\t SUBOPTIMAL! %+F IS UNUSED (cost: %g)\n", irn, get_cost(kh->si, irn)*execution_frequency(kh->si, bb)));
2777                                 assert(lpp_get_sol_state(kh->si->lpp) != lpp_optimal && "optimal solution is suboptimal?");
2778                         }
2779
2780                         sched_remove(irn);
2781
2782                         set_nodes_block(irn, bad);
2783                         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
2784                                 set_irn_n(irn, i, bad);
2785                         }
2786                 }
2787                 irn = next;
2788         }
2789 }
2790
2791 static void
2792 kill_all_unused_values_in_schedule(spill_ilp_t * si)
2793 {
2794         struct kill_helper kh;
2795
2796         kh.used = lc_bitset_malloc(get_irg_last_idx(si->chordal_env->irg));
2797         kh.si = si;
2798
2799         irg_walk_graph(si->chordal_env->irg, walker_collect_used, NULL, kh.used);
2800         irg_block_walk_graph(si->chordal_env->irg, walker_kill_unused, NULL, &kh);
2801
2802         lc_bitset_free(kh.used);
2803 }
2804
2805 static void
2806 print_irn_pset(pset * p)
2807 {
2808         ir_node   *irn;
2809
2810         pset_foreach(p, irn) {
2811                 ir_printf("%+F\n", irn);
2812         }
2813 }
2814
2815 static void
2816 rewire_uses(spill_ilp_t * si)
2817 {
2818         dom_front_info_t     *dfi = be_compute_dominance_frontiers(si->chordal_env->irg);
2819         defs_t               *defs;
2820         pset                 *ignore = pset_new_ptr(1);
2821
2822         pset_insert_ptr(ignore, get_irg_end(si->chordal_env->irg));
2823
2824         /* then fix uses of spills */
2825         set_foreach(si->values, defs) {
2826                 pset     *reloads;
2827                 pset     *spills;
2828                 ir_node  *next = defs->remats;
2829                 int remats = 0;
2830
2831                 reloads = pset_new_ptr_default();
2832
2833                 while(next) {
2834                         if(be_is_Reload(next)) {
2835                                 pset_insert_ptr(reloads, next);
2836                         } else {
2837                                 ++remats;
2838                         }
2839                         next = get_irn_link(next);
2840                 }
2841
2842                 spills = get_spills_for_value(si, defs->value);
2843                 DBG((si->dbg, LEVEL_2, "\t  %d remats, %d reloads, and %d spills for value %+F\n", remats, pset_count(reloads), pset_count(spills), defs->value));
2844                 if(pset_count(spills) > 1) {
2845                         //assert(pset_count(reloads) > 0);
2846                         //                              print_irn_pset(spills);
2847                         //                              print_irn_pset(reloads);
2848
2849                         be_ssa_constr_set_ignore(dfi, spills, ignore);
2850                 }
2851
2852                 del_pset(reloads);
2853                 del_pset(spills);
2854         }
2855
2856         /* first fix uses of remats and reloads */
2857         set_foreach(si->values, defs) {
2858                 pset     *nodes;
2859                 ir_node  *next = defs->remats;
2860
2861                 if(next) {
2862                         nodes = pset_new_ptr_default();
2863                         pset_insert_ptr(nodes, defs->value);
2864
2865                         while(next) {
2866                                 pset_insert_ptr(nodes, next);
2867                                 next = get_irn_link(next);
2868                         }
2869
2870                         if(pset_count(nodes) > 1) {
2871                                 DBG((si->dbg, LEVEL_4, "\t    %d new definitions for value %+F\n", pset_count(nodes)-1, defs->value));
2872                                 be_ssa_constr_set(dfi, nodes);
2873                         }
2874
2875                         del_pset(nodes);
2876                 }
2877         }
2878
2879 //      remove_unused_defs(si);
2880
2881         be_free_dominance_frontiers(dfi);
2882 }
2883
2884 static void
2885 writeback_results(spill_ilp_t * si)
2886 {
2887         /* walk through the graph and collect all spills, reloads and remats for a value */
2888
2889         si->values = new_set(cmp_defs, 4096);
2890
2891         DBG((si->dbg, LEVEL_1, "Applying results\n"));
2892         delete_unnecessary_remats(si);
2893         si->m_unknown = new_r_Unknown(si->chordal_env->irg, mode_M);
2894         irg_block_walk_graph(si->chordal_env->irg, walker_spill_placer, NULL, si);
2895         phim_fixer(si);
2896         irg_block_walk_graph(si->chordal_env->irg, walker_reload_placer, NULL, si);
2897
2898         /* clean the remat info! there are still back-edges leading there! */
2899         clean_remat_info(si);
2900
2901         rewire_uses(si);
2902
2903         connect_all_spills_with_keep(si);
2904
2905         del_set(si->values);
2906 }
2907
2908 static int
2909 get_n_regs(spill_ilp_t * si)
2910 {
2911         int     arch_n_regs = arch_register_class_n_regs(si->cls);
2912         int     free = 0;
2913         int     i;
2914
2915         for(i=0; i<arch_n_regs; i++) {
2916                 if(!arch_register_type_is(&si->cls->regs[i], ignore)) {
2917                         free++;
2918                 }
2919         }
2920
2921         DBG((si->dbg, LEVEL_1, "\tArchitecture has %d free registers in class %s\n", free, si->cls->name));
2922         return free;
2923 }
2924
2925 static void
2926 walker_reload_mover(ir_node * bb, void * data)
2927 {
2928         spill_ilp_t   *si = data;
2929         ir_node           *tmp;
2930
2931         sched_foreach(bb, tmp) {
2932                 if(be_is_Reload(tmp) && has_reg_class(si, tmp)) {
2933                         ir_node       *reload = tmp;
2934                         ir_node       *irn = tmp;
2935
2936                         /* move reload upwards */
2937
2938                         int pressure = (int)get_irn_link(reload);
2939                         if(pressure < si->n_regs) {
2940                                 irn = sched_prev(reload);
2941                                 DBG((si->dbg, LEVEL_5, "regpressure before %+F: %d\n", reload, pressure));
2942                                 sched_remove(reload);
2943                                 pressure = (int)get_irn_link(irn);
2944
2945                                 while(pressure < si->n_regs) {
2946                                         if(sched_is_end(irn) || (be_is_Reload(irn) && has_reg_class(si, irn))) break;
2947
2948                                         set_irn_link(irn, INT_TO_PTR(pressure+1));
2949                                         DBG((si->dbg, LEVEL_5, "new regpressure before %+F: %d\n", irn, pressure+1));
2950                                         irn = sched_prev(irn);
2951
2952                                         pressure = (int)get_irn_link(irn);
2953                                 }
2954
2955                                 DBG((si->dbg, LEVEL_3, "putting reload %+F after %+F\n", reload, irn));
2956                                 sched_put_after(irn, reload);
2957                         }
2958                 }
2959         }
2960 }
2961
2962 static void
2963 move_reloads_upward(spill_ilp_t * si)
2964 {
2965         irg_block_walk_graph(si->chordal_env->irg, walker_reload_mover, NULL, si);
2966 }
2967
2968 void
2969 be_spill_remat(const be_chordal_env_t * chordal_env)
2970 {
2971         char            problem_name[256];
2972         char            dump_suffix[256];
2973         char            dump_suffix2[256];
2974         char            dump_suffix3[256];
2975         struct obstack  obst;
2976         spill_ilp_t     si;
2977
2978         ir_snprintf(problem_name, sizeof(problem_name), "%F_%s", chordal_env->irg, chordal_env->cls->name);
2979         ir_snprintf(dump_suffix, sizeof(dump_suffix), "-%s-remats", chordal_env->cls->name);
2980         ir_snprintf(dump_suffix2, sizeof(dump_suffix2), "-%s-pressure", chordal_env->cls->name);
2981         ir_snprintf(dump_suffix3, sizeof(dump_suffix3), "-%s-reloads_moved", chordal_env->cls->name);
2982
2983         FIRM_DBG_REGISTER(si.dbg, "firm.be.ra.spillremat");
2984         DBG((si.dbg, LEVEL_1, "\n\n\t\t===== Processing %s =====\n\n", problem_name));
2985
2986         obstack_init(&obst);
2987         si.chordal_env = chordal_env;
2988         si.obst = &obst;
2989         si.cls = chordal_env->cls;
2990         si.lpp = new_lpp(problem_name, lpp_minimize);
2991         si.remat_info = new_set(cmp_remat_info, 4096);
2992         si.all_possible_remats = pset_new_ptr_default();
2993         si.spills = pset_new_ptr_default();
2994         si.inverse_ops = pset_new_ptr_default();
2995 #ifndef EXECFREQ_LOOPDEPH
2996         si.execfreqs = compute_execfreq(chordal_env->irg);
2997 #else
2998         si.execfreqs = NULL;
2999 #endif
3000 #ifdef KEEPALIVE
3001         si.keep = NULL;
3002 #endif
3003         si.n_regs = get_n_regs(&si);
3004
3005         set_irg_link(chordal_env->irg, &si);
3006         compute_doms(chordal_env->irg);
3007
3008         be_analyze_regpressure(chordal_env, "-pre");
3009
3010 #ifdef COLLECT_REMATS
3011         /* collect remats */
3012         DBG((si.dbg, LEVEL_1, "Collecting remats\n"));
3013         irg_walk_graph(chordal_env->irg, walker_remat_collector, NULL, &si);
3014 #endif
3015
3016         /* insert possible remats */
3017         DBG((si.dbg, LEVEL_1, "Inserting possible remats\n"));
3018         irg_block_walk_graph(chordal_env->irg, walker_remat_insertor, NULL, &si);
3019         DBG((si.dbg, LEVEL_2, " -> inserted %d possible remats\n", pset_count(si.all_possible_remats)));
3020
3021 #ifdef KEEPALIVE
3022         DBG((si.dbg, LEVEL_1, "Connecting remats with keep and dumping\n"));
3023         connect_all_remats_with_keep(&si);
3024         /* dump graph with inserted remats */
3025         dump_graph_with_remats(chordal_env->irg, dump_suffix);
3026 #endif
3027
3028
3029         /* recompute liveness */
3030         DBG((si.dbg, LEVEL_1, "Recomputing liveness\n"));
3031         be_liveness(chordal_env->irg);
3032
3033         /* build the ILP */
3034
3035         DBG((si.dbg, LEVEL_1, "\tBuilding ILP\n"));
3036         DBG((si.dbg, LEVEL_2, "\t endwalker\n"));
3037         irg_block_walk_graph(chordal_env->irg, luke_endwalker, NULL, &si);
3038
3039         DBG((si.dbg, LEVEL_2, "\t blockwalker\n"));
3040         irg_block_walk_graph(chordal_env->irg, luke_blockwalker, NULL, &si);
3041
3042 #ifdef DUMP_ILP
3043         {
3044                 FILE           *f;
3045                 char            buf[256];
3046
3047                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.ilp", problem_name);
3048                 if ((f = fopen(buf, "wt")) != NULL) {
3049                         lpp_dump_plain(si.lpp, f);
3050                         fclose(f);
3051                 }
3052         }
3053 #endif
3054
3055 #ifdef SOLVE
3056         DBG((si.dbg, LEVEL_1, "\tSolving %F\n", chordal_env->irg));
3057 #ifdef ILP_TIMEOUT
3058         lpp_set_time_limit(si.lpp, ILP_TIMEOUT);
3059 #endif
3060
3061 #ifdef SOLVE_LOCAL
3062         lpp_solve_cplex(si.lpp);
3063 #else
3064         lpp_solve_net(si.lpp, LPP_SERVER, LPP_SOLVER);
3065 #endif
3066         assert(lpp_is_sol_valid(si.lpp)
3067                && "solution of ILP must be valid");
3068
3069         DBG((si.dbg, LEVEL_1, "\t%s: iterations: %d, solution time: %g, objective function: %g\n", problem_name, si.lpp->iterations, si.lpp->sol_time, is_zero(si.lpp->objval)?0.0:si.lpp->objval));
3070
3071 #ifdef DUMP_SOLUTION
3072         {
3073                 FILE           *f;
3074                 char            buf[256];
3075
3076                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.sol", problem_name);
3077                 if ((f = fopen(buf, "wt")) != NULL) {
3078                         int             i;
3079                         for (i = 0; i < si.lpp->var_next; ++i) {
3080                                 lpp_name_t     *name = si.lpp->vars[i];
3081                                 fprintf(f, "%20s %4d %10f\n", name->name, name->nr, name->value);
3082                         }
3083                         fclose(f);
3084                 }
3085         }
3086 #endif
3087
3088         writeback_results(&si);
3089
3090 #endif                          /* SOLVE */
3091
3092         kill_all_unused_values_in_schedule(&si);
3093
3094 #if defined(KEEPALIVE_SPILLS) || defined(KEEPALIVE_RELOADS)
3095         be_dump(chordal_env->irg, "-spills-placed", dump_ir_block_graph);
3096 #endif
3097
3098         be_liveness(chordal_env->irg);
3099         irg_block_walk_graph(chordal_env->irg, walker_pressure_annotator, NULL, &si);
3100
3101         dump_pressure_graph(&si, dump_suffix2);
3102
3103         // TODO fix temporarily exceeded regpressure due to remat2s
3104
3105         // TODO insert copys to fix interferences in memory
3106
3107         // move reloads upwards
3108         move_reloads_upward(&si);
3109         //irg_block_walk_graph(chordal_env->irg, walker_pressure_annotator, NULL, &si);
3110         //dump_pressure_graph(&si, dump_suffix3);
3111
3112         be_analyze_regpressure(chordal_env, "-post");
3113
3114         free_dom(chordal_env->irg);
3115         del_pset(si.inverse_ops);
3116         del_pset(si.all_possible_remats);
3117         del_pset(si.spills);
3118 #ifndef EXECFREQ_LOOPDEPH
3119         free_execfreq(si.execfreqs);
3120 #endif
3121         free_lpp(si.lpp);
3122         obstack_free(&obst, NULL);
3123         DBG((si.dbg, LEVEL_1, "\tdone.\n"));
3124 }
3125
3126 #else                           /* WITH_ILP */
3127
3128 static void
3129 only_that_you_can_compile_without_WITH_ILP_defined(void)
3130 {
3131 }
3132
3133 #endif                          /* WITH_ILP */