replaced inline by __inline to allow to be compiled in gcc and msvc modes
[libfirm] / ir / be / bespillremat.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       ILP based spilling & rematerialization
23  * @author      Adam M. Szalkowski
24  * @date        06.04.2006
25  * @version     $Id$
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #ifdef WITH_ILP
32
33 #include <math.h>
34
35 #include "hashptr.h"
36 #include "debug.h"
37 #include "obst.h"
38 #include "set.h"
39 #include "list.h"
40 #include "pmap.h"
41
42 #include "irprintf.h"
43 #include "irgwalk.h"
44 #include "irdump_t.h"
45 #include "irnode_t.h"
46 #include "ircons_t.h"
47 #include "irloop_t.h"
48 #include "irnodeset.h"
49 #include "phiclass.h"
50 #include "iredges_t.h"
51 #include "execfreq.h"
52 #include "irvrfy.h"
53 #include "irbackedge_t.h"
54
55 #include <lpp/lpp.h>
56 #include <lpp/mps.h>
57 #include <lpp/lpp_net.h>
58 #include <lpp/lpp_cplex.h>
59
60 #include "be_t.h"
61 #include "beirg_t.h"
62 #include "belive_t.h"
63 #include "besched_t.h"
64 #include "bessaconstr.h"
65 #include "bearch_t.h"
66 #include "beintlive_t.h"
67 #include "beabi.h"
68 #include "benode_t.h"
69 #include "beutil.h"
70 #include "bespillremat.h"
71 #include "bespill.h"
72 #include "bepressurestat.h"
73 #include "beprofile.h"
74 #include "bespilloptions.h"
75 #include "bechordal_t.h"
76 #include "bemodule.h"
77
78 #include <libcore/lc_opts.h>
79 #include <libcore/lc_opts_enum.h>
80
81 #define DUMP_PROBLEM       1
82 #define DUMP_MPS           2
83 #define DUMP_SOLUTION      4
84 #define DUMP_STATS         8
85 #define DUMP_PRESSURE      16
86
87 #define KEEPALIVE_REMATS   1
88 #define KEEPALIVE_SPILLS   2
89 #define KEEPALIVE_RELOADS  4
90
91 #define VERIFY_MEMINTERF   1
92 #define VERIFY_DOMINANCE   2
93
94 #define REMATS_NONE        0
95 #define REMATS_BRIGGS      1
96 #define REMATS_NOINVERSE   2
97 #define REMATS_ALL         3
98
99 static unsigned opt_dump_flags = 0;
100 static int opt_log = 0;
101 static unsigned opt_keep_alive = 0;
102 static int opt_goodwin = 1;
103 static int opt_memcopies = 1;
104 static int opt_memoperands = 1;
105 static int opt_verify = VERIFY_MEMINTERF;
106 static unsigned opt_remats = REMATS_ALL;
107 static int opt_repair_schedule = 0;
108 static int opt_no_enlarge_liveness = 0;
109 static int opt_remat_while_live = 1;
110 static int opt_timeout = 300;
111 static double opt_cost_reload = 8.0;
112 static double opt_cost_memoperand =  7.0;
113 static double opt_cost_spill =  15.0;
114 static double opt_cost_remat =  1.0;
115
116
117 static const lc_opt_enum_mask_items_t dump_items[] = {
118         { "problem",  DUMP_PROBLEM  },
119         { "mps",      DUMP_MPS      },
120         { "solution", DUMP_SOLUTION },
121         { "stats",    DUMP_STATS },
122         { "pressure", DUMP_PRESSURE },
123         { NULL,       0 }
124 };
125
126 static lc_opt_enum_mask_var_t dump_var = {
127         &opt_dump_flags, dump_items
128 };
129
130 static const lc_opt_enum_mask_items_t keepalive_items[] = {
131         { "remats",  KEEPALIVE_REMATS  },
132         { "spills",  KEEPALIVE_SPILLS  },
133         { "reloads", KEEPALIVE_RELOADS },
134         { NULL,      0 }
135 };
136
137 static lc_opt_enum_mask_var_t keep_alive_var = {
138         &opt_keep_alive, keepalive_items
139 };
140
141 static const lc_opt_enum_mask_items_t remats_items[] = {
142         { "none",      REMATS_NONE      },
143         { "briggs",    REMATS_BRIGGS    },
144         { "noinverse", REMATS_NOINVERSE },
145         { "all",       REMATS_ALL       },
146         { NULL,        0 }
147 };
148
149 static lc_opt_enum_mask_var_t remats_var = {
150         &opt_remats, remats_items
151 };
152
153 static const lc_opt_table_entry_t options[] = {
154         LC_OPT_ENT_ENUM_MASK("keepalive", "keep alive inserted nodes",                              &keep_alive_var),
155
156         LC_OPT_ENT_BOOL     ("goodwin",  "activate goodwin reduction",                              &opt_goodwin),
157         LC_OPT_ENT_BOOL     ("memcopies",  "activate memcopy handling",                             &opt_memcopies),
158         LC_OPT_ENT_BOOL     ("memoperands",  "activate memoperands",                                &opt_memoperands),
159         LC_OPT_ENT_ENUM_INT ("remats",  "type of remats to insert",                                 &remats_var),
160         LC_OPT_ENT_BOOL     ("repair_schedule",  "repair the schedule by rematting once used nodes",&opt_repair_schedule),
161         LC_OPT_ENT_BOOL     ("no_enlage_liveness",  "do not enlarge liveness of operands of remats",&opt_no_enlarge_liveness),
162         LC_OPT_ENT_BOOL     ("remat_while_live",  "only remat where rematted value was live",       &opt_remat_while_live),
163
164         LC_OPT_ENT_ENUM_MASK("dump", "dump problem, solution or statistical data",                  &dump_var),
165         LC_OPT_ENT_BOOL     ("log",  "activate the lpp log",                                        &opt_log),
166         LC_OPT_ENT_INT      ("timeout",  "ILP solver timeout",                                      &opt_timeout),
167
168         LC_OPT_ENT_DBL      ("cost_reload",  "cost of a reload",                                    &opt_cost_reload),
169         LC_OPT_ENT_DBL      ("cost_memoperand",  "cost of a memory operand",                        &opt_cost_memoperand),
170         LC_OPT_ENT_DBL      ("cost_spill",  "cost of a spill instruction",                          &opt_cost_spill),
171         LC_OPT_ENT_DBL      ("cost_remat",  "cost of a rematerialization",                          &opt_cost_remat),
172         { NULL }
173 };
174
175 //#define EXECFREQ_LOOPDEPH   /* compute execution frequency from loop depth only */
176 //#define SCHEDULE_PHIM   /* insert phim nodes into schedule */
177
178 #define  SOLVE
179 //#define  SOLVE_LOCAL
180 #define LPP_SERVER "i44pc52"
181 #define LPP_SOLVER "cplex"
182
183
184 #define MAX_PATHS      INT_MAX
185 #define ILP_UNDEF               -1
186
187 typedef struct _spill_ilp_t {
188         const arch_register_class_t  *cls;
189         int                           n_regs;
190         be_irg_t                     *birg;
191         be_lv_t                      *lv;
192         lpp_t                        *lpp;
193         struct obstack               *obst;
194         set                          *remat_info;
195         pset                         *all_possible_remats;
196         pset                         *inverse_ops;
197         ir_node                      *keep;
198         set                          *values; /**< for collecting all definitions of values before running ssa-construction */
199         pset                         *spills;
200         set                          *interferences;
201         ir_node                      *m_unknown;
202         set                          *memoperands;
203         phi_classes_t                *pc;
204 #ifndef SCHEDULE_PHIM
205         pset                         *phims;
206 #endif
207         DEBUG_ONLY(firm_dbg_module_t * dbg);
208 } spill_ilp_t;
209
210 typedef int ilp_var_t;
211 typedef int ilp_cst_t;
212
213 typedef struct _spill_bb_t {
214         set      *ilp;
215         set      *reloads;
216 } spill_bb_t;
217
218 typedef struct _remat_t {
219         const ir_node        *op;      /**< for copy_irn */
220         const ir_node        *value;   /**< the value which is being recomputed by this remat */
221         const ir_node        *proj;    /**< not NULL if the above op produces a tuple */
222         int                   cost;    /**< cost of this remat */
223         int                   inverse; /**< nonzero if this is an inverse remat */
224 } remat_t;
225
226 /**
227  * Data to be attached to each IR node. For remats this contains the ilp_var
228  * for this remat and for normal ops this contains the ilp_vars for
229  * reloading each operand
230  */
231 typedef struct _op_t {
232         int             is_remat;
233         union {
234                 struct {
235                         ilp_var_t       ilp;
236                         const remat_t  *remat; /** the remat this op belongs to */
237                         int             pre; /** 1, if this is a pressure-increasing remat */
238                 } remat;
239                 struct {
240                         ilp_var_t       ilp;
241                         ir_node        *op; /** the operation this live range belongs to */
242                         union {
243                                 ilp_var_t      *reloads;
244                                 ilp_var_t      *copies;
245                         } args;
246                 } live_range;
247         } attr;
248 } op_t;
249
250 typedef struct _defs_t {
251         const ir_node   *value;
252         ir_node         *spills;  /**< points to the first spill for this value (linked by link field) */
253         ir_node         *remats;  /**< points to the first definition for this value (linked by link field) */
254 } defs_t;
255
256 typedef struct _remat_info_t {
257         const ir_node       *irn; /**< the irn to which these remats belong */
258         pset                *remats; /**< possible remats for this value */
259         pset                *remats_by_operand; /**< remats with this value as operand */
260 } remat_info_t;
261
262 typedef struct _keyval_t {
263         const void          *key;
264         const void          *val;
265 } keyval_t;
266
267 typedef struct _spill_t {
268         ir_node            *irn;
269         ilp_var_t           reg_in;
270         ilp_var_t           mem_in;
271         ilp_var_t           reg_out;
272         ilp_var_t           mem_out;
273         ilp_var_t           spill;
274 } spill_t;
275
276 typedef struct _memoperand_t {
277         ir_node             *irn; /**< the irn */
278         unsigned int         pos; /**< the position of the argument */
279         ilp_var_t            ilp; /**< the ilp var for this memory operand */
280 } memoperand_t;
281
282 static INLINE int
283 has_reg_class(const spill_ilp_t * si, const ir_node * irn)
284 {
285         return arch_irn_consider_in_reg_alloc(si->birg->main_env->arch_env,
286                                               si->cls, irn);
287 }
288
289 #if 0
290 static int
291 cmp_remat(const void *a, const void *b)
292 {
293         const keyval_t *p = a;
294         const keyval_t *q = b;
295         const remat_t  *r = p->val;
296         const remat_t  *s = q->val;
297
298         assert(r && s);
299
300         return !(r == s || r->op == s->op);
301 }
302 #endif
303 static int
304 cmp_remat(const void *a, const void *b)
305 {
306         const remat_t  *r = a;
307         const remat_t  *s = a;
308
309         return !(r == s || r->op == s->op);
310 }
311
312 static int
313 cmp_spill(const void *a, const void *b, size_t size)
314 {
315         const spill_t *p = a;
316         const spill_t *q = b;
317
318 //      return !(p->irn == q->irn && p->bb == q->bb);
319         return !(p->irn == q->irn);
320 }
321
322 static int
323 cmp_memoperands(const void *a, const void *b, size_t size)
324 {
325         const memoperand_t *p = a;
326         const memoperand_t *q = b;
327
328         return !(p->irn == q->irn && p->pos == q->pos);
329 }
330
331 static keyval_t *
332 set_find_keyval(set * set, const void * key)
333 {
334         keyval_t     query;
335
336         query.key = key;
337         return set_find(set, &query, sizeof(query), HASH_PTR(key));
338 }
339
340 static keyval_t *
341 set_insert_keyval(set * set, void * key, void * val)
342 {
343         keyval_t     query;
344
345         query.key = key;
346         query.val = val;
347         return set_insert(set, &query, sizeof(query), HASH_PTR(key));
348 }
349
350 static defs_t *
351 set_find_def(set * set, const ir_node * value)
352 {
353         defs_t     query;
354
355         query.value = value;
356         return set_find(set, &query, sizeof(query), HASH_PTR(value));
357 }
358
359 static defs_t *
360 set_insert_def(set * set, const ir_node * value)
361 {
362         defs_t     query;
363
364         query.value = value;
365         query.spills = NULL;
366         query.remats = NULL;
367         return set_insert(set, &query, sizeof(query), HASH_PTR(value));
368 }
369
370 static memoperand_t *
371 set_insert_memoperand(set * set, ir_node * irn, unsigned int pos, ilp_var_t ilp)
372 {
373         memoperand_t     query;
374
375         query.irn = irn;
376         query.pos = pos;
377         query.ilp = ilp;
378         return set_insert(set, &query, sizeof(query), HASH_PTR(irn)+pos);
379 }
380
381 static memoperand_t *
382 set_find_memoperand(set * set, const ir_node * irn, unsigned int pos)
383 {
384         memoperand_t     query;
385
386         query.irn = (ir_node*)irn;
387         query.pos = pos;
388         return set_find(set, &query, sizeof(query), HASH_PTR(irn)+pos);
389 }
390
391
392 static spill_t *
393 set_find_spill(set * set, const ir_node * value)
394 {
395         spill_t     query;
396
397         query.irn = (ir_node*)value;
398         return set_find(set, &query, sizeof(query), HASH_PTR(value));
399 }
400
401 #define pset_foreach(s,i) for((i)=pset_first((s)); (i); (i)=pset_next((s)))
402 #define set_foreach(s,i) for((i)=set_first((s)); (i); (i)=set_next((s)))
403 #define foreach_post_remat(s,i) for((i)=next_post_remat((s)); (i); (i)=next_post_remat((i)))
404 #define foreach_pre_remat(si,s,i) for((i)=next_pre_remat((si),(s)); (i); (i)=next_pre_remat((si),(i)))
405 #define sched_foreach_op(s,i) for((i)=sched_next_op((s));!sched_is_end((i));(i)=sched_next_op((i)))
406
407 static int
408 cmp_remat_info(const void *a, const void *b, size_t size)
409 {
410         const remat_info_t *p = a;
411         const remat_info_t *q = b;
412
413         return !(p->irn == q->irn);
414 }
415
416 static int
417 cmp_defs(const void *a, const void *b, size_t size)
418 {
419         const defs_t *p = a;
420         const defs_t *q = b;
421
422         return !(p->value == q->value);
423 }
424
425 static int
426 cmp_keyval(const void *a, const void *b, size_t size)
427 {
428         const keyval_t *p = a;
429         const keyval_t *q = b;
430
431         return !(p->key == q->key);
432 }
433
434 static double
435 execution_frequency(const spill_ilp_t *si, const ir_node * irn)
436 {
437 #define FUDGE 0.001
438         if(be_profile_has_data())
439                 return ((double)be_profile_get_block_execcount(get_block(irn))) + FUDGE;
440
441 #ifndef EXECFREQ_LOOPDEPH
442         return get_block_execfreq(si->birg->exec_freq, get_block(irn)) + FUDGE;
443 #else
444         if(is_Block(irn))
445                 return exp(get_loop_depth(get_irn_loop(irn)) * log(10)) + FUDGE;
446         else
447                 return exp(get_loop_depth(get_irn_loop(get_nodes_block(irn))) * log(10)) + FUDGE;
448 #endif
449 }
450
451 static double
452 get_cost(const spill_ilp_t * si, const ir_node * irn)
453 {
454         if(be_is_Spill(irn)) {
455                 return opt_cost_spill;
456         } else if(be_is_Reload(irn)){
457                 return opt_cost_reload;
458         } else {
459                 return arch_get_op_estimated_cost(si->birg->main_env->arch_env, irn);
460         }
461 }
462
463 /**
464  * Checks, whether node and its operands have suitable reg classes
465  */
466 static INLINE int
467 is_rematerializable(const spill_ilp_t * si, const ir_node * irn)
468 {
469         int               n;
470         const arch_env_t *arch_env = si->birg->main_env->arch_env;
471         int               remat = (arch_irn_get_flags(arch_env, irn) & arch_irn_flags_rematerializable) != 0;
472
473 #if 0
474         if(!remat)
475                 ir_fprintf(stderr, "  Node %+F is not rematerializable\n", irn);
476 #endif
477
478         for (n = get_irn_arity(irn)-1; n>=0 && remat; --n) {
479                 ir_node        *op = get_irn_n(irn, n);
480                 remat &= has_reg_class(si, op) || arch_irn_get_flags(arch_env, op) & arch_irn_flags_ignore || (get_irn_op(op) == op_NoMem);
481
482 //              if(!remat)
483 //                      ir_fprintf(stderr, "  Argument %d (%+F) of Node %+F has wrong regclass\n", i, op, irn);
484         }
485
486         return remat;
487 }
488
489 /**
490  * Try to create a remat from @p op with destination value @p dest_value
491  */
492 static INLINE remat_t *
493 get_remat_from_op(spill_ilp_t * si, const ir_node * dest_value, const ir_node * op)
494 {
495         remat_t  *remat = NULL;
496
497 //      if(!mode_is_datab(get_irn_mode(dest_value)))
498 //              return NULL;
499
500         if(dest_value == op) {
501                 const ir_node *proj = NULL;
502
503                 if(is_Proj(dest_value)) {
504                         op = get_Proj_pred(op);
505                         proj = dest_value;
506                 }
507
508                 if(!is_rematerializable(si, op))
509                         return NULL;
510
511                 remat          = obstack_alloc(si->obst, sizeof(*remat));
512                 remat->op      = op;
513                 remat->cost    = (int)get_cost(si, op);
514                 remat->value   = dest_value;
515                 remat->proj    = proj;
516                 remat->inverse = 0;
517         } else {
518                 arch_inverse_t     inverse;
519                 int                n;
520
521                 /* get the index of the operand we want to retrieve by the inverse op */
522                 for (n = get_irn_arity(op)-1; n>=0; --n) {
523                         ir_node        *arg = get_irn_n(op, n);
524
525                         if(arg == dest_value) break;
526                 }
527                 if(n<0) return NULL;
528
529                 DBG((si->dbg, LEVEL_5, "\t  requesting inverse op for argument %d of op %+F\n", n, op));
530
531                 /* else ask the backend to give an inverse op */
532                 if(arch_get_inverse(si->birg->main_env->arch_env, op, n, &inverse, si->obst)) {
533                         int   i;
534
535                         DBG((si->dbg, LEVEL_4, "\t  backend gave us an inverse op with %d nodes and cost %d\n", inverse.n, inverse.costs));
536
537                         assert(inverse.n > 0 && "inverse op should have at least one node");
538
539                         for(i=inverse.n-1; i>=0; --i) {
540                                 pset_insert_ptr(si->inverse_ops, inverse.nodes[i]);
541                         }
542
543                         if(inverse.n <= 2) {
544                                 remat = obstack_alloc(si->obst, sizeof(*remat));
545                                 remat->op = inverse.nodes[0];
546                                 remat->cost = inverse.costs;
547                                 remat->value = dest_value;
548                                 remat->proj = (inverse.n==2)?inverse.nodes[1]:NULL;
549                                 remat->inverse = 1;
550
551                                 // Matze: commented this out, this doesn't seem to be true if
552                                 // the inverse is a simple operation with only 1 result...
553                                 //assert(is_Proj(remat->proj));
554                         } else {
555                                 assert(0 && "I can not handle remats with more than 2 nodes");
556                         }
557                 }
558         }
559
560         if(remat) {
561                 if(remat->proj) {
562                         DBG((si->dbg, LEVEL_3, "\t >Found remat %+F for %+F from %+F with %+F\n", remat->op, dest_value, op, remat->proj));
563                 } else {
564                         DBG((si->dbg, LEVEL_3, "\t >Found remat %+F for %+F from %+F\n", remat->op, dest_value, op));
565                 }
566         }
567         return remat;
568 }
569
570
571 static INLINE void
572 add_remat(const spill_ilp_t * si, const remat_t * remat)
573 {
574         remat_info_t    *remat_info,
575                      query;
576         int              n;
577
578         assert(remat->op);
579         assert(remat->value);
580
581         query.irn = remat->value;
582         query.remats = NULL;
583         query.remats_by_operand = NULL;
584         remat_info = set_insert(si->remat_info, &query, sizeof(query), HASH_PTR(remat->value));
585
586         if(remat_info->remats == NULL) {
587                 remat_info->remats = new_pset(cmp_remat, 4096);
588         }
589         pset_insert(remat_info->remats, remat, HASH_PTR(remat->op));
590
591         /* insert the remat into the remats_be_operand set of each argument of the remat op */
592         for (n = get_irn_arity(remat->op)-1; n>=0; --n) {
593                 ir_node        *arg = get_irn_n(remat->op, n);
594
595                 query.irn = arg;
596                 query.remats = NULL;
597                 query.remats_by_operand = NULL;
598                 remat_info = set_insert(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
599
600                 if(remat_info->remats_by_operand == NULL) {
601                         remat_info->remats_by_operand = new_pset(cmp_remat, 4096);
602                 }
603                 pset_insert(remat_info->remats_by_operand, remat, HASH_PTR(remat->op));
604         }
605 }
606
607 static int
608 get_irn_n_nonremat_edges(const spill_ilp_t * si, const ir_node * irn)
609 {
610         const ir_edge_t   *edge = get_irn_out_edge_first(irn);
611         int                i = 0;
612
613         while(edge) {
614                 if(!pset_find_ptr(si->inverse_ops, edge->src)) {
615                         ++i;
616                 }
617                 edge = get_irn_out_edge_next(irn, edge);
618         }
619
620         return i;
621 }
622
623 static int
624 get_irn_n_nonignore_args(const spill_ilp_t * si, const ir_node * irn)
625 {
626         int n;
627         int ret = 0;
628
629         if(is_Proj(irn))
630                 irn = get_Proj_pred(irn);
631
632         for(n=get_irn_arity(irn)-1; n>=0; --n) {
633                 const ir_node  *arg = get_irn_n(irn, n);
634
635                 if(has_reg_class(si, arg)) ++ret;
636         }
637
638         return ret;
639 }
640
641 static INLINE void
642 get_remats_from_op(spill_ilp_t * si, const ir_node * op)
643 {
644         int      n;
645         remat_t *remat;
646
647         if( has_reg_class(si, op)
648         && (opt_repair_schedule || get_irn_n_nonremat_edges(si, op) > 1)
649         && (opt_remats !=  REMATS_BRIGGS || get_irn_n_nonignore_args(si, op) == 0)
650         ) {
651                 remat = get_remat_from_op(si, op, op);
652                 if(remat) {
653                         add_remat(si, remat);
654                 }
655         }
656
657         if(opt_remats == REMATS_ALL) {
658                 /* repeat the whole stuff for each remat retrieved by get_remat_from_op(op, arg)
659                    for each arg */
660                 for (n = get_irn_arity(op)-1; n>=0; --n) {
661                         ir_node        *arg = get_irn_n(op, n);
662
663                         if(has_reg_class(si, arg)) {
664                                 /* try to get an inverse remat */
665                                 remat = get_remat_from_op(si, arg, op);
666                                 if(remat) {
667                                         add_remat(si, remat);
668                                 }
669                         }
670                 }
671         }
672 }
673
674 static INLINE int
675 value_is_defined_before(const spill_ilp_t * si, const ir_node * pos, const ir_node * val)
676 {
677         ir_node *block;
678         ir_node *def_block = get_nodes_block(val);
679         int      ret;
680
681         if(val == pos)
682                 return 0;
683
684         /* if pos is at end of a basic block */
685         if(is_Block(pos)) {
686                 ret = (pos == def_block || block_dominates(def_block, pos));
687 //              ir_fprintf(stderr, "(def(bb)=%d) ", ret);
688                 return ret;
689         }
690
691         /* else if this is a normal operation */
692         block = get_nodes_block(pos);
693         if(block == def_block) {
694                 if(!sched_is_scheduled(val)) return 1;
695
696                 ret = sched_comes_after(val, pos);
697 //              ir_fprintf(stderr, "(def(same block)=%d) ",ret);
698                 return ret;
699         }
700
701         ret = block_dominates(def_block, block);
702 //      ir_fprintf(stderr, "(def(other block)=%d) ", ret);
703         return ret;
704 }
705
706 static INLINE ir_node *
707 sched_block_last_noncf(const spill_ilp_t * si, const ir_node * bb)
708 {
709     return sched_skip((ir_node*)bb, 0, sched_skip_cf_predicator, (void *) si->birg->main_env->arch_env);
710 }
711
712 /**
713  * Returns first non-Phi node of block @p bb
714  */
715 static INLINE ir_node *
716 sched_block_first_nonphi(const ir_node * bb)
717 {
718         return sched_skip((ir_node*)bb, 1, sched_skip_phi_predicator, NULL);
719 }
720
721 static int
722 sched_skip_proj_predicator(const ir_node * irn, void * data)
723 {
724         return (is_Proj(irn));
725 }
726
727 static INLINE ir_node *
728 sched_next_nonproj(const ir_node * irn, int forward)
729 {
730         return sched_skip((ir_node*)irn, forward, sched_skip_proj_predicator, NULL);
731 }
732
733 /**
734  * Returns next operation node (non-Proj) after @p irn
735  * or the basic block of this node
736  */
737 static INLINE ir_node *
738 sched_next_op(const ir_node * irn)
739 {
740         ir_node *next = sched_next(irn);
741
742         if(is_Block(next))
743                 return next;
744
745         return sched_next_nonproj(next, 1);
746 }
747
748 /**
749  * Returns previous operation node (non-Proj) before @p irn
750  * or the basic block of this node
751  */
752 static INLINE ir_node *
753 sched_prev_op(const ir_node * irn)
754 {
755         ir_node *prev = sched_prev(irn);
756
757         if(is_Block(prev))
758                 return prev;
759
760         return sched_next_nonproj(prev, 0);
761 }
762
763 static void
764 sched_put_after(ir_node * insert, ir_node * irn)
765 {
766         if(is_Block(insert)) {
767                 insert = sched_block_first_nonphi(insert);
768         } else {
769                 insert = sched_next_op(insert);
770         }
771         sched_reset(irn);
772         sched_add_before(insert, irn);
773 }
774
775 static void
776 sched_put_before(const spill_ilp_t * si, ir_node * insert, ir_node * irn)
777 {
778   if(is_Block(insert)) {
779           insert = sched_block_last_noncf(si, insert);
780   } else {
781           insert = sched_next_nonproj(insert, 0);
782           insert = sched_prev(insert);
783   }
784   sched_reset(irn);
785   sched_add_after(insert, irn);
786 }
787
788 static ir_node *
789 next_post_remat(const ir_node * irn)
790 {
791         op_t      *op;
792     ir_node   *next;
793
794         if(is_Block(irn)) {
795                 next = sched_block_first_nonphi(irn);
796         } else {
797                 next = sched_next_op(irn);
798         }
799
800         if(sched_is_end(next))
801                 return NULL;
802
803         op = get_irn_link(next);
804         if(op->is_remat && !op->attr.remat.pre) {
805                 return next;
806         }
807
808         return NULL;
809 }
810
811
812 static ir_node *
813 next_pre_remat(const spill_ilp_t * si, const ir_node * irn)
814 {
815         op_t      *op;
816         ir_node   *ret;
817
818         if(is_Block(irn)) {
819                 ret = sched_block_last_noncf(si, irn);
820                 ret = sched_next(ret);
821                 ret = sched_prev_op(ret);
822         } else {
823                 ret = sched_prev_op(irn);
824         }
825
826         if(sched_is_end(ret) || is_Phi(ret))
827                 return NULL;
828
829         op = (op_t*)get_irn_link(ret);
830         if(op->is_remat && op->attr.remat.pre) {
831                 return ret;
832         }
833
834         return NULL;
835 }
836
837 /**
838  * Tells you whether a @p remat can be placed before the irn @p pos
839  */
840 static INLINE int
841 can_remat_before(const spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
842 {
843         const ir_node   *op = remat->op;
844         const ir_node   *prev;
845         int        n,
846                            res = 1;
847
848         if(is_Block(pos)) {
849                 prev = sched_block_last_noncf(si, pos);
850                 prev = sched_next_nonproj(prev, 0);
851         } else {
852                 prev = sched_prev_op(pos);
853         }
854         /* do not remat if the rematted value is defined immediately before this op */
855         if(prev == remat->op) {
856                 return 0;
857         }
858
859 #if 0
860         /* this should be just fine, the following OP will be using this value, right? */
861
862         /* only remat AFTER the real definition of a value (?) */
863         if(!value_is_defined_before(si, pos, remat->value)) {
864 //              ir_fprintf(stderr, "error(not defined)");
865                 return 0;
866         }
867 #endif
868
869         for(n=get_irn_arity(op)-1; n>=0 && res; --n) {
870                 const ir_node   *arg = get_irn_n(op, n);
871
872                 if(opt_no_enlarge_liveness) {
873                         if(has_reg_class(si, arg) && live) {
874                                 res &= pset_find_ptr((pset*)live, arg)?1:0;
875                         } else {
876                                 res &= value_is_defined_before(si, pos, arg);
877                         }
878                 } else {
879                         res &= value_is_defined_before(si, pos, arg);
880                 }
881         }
882
883         return res;
884 }
885
886 /**
887  * Tells you whether a @p remat can be placed after the irn @p pos
888  */
889 static INLINE int
890 can_remat_after(const spill_ilp_t * si, const remat_t * remat, const ir_node * pos, const pset * live)
891 {
892         if(is_Block(pos)) {
893                 pos = sched_block_first_nonphi(pos);
894         } else {
895                 pos = sched_next_op(pos);
896         }
897
898         /* only remat AFTER the real definition of a value (?) */
899         if(!value_is_defined_before(si, pos, remat->value)) {
900                 return 0;
901         }
902
903         return can_remat_before(si, remat, pos, live);
904 }
905
906 /**
907  * Collect potetially rematerializable OPs
908  */
909 static void
910 walker_remat_collector(ir_node * irn, void * data)
911 {
912         spill_ilp_t    *si = data;
913
914         if(!is_Block(irn) && !is_Phi(irn)) {
915                 DBG((si->dbg, LEVEL_4, "\t  Processing %+F\n", irn));
916                 get_remats_from_op(si, irn);
917         }
918 }
919
920 /**
921  * Inserts a copy of @p irn before @p pos
922  */
923 static ir_node *
924 insert_copy_before(const spill_ilp_t * si, const ir_node * irn, ir_node * pos)
925 {
926         ir_node     *bb;
927         ir_node     *copy;
928
929         bb = is_Block(pos)?pos:get_nodes_block(pos);
930         copy = exact_copy(irn);
931
932         set_phi_class(si->pc, copy, NULL);
933         set_nodes_block(copy, bb);
934         sched_put_before(si, pos, copy);
935
936         return copy;
937 }
938
939 /**
940  * Inserts a copy of @p irn after @p pos
941  */
942 static ir_node *
943 insert_copy_after(const spill_ilp_t * si, const ir_node * irn, ir_node * pos)
944 {
945         ir_node     *bb;
946         ir_node     *copy;
947
948         bb = is_Block(pos)?pos:get_nodes_block(pos);
949         copy = exact_copy(irn);
950
951         set_phi_class(si->pc, copy, NULL);
952         set_nodes_block(copy, bb);
953         sched_put_after(pos, copy);
954
955         return copy;
956 }
957
958 static ir_node *
959 insert_remat_after(spill_ilp_t * si, const remat_t * remat, ir_node * pos, const pset * live)
960 {
961         char     buf[256];
962
963         if(can_remat_after(si, remat, pos, live)) {
964                 ir_node         *copy,
965                                                 *proj_copy;
966                 op_t            *op;
967
968                 DBG((si->dbg, LEVEL_3, "\t  >inserting remat2 %+F\n", remat->op));
969
970                 copy = insert_copy_after(si, remat->op, pos);
971
972                 ir_snprintf(buf, sizeof(buf), "remat2_%N_%N", copy, pos);
973                 op = obstack_alloc(si->obst, sizeof(*op));
974                 op->is_remat = 1;
975                 op->attr.remat.remat = remat;
976                 op->attr.remat.pre = 0;
977                 op->attr.remat.ilp = lpp_add_var_default(si->lpp, buf, lpp_binary, remat->cost*execution_frequency(si, pos), 0.0);
978
979                 set_irn_link(copy, op);
980                 pset_insert_ptr(si->all_possible_remats, copy);
981                 if(remat->proj) {
982                         proj_copy = insert_copy_after(si, remat->proj, copy);
983                         set_irn_n(proj_copy, 0, copy);
984                         set_irn_link(proj_copy, op);
985                         pset_insert_ptr(si->all_possible_remats, proj_copy);
986                 } else {
987                         proj_copy = NULL;
988                 }
989
990                 return copy;
991         }
992
993         return NULL;
994 }
995
996 static ir_node *
997 insert_remat_before(spill_ilp_t * si, const remat_t * remat, ir_node * pos, const pset * live)
998 {
999         char     buf[256];
1000
1001         if(can_remat_before(si, remat, pos, live)) {
1002                 ir_node         *copy,
1003                                                 *proj_copy;
1004                 op_t            *op;
1005
1006                 DBG((si->dbg, LEVEL_3, "\t  >inserting remat %+F\n", remat->op));
1007
1008                 copy = insert_copy_before(si, remat->op, pos);
1009
1010                 ir_snprintf(buf, sizeof(buf), "remat_%N_%N", copy, pos);
1011                 op = obstack_alloc(si->obst, sizeof(*op));
1012                 op->is_remat = 1;
1013                 op->attr.remat.remat = remat;
1014                 op->attr.remat.pre = 1;
1015                 op->attr.remat.ilp = lpp_add_var_default(si->lpp, buf, lpp_binary, remat->cost*execution_frequency(si, pos), 0.0);
1016
1017                 set_irn_link(copy, op);
1018                 pset_insert_ptr(si->all_possible_remats, copy);
1019                 if(remat->proj) {
1020                         proj_copy = insert_copy_after(si, remat->proj, copy);
1021                         set_irn_n(proj_copy, 0, copy);
1022                         set_irn_link(proj_copy, op);
1023                         pset_insert_ptr(si->all_possible_remats, proj_copy);
1024                 } else {
1025                         proj_copy = NULL;
1026                 }
1027
1028                 return copy;
1029         }
1030
1031         return NULL;
1032 }
1033
1034 static int
1035 get_block_n_succs(const ir_node *block) {
1036         const ir_edge_t *edge;
1037
1038         assert(edges_activated(current_ir_graph));
1039
1040         edge = get_block_succ_first(block);
1041         if (! edge)
1042                 return 0;
1043
1044         edge = get_block_succ_next(block, edge);
1045         return edge ? 2 : 1;
1046 }
1047
1048 static int
1049 is_start_block(const ir_node * bb)
1050 {
1051         return get_irg_start_block(get_irn_irg(bb)) == bb;
1052 }
1053
1054 static int
1055 is_merge_edge(const ir_node * bb)
1056 {
1057         if(is_start_block(bb))
1058                 return 0;
1059
1060         if(opt_goodwin)
1061                 return get_block_n_succs(bb) == 1;
1062         else
1063                 return 1;
1064 }
1065
1066 static int
1067 is_diverge_edge(const ir_node * bb)
1068 {
1069         if(is_start_block(bb))
1070                 return 0;
1071
1072         if(opt_goodwin)
1073                 return get_Block_n_cfgpreds(bb) == 1;
1074         else
1075                 return 1;
1076 }
1077
1078 static void
1079 get_live_end(spill_ilp_t * si, ir_node * bb, pset * live)
1080 {
1081         ir_node        *irn;
1082         int i;
1083
1084         be_lv_foreach(si->lv, bb, be_lv_state_end, i) {
1085                 irn = be_lv_get_irn(si->lv, bb, i);
1086
1087                 if (has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1088                         pset_insert_ptr(live, irn);
1089                 }
1090         }
1091
1092         irn = sched_last(bb);
1093
1094         /* all values eaten by control flow operations are also live until the end of the block */
1095         sched_foreach_reverse(bb, irn) {
1096                 int  i;
1097
1098                 if(!sched_skip_cf_predicator(irn, si->birg->main_env->arch_env)) break;
1099
1100                 for(i=get_irn_arity(irn)-1; i>=0; --i) {
1101                         ir_node *arg = get_irn_n(irn,i);
1102
1103                         if(has_reg_class(si, arg)) {
1104                                 pset_insert_ptr(live, arg);
1105                         }
1106                 }
1107         }
1108         /*
1109          * find values that are used by remats at end of block
1110          * and insert them into live set
1111          */
1112         foreach_pre_remat(si, bb, irn) {
1113                 int       n;
1114
1115                 for (n=get_irn_arity(irn)-1; n>=0; --n) {
1116                         ir_node        *remat_arg = get_irn_n(irn, n);
1117
1118                         if(!has_reg_class(si, remat_arg)) continue;
1119
1120                         /* if value is becoming live through use by remat */
1121                         if(!pset_find_ptr(live, remat_arg)) {
1122                                 DBG((si->dbg, LEVEL_4, "  value %+F becoming live through use by remat at end of block %+F\n", remat_arg, irn));
1123
1124                                 pset_insert_ptr(live, remat_arg);
1125                         }
1126                 }
1127         }
1128 }
1129
1130 static void
1131 walker_regclass_copy_insertor(ir_node * irn, void * data)
1132 {
1133         spill_ilp_t    *si = data;
1134
1135         if(is_Phi(irn) && has_reg_class(si, irn)) {
1136                 int n;
1137
1138                 for(n=get_irn_arity(irn)-1; n>=0; --n) {
1139                         ir_node  *phi_arg = get_irn_n(irn, n);
1140                         ir_node  *bb = get_Block_cfgpred_block(get_nodes_block(irn), n);
1141
1142                         if(!has_reg_class(si, phi_arg)) {
1143                                 ir_node   *copy = be_new_Copy(si->cls, si->birg->irg, bb, phi_arg);
1144                                 ir_node   *pos = sched_block_last_noncf(si, bb);
1145                                 op_t      *op = obstack_alloc(si->obst, sizeof(*op));
1146
1147                                 DBG((si->dbg, LEVEL_2, "\t copy to my regclass for arg %+F of %+F\n", phi_arg, irn));
1148                                 sched_add_after(pos, copy);
1149                                 set_irn_n(irn, n, copy);
1150
1151                                 op->is_remat = 0;
1152                                 op->attr.live_range.args.reloads = NULL;
1153                                 op->attr.live_range.ilp = ILP_UNDEF;
1154                                 set_irn_link(copy, op);
1155                         }
1156                 }
1157         }
1158 }
1159
1160 /**
1161  * Insert (so far unused) remats into the irg to
1162  * recompute the potential liveness of all values
1163  */
1164 static void
1165 walker_remat_insertor(ir_node * bb, void * data)
1166 {
1167         spill_ilp_t    *si = data;
1168         ir_node        *irn;
1169         int             n, i;
1170         pset           *live;
1171         pset           *post_remats;
1172         remat_t        *remat;
1173
1174         /* skip start block, no remats to do there */
1175         if(is_start_block(bb)) return;
1176
1177         DBG((si->dbg, LEVEL_3, "\t Entering %+F\n\n", bb));
1178
1179         live = pset_new_ptr_default();
1180         be_lv_foreach(si->lv, bb, be_lv_state_end, i) {
1181                 ir_node        *value = be_lv_get_irn(si->lv, bb, i);
1182
1183                 /* add remats at end of block */
1184                 if (has_reg_class(si, value)) {
1185                         pset_insert_ptr(live, value);
1186                 }
1187         }
1188
1189         irn = sched_last(bb);
1190         while(!sched_is_end(irn)) {
1191                 ir_node   *next;
1192                 pset      *args;
1193                 ir_node   *arg;
1194                 pset      *used;
1195
1196                 next = sched_prev(irn);
1197
1198                 /* delete defined value from live set */
1199                 if(has_reg_class(si, irn)) {
1200                         pset_remove_ptr(live, irn);
1201                 }
1202
1203                 if(is_Phi(irn) || is_Proj(irn)) {
1204                         irn = next;
1205                         continue;
1206                 }
1207
1208                 args = pset_new_ptr_default();
1209                 used = pset_new_ptr_default();
1210
1211                 /* collect arguments of op and set args of op already live in epilog */
1212                 for (n = get_irn_arity(irn)-1; n>=0; --n) {
1213                         ir_node        *arg = get_irn_n(irn, n);
1214
1215                         pset_insert_ptr(args, arg);
1216                         if(has_reg_class(si, arg)) {
1217                                 pset_insert_ptr(live, arg);
1218                                 pset_insert_ptr(used, arg);
1219                         }
1220                 }
1221
1222                 /* insert all possible remats before irn */
1223                 pset_foreach(args, arg) {
1224                         remat_info_t   *remat_info,
1225                                                     query;
1226
1227                         /* continue if the operand has the wrong reg class */
1228                         if(!has_reg_class(si, arg))
1229                                 continue;
1230
1231                         query.irn = arg;
1232                         query.remats = NULL;
1233                         query.remats_by_operand = NULL;
1234                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
1235
1236                         if(!remat_info) {
1237                                 continue;
1238                         }
1239
1240                         if(remat_info->remats) {
1241                                 pset_foreach(remat_info->remats, remat) {
1242                                         ir_node  *remat_irn = NULL;
1243
1244                                         DBG((si->dbg, LEVEL_4, "\t  considering remat %+F for arg %+F\n", remat->op, arg));
1245                                         remat_irn = insert_remat_before(si, remat, irn, live);
1246
1247                                         if(remat_irn) {
1248                                                 for(n=get_irn_arity(remat_irn)-1; n>=0; --n) {
1249                                                         ir_node  *remat_arg = get_irn_n(remat_irn, n);
1250
1251                                                         /* collect args of remats which are not args of op */
1252                                                         if(has_reg_class(si, remat_arg) && !pset_find_ptr(args, remat_arg)) {
1253                                                                 pset_insert_ptr(used, remat_arg);
1254                                                         }
1255                                                 }
1256                                         }
1257                                 }
1258                         }
1259                 }
1260
1261                 /* do not place post remats after jumps */
1262                 if(sched_skip_cf_predicator(irn, si->birg->main_env->arch_env)) {
1263                         del_pset(used);
1264                         del_pset(args);
1265                         break;
1266                 }
1267
1268                 /* insert all possible remats after irn */
1269                 post_remats = pset_new_ptr_default();
1270                 pset_foreach(used, arg) {
1271                         remat_info_t   *remat_info,
1272                                                     query;
1273
1274                         /* continue if the operand has the wrong reg class */
1275                         if(!has_reg_class(si, arg))
1276                                 continue;
1277
1278                         query.irn = arg;
1279                         query.remats = NULL;
1280                         query.remats_by_operand = NULL;
1281                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(arg));
1282
1283                         if(!remat_info) {
1284                                 continue;
1285                         }
1286
1287                         if(remat_info->remats_by_operand) {
1288                                 pset_foreach(remat_info->remats_by_operand, remat) {
1289                                         /* do not insert remats producing the same value as one of the operands */
1290                                         if(!pset_find_ptr(args, remat->value)) {
1291                                                 DBG((si->dbg, LEVEL_4, "\t  considering remat %+F with arg %+F\n", remat->op, arg));
1292
1293                                                 /* only remat values that can be used by real ops */
1294                                                 if(!opt_remat_while_live || pset_find_ptr(live, remat->value)) {
1295                                                         pset_insert_ptr(post_remats, remat);
1296                                                 }
1297                                         }
1298                                 }
1299                         }
1300                 }
1301                 pset_foreach(post_remats, remat) {
1302                         insert_remat_after(si, remat, irn, live);
1303                 }
1304                 del_pset(post_remats);
1305
1306                 del_pset(used);
1307                 del_pset(args);
1308                 irn = next;
1309         }
1310
1311         /* add remats at end if successor has multiple predecessors */
1312         if(is_merge_edge(bb)) {
1313                 pset     *live_out = pset_new_ptr_default();
1314                 ir_node  *value;
1315
1316                 get_live_end(si, bb, live_out);
1317
1318                 /* add remats at end of block */
1319                 pset_foreach(live_out, value) {
1320                         remat_info_t   *remat_info,
1321                                                    query;
1322
1323                         query.irn = value;
1324                         query.remats = NULL;
1325                         query.remats_by_operand = NULL;
1326                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(value));
1327
1328                         if(remat_info && remat_info->remats) {
1329                                 pset_foreach(remat_info->remats, remat) {
1330                                         DBG((si->dbg, LEVEL_4, "\t  considering remat %+F at end of block %+F\n", remat->op, bb));
1331
1332                                         insert_remat_before(si, remat, bb, live_out);
1333                                 }
1334                         }
1335                 }
1336                 del_pset(live_out);
1337         }
1338
1339         if(is_diverge_edge(bb)) {
1340                 pset     *live_in = pset_new_ptr_default();
1341                 ir_node  *value;
1342
1343                 be_lv_foreach(si->lv, bb, be_lv_state_in, i) {
1344                         value = be_lv_get_irn(si->lv, bb, i);
1345
1346                         if(has_reg_class(si, value)) {
1347                                 pset_insert_ptr(live_in, value);
1348                         }
1349                 }
1350                 /* add phis to live_in */
1351                 sched_foreach(bb, value) {
1352                         if(!is_Phi(value)) break;
1353
1354                         if(has_reg_class(si, value)) {
1355                                 pset_insert_ptr(live_in, value);
1356                         }
1357                 }
1358
1359                 /* add remat2s at beginning of block */
1360                 post_remats = pset_new_ptr_default();
1361                 pset_foreach(live_in, value) {
1362                         remat_info_t   *remat_info,
1363                                                    query;
1364
1365                         query.irn = value;
1366                         query.remats = NULL;
1367                         query.remats_by_operand = NULL;
1368                         remat_info = set_find(si->remat_info, &query, sizeof(query), HASH_PTR(value));
1369
1370                         if(remat_info && remat_info->remats_by_operand) {
1371                                 pset_foreach(remat_info->remats_by_operand, remat) {
1372                                         DBG((si->dbg, LEVEL_4, "\t  considering remat2 %+F at beginning of block %+F\n", remat->op, bb));
1373
1374                                         /* put the remat here if all its args are available and result is still live */
1375                                         if(!opt_remat_while_live || pset_find_ptr(live_in, remat->value)) {
1376                                                 pset_insert_ptr(post_remats, remat);
1377                                         }
1378                                 }
1379                         }
1380                 }
1381                 pset_foreach(post_remats, remat) {
1382                         insert_remat_after(si, remat, bb, live_in);
1383                 }
1384                 del_pset(post_remats);
1385                 del_pset(live_in);
1386         }
1387 }
1388
1389 static int
1390 can_be_copied(const ir_node * bb, const ir_node * irn)
1391 {
1392         const ir_edge_t *edge    = get_block_succ_first(bb);
1393         const ir_node   *next_bb = edge->src;
1394         int             pos      = edge->pos;
1395         const ir_node   *phi;
1396
1397         assert(is_merge_edge(bb));
1398
1399         sched_foreach(next_bb, phi) {
1400                 const ir_node  *phi_arg;
1401
1402                 if(!is_Phi(phi)) break;
1403
1404                 phi_arg = get_irn_n(phi, pos);
1405
1406                 if(phi_arg == irn) {
1407                         return 1;
1408                 }
1409         }
1410         return 0;
1411 }
1412
1413 /**
1414  * Initialize additional node info
1415  */
1416 static void
1417 luke_initializer(ir_node * bb, void * data)
1418 {
1419         spill_ilp_t    *si = (spill_ilp_t*)data;
1420         spill_bb_t     *spill_bb;
1421         ir_node        *irn;
1422
1423         spill_bb = obstack_alloc(si->obst, sizeof(*spill_bb));
1424         set_irn_link(bb, spill_bb);
1425
1426         sched_foreach(bb, irn) {
1427                 op_t      *op;
1428
1429                 op = obstack_alloc(si->obst, sizeof(*op));
1430                 op->is_remat = 0;
1431                 op->attr.live_range.ilp = ILP_UNDEF;
1432                 if(is_Phi(irn)) {
1433                         if(opt_memcopies) {
1434                                 op->attr.live_range.args.copies = obstack_alloc(si->obst, sizeof(*op->attr.live_range.args.copies) * get_irn_arity(irn));
1435                                 memset(op->attr.live_range.args.copies, 0xFF, sizeof(*op->attr.live_range.args.copies) * get_irn_arity(irn));
1436                         }
1437                 } else if(!is_Proj(irn)) {
1438                         op->attr.live_range.args.reloads = obstack_alloc(si->obst, sizeof(*op->attr.live_range.args.reloads) * get_irn_arity(irn));
1439                         memset(op->attr.live_range.args.reloads, 0xFF, sizeof(*op->attr.live_range.args.reloads) * get_irn_arity(irn));
1440                 } else {
1441                         op->attr.live_range.args.reloads = NULL;
1442                 }
1443                 set_irn_link(irn, op);
1444         }
1445 }
1446
1447
1448 /**
1449  * Preparation of blocks' ends for Luke Blockwalker(tm)(R)
1450  */
1451 static void
1452 luke_endwalker(ir_node * bb, void * data)
1453 {
1454         spill_ilp_t    *si = (spill_ilp_t*)data;
1455         pset           *live;
1456         pset           *use_end;
1457         char            buf[256];
1458         ilp_cst_t       cst;
1459         ir_node        *irn;
1460         spill_bb_t     *spill_bb = get_irn_link(bb);
1461         int             i;
1462
1463         live = pset_new_ptr_default();
1464         use_end = pset_new_ptr_default();
1465
1466         be_lv_foreach(si->lv, bb, be_lv_state_end, i) {
1467                 irn = be_lv_get_irn(si->lv, bb, i);
1468                 if (has_reg_class(si, irn) && !pset_find_ptr(si->all_possible_remats, irn)) {
1469                         pset_insert_ptr(live, irn);
1470                 }
1471         }
1472         /*
1473          * find values that are used by remats at end of block
1474          * and insert them into live set
1475          */
1476         foreach_pre_remat(si, bb, irn) {
1477                 int       n;
1478
1479                 for (n=get_irn_arity(irn)-1; n>=0; --n) {
1480                         ir_node        *remat_arg = get_irn_n(irn, n);
1481
1482                         if(has_reg_class(si, remat_arg)) {
1483                                 pset_insert_ptr(live, remat_arg);
1484                         }
1485                 }
1486         }
1487
1488         /* collect values used by cond jumps etc. at bb end (use_end) -> always live */
1489         /* their reg_out must always be set */
1490         sched_foreach_reverse(bb, irn) {
1491                 int   n;
1492
1493                 if(!sched_skip_cf_predicator(irn, si->birg->main_env->arch_env)) break;
1494
1495                 for (n=get_irn_arity(irn)-1; n>=0; --n) {
1496                         ir_node        *irn_arg = get_irn_n(irn, n);
1497
1498                         if(has_reg_class(si, irn_arg)) {
1499                                 pset_insert_ptr(use_end, irn_arg);
1500                         }
1501                 }
1502         }
1503
1504         ir_snprintf(buf, sizeof(buf), "check_end_%N", bb);
1505         //cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs);
1506         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs - pset_count(use_end));
1507
1508         spill_bb->ilp = new_set(cmp_spill, pset_count(live)+pset_count(use_end));
1509
1510         /* if this is a merge edge we can reload at the end of this block */
1511         if(is_merge_edge(bb)) {
1512                 spill_bb->reloads = new_set(cmp_keyval, pset_count(live)+pset_count(use_end));
1513         } else if(pset_count(use_end)){
1514                 spill_bb->reloads = new_set(cmp_keyval, pset_count(use_end));
1515         } else {
1516                 spill_bb->reloads = NULL;
1517         }
1518
1519         pset_foreach(live,irn) {
1520                 spill_t     query,
1521                                         *spill;
1522                 double      spill_cost;
1523                 int         default_spilled;
1524
1525
1526                 /* handle values used by control flow nodes later separately */
1527                 if(pset_find_ptr(use_end, irn)) continue;
1528
1529                 query.irn = irn;
1530                 spill = set_insert(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1531
1532                 spill_cost = is_Unknown(irn)?0.0001:opt_cost_spill*execution_frequency(si, bb);
1533
1534                 ir_snprintf(buf, sizeof(buf), "reg_out_%N_%N", irn, bb);
1535                 spill->reg_out = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
1536                 lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1537
1538                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", irn, bb);
1539                 spill->mem_out = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
1540
1541                 ir_snprintf(buf, sizeof(buf), "spill_%N_%N", irn, bb);
1542                 /* by default spill value right after definition */
1543                 default_spilled = be_is_live_in(si->lv, bb, irn) || is_Phi(irn);
1544                 spill->spill    = lpp_add_var_default(si->lpp, buf, lpp_binary, spill_cost, !default_spilled);
1545
1546                 if(is_merge_edge(bb)) {
1547                         ilp_var_t   reload;
1548                         ilp_cst_t   rel_cst;
1549
1550                         ir_snprintf(buf, sizeof(buf), "reload_%N_%N", bb, irn);
1551                         reload = lpp_add_var_default(si->lpp, buf, lpp_binary, opt_cost_reload*execution_frequency(si, bb), can_be_copied(bb, irn));
1552                         set_insert_keyval(spill_bb->reloads, irn, INT_TO_PTR(reload));
1553
1554                         /* reload <= mem_out */
1555                         rel_cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
1556                         lpp_set_factor_fast(si->lpp, rel_cst, reload, 1.0);
1557                         lpp_set_factor_fast(si->lpp, rel_cst, spill->mem_out, -1.0);
1558                 }
1559
1560                 spill->reg_in = ILP_UNDEF;
1561                 spill->mem_in = ILP_UNDEF;
1562         }
1563
1564         pset_foreach(use_end,irn) {
1565                 spill_t     query,
1566                                         *spill;
1567                 double      spill_cost;
1568                 ilp_cst_t   end_use_req,
1569                                         rel_cst;
1570                 ilp_var_t   reload;
1571                 int         default_spilled;
1572
1573                 query.irn = irn;
1574                 spill = set_insert(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1575
1576                 spill_cost = is_Unknown(irn)?0.0001:opt_cost_spill*execution_frequency(si, bb);
1577
1578                 ir_snprintf(buf, sizeof(buf), "reg_out_%N_%N", irn, bb);
1579                 spill->reg_out = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
1580
1581                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", irn, bb);
1582                 spill->mem_out = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
1583
1584                 ir_snprintf(buf, sizeof(buf), "spill_%N_%N", irn, bb);
1585                 default_spilled = be_is_live_in(si->lv, bb, irn) || is_Phi(irn);
1586                 spill->spill    = lpp_add_var_default(si->lpp, buf, lpp_binary, spill_cost, !default_spilled);
1587
1588                 /* reload for use be control flow op */
1589                 ir_snprintf(buf, sizeof(buf), "reload_%N_%N", bb, irn);
1590                 reload = lpp_add_var_default(si->lpp, buf, lpp_binary, opt_cost_reload*execution_frequency(si, bb), 1.0);
1591                 set_insert_keyval(spill_bb->reloads, irn, INT_TO_PTR(reload));
1592
1593                 /* reload <= mem_out */
1594                 rel_cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
1595                 lpp_set_factor_fast(si->lpp, rel_cst, reload, 1.0);
1596                 lpp_set_factor_fast(si->lpp, rel_cst, spill->mem_out, -1.0);
1597
1598                 spill->reg_in = ILP_UNDEF;
1599                 spill->mem_in = ILP_UNDEF;
1600
1601                 ir_snprintf(buf, sizeof(buf), "req_cf_end_%N_%N", irn, bb);
1602                 end_use_req = lpp_add_cst_uniq(si->lpp, buf, lpp_equal, 1);
1603                 lpp_set_factor_fast(si->lpp, end_use_req, spill->reg_out, 1.0);
1604         }
1605
1606         del_pset(live);
1607         del_pset(use_end);
1608 }
1609
1610 #ifndef NDEBUG
1611 /**
1612  * Find a remat of value @p value in the epilog of @p pos
1613  */
1614 static ir_node *
1615 find_post_remat(const ir_node * value, const ir_node * pos)
1616 {
1617         while((pos = next_post_remat(pos)) != NULL) {
1618                 op_t   *op;
1619
1620                 op = get_irn_link(pos);
1621                 assert(op->is_remat && !op->attr.remat.pre);
1622
1623                 if(op->attr.remat.remat->value == value)
1624                         return (ir_node*)pos;
1625
1626 #if 0
1627         const ir_edge_t *edge;
1628                 foreach_out_edge(pos, edge) {
1629                         ir_node   *proj = get_edge_src_irn(edge);
1630                         assert(is_Proj(proj));
1631                 }
1632 #endif
1633
1634         }
1635
1636         return NULL;
1637 }
1638 #endif
1639
1640 static spill_t *
1641 add_to_spill_bb(spill_ilp_t * si, ir_node * bb, ir_node * irn)
1642 {
1643         spill_bb_t  *spill_bb = get_irn_link(bb);
1644         spill_t     *spill,
1645                                  query;
1646         char         buf[256];
1647         int          default_spilled;
1648
1649         query.irn = irn;
1650         spill = set_find(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1651         if(!spill) {
1652                 double   spill_cost = is_Unknown(irn)?0.0001:opt_cost_spill*execution_frequency(si, bb);
1653
1654                 spill = set_insert(spill_bb->ilp, &query, sizeof(query), HASH_PTR(irn));
1655
1656                 spill->reg_out = ILP_UNDEF;
1657                 spill->reg_in  = ILP_UNDEF;
1658                 spill->mem_in  = ILP_UNDEF;
1659
1660                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", irn, bb);
1661                 spill->mem_out = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
1662
1663                 ir_snprintf(buf, sizeof(buf), "spill_%N_%N", irn, bb);
1664                 default_spilled = be_is_live_in(si->lv, bb, irn) || is_Phi(irn);
1665                 spill->spill    = lpp_add_var_default(si->lpp, buf, lpp_binary, spill_cost, !default_spilled);
1666         }
1667
1668         return spill;
1669 }
1670
1671 /**
1672  *  Inserts ILP-constraints and variables for memory copying before the given position
1673  */
1674 static void
1675 insert_mem_copy_position(spill_ilp_t * si, pset * live, const ir_node * block)
1676 {
1677         const ir_node    *succ;
1678         const ir_edge_t  *edge;
1679         spill_bb_t       *spill_bb = get_irn_link(block);
1680         ir_node          *phi;
1681         int               pos;
1682         ilp_cst_t         cst;
1683         ilp_var_t         copyreg;
1684         char              buf[256];
1685         ir_node          *tmp;
1686
1687
1688         assert(edges_activated(current_ir_graph));
1689
1690         edge = get_block_succ_first(block);
1691         if(!edge) return;
1692
1693         succ = edge->src;
1694         pos = edge->pos;
1695
1696         edge = get_block_succ_next(block, edge);
1697         /* next block can only contain phis, if this is a merge edge */
1698         if(edge) return;
1699
1700         ir_snprintf(buf, sizeof(buf), "copyreg_%N", block);
1701         copyreg = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
1702
1703         ir_snprintf(buf, sizeof(buf), "check_copyreg_%N", block);
1704         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs);
1705
1706         pset_foreach(live, tmp) {
1707                 spill_t  *spill;
1708 #if 0
1709                 op_t  *op = get_irn_link(irn);
1710                 lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, 1.0);
1711 #endif
1712                 spill = set_find_spill(spill_bb->ilp, tmp);
1713                 assert(spill);
1714
1715                 lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1716         }
1717         lpp_set_factor_fast(si->lpp, cst, copyreg, 1.0);
1718
1719         sched_foreach(succ, phi) {
1720                 const ir_node  *to_copy;
1721                 op_t           *to_copy_op;
1722                 spill_t        *to_copy_spill;
1723                 op_t           *phi_op = get_irn_link(phi);
1724                 ilp_var_t       reload = ILP_UNDEF;
1725
1726
1727                 if(!is_Phi(phi)) break;
1728                 if(!has_reg_class(si, phi)) continue;
1729
1730                 to_copy = get_irn_n(phi, pos);
1731                 to_copy_op = get_irn_link(to_copy);
1732
1733                 to_copy_spill = set_find_spill(spill_bb->ilp, to_copy);
1734                 assert(to_copy_spill);
1735
1736                 if(spill_bb->reloads) {
1737                         keyval_t *keyval = set_find_keyval(spill_bb->reloads, to_copy);
1738
1739                         if(keyval) {
1740                                 reload = PTR_TO_INT(keyval->val);
1741                         }
1742                 }
1743
1744                 ir_snprintf(buf, sizeof(buf), "req_copy_%N_%N_%N", block, phi, to_copy);
1745                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
1746
1747                 /* copy - reg_out - reload - remat - live_range <= 0 */
1748                 lpp_set_factor_fast(si->lpp, cst, phi_op->attr.live_range.args.copies[pos], 1.0);
1749                 lpp_set_factor_fast(si->lpp, cst, to_copy_spill->reg_out, -1.0);
1750                 if(reload != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, reload, -1.0);
1751                 lpp_set_factor_fast(si->lpp, cst, to_copy_op->attr.live_range.ilp, -1.0);
1752                 foreach_pre_remat(si, block, tmp) {
1753                         op_t     *remat_op = get_irn_link(tmp);
1754                         if(remat_op->attr.remat.remat->value == to_copy) {
1755                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1756                         }
1757                 }
1758
1759                 ir_snprintf(buf, sizeof(buf), "copyreg_%N_%N_%N", block, phi, to_copy);
1760                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
1761
1762                 /* copy - reg_out - copyreg <= 0 */
1763                 lpp_set_factor_fast(si->lpp, cst, phi_op->attr.live_range.args.copies[pos], 1.0);
1764                 lpp_set_factor_fast(si->lpp, cst, to_copy_spill->reg_out, -1.0);
1765                 lpp_set_factor_fast(si->lpp, cst, copyreg, -1.0);
1766         }
1767 }
1768
1769
1770 /**
1771  * Walk all irg blocks and emit this ILP
1772  */
1773 static void
1774 luke_blockwalker(ir_node * bb, void * data)
1775 {
1776         spill_ilp_t    *si = (spill_ilp_t*)data;
1777         ir_node        *irn;
1778         pset           *live;
1779         char            buf[256];
1780         ilp_cst_t       cst;
1781         spill_bb_t     *spill_bb = get_irn_link(bb);
1782         ir_node        *tmp;
1783         spill_t        *spill;
1784         pset           *defs = pset_new_ptr_default();
1785         const arch_env_t *arch_env = si->birg->main_env->arch_env;
1786
1787         live = pset_new_ptr_default();
1788
1789         /****************************************
1790          *      B A S I C  B L O C K  E N D
1791          ***************************************/
1792
1793
1794         /* init live values at end of block */
1795         get_live_end(si, bb, live);
1796
1797         pset_foreach(live, irn) {
1798                 op_t           *op;
1799                 ilp_var_t       reload = ILP_UNDEF;
1800
1801                 spill = set_find_spill(spill_bb->ilp, irn);
1802                 assert(spill);
1803
1804                 if(spill_bb->reloads) {
1805                         keyval_t *keyval = set_find_keyval(spill_bb->reloads, irn);
1806
1807                         if(keyval) {
1808                                 reload = PTR_TO_INT(keyval->val);
1809                         }
1810                 }
1811
1812                 op = get_irn_link(irn);
1813                 assert(!op->is_remat);
1814
1815                 ir_snprintf(buf, sizeof(buf), "lr_%N_%N", irn, bb);
1816                 op->attr.live_range.ilp = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
1817                 op->attr.live_range.op = bb;
1818
1819                 ir_snprintf(buf, sizeof(buf), "reg_out_%N_%N", bb, irn);
1820                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
1821
1822                 /* reg_out - reload - remat - live_range <= 0 */
1823                 lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1824                 if(reload != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, reload, -1.0);
1825                 lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, -1.0);
1826                 foreach_pre_remat(si, bb, tmp) {
1827                         op_t     *remat_op = get_irn_link(tmp);
1828                         if(remat_op->attr.remat.remat->value == irn) {
1829                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1830                         }
1831                 }
1832                 ir_snprintf(buf, sizeof(buf), "reg_out2_%N_%N", bb, irn);
1833                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_greater, 0.0);
1834
1835                 /* value may only die at bb end if it is used for a mem copy */
1836                 /* reg_out + \sum copy - reload - remat - live_range >= 0 */
1837                 lpp_set_factor_fast(si->lpp, cst, spill->reg_out, 1.0);
1838                 if(reload != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, reload, -1.0);
1839                 lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, -1.0);
1840                 foreach_pre_remat(si, bb, tmp) {
1841                         op_t     *remat_op = get_irn_link(tmp);
1842                         if(remat_op->attr.remat.remat->value == irn) {
1843                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
1844                         }
1845                 }
1846                 if(is_merge_edge(bb)) {
1847                         const ir_edge_t *edge = get_block_succ_first(bb);
1848                         const ir_node   *next_bb = edge->src;
1849                         int              pos = edge->pos;
1850                         const ir_node   *phi;
1851
1852                         sched_foreach(next_bb, phi) {
1853                                 const ir_node  *phi_arg;
1854
1855                                 if(!is_Phi(phi)) break;
1856
1857                                 phi_arg = get_irn_n(phi, pos);
1858
1859                                 if(phi_arg == irn) {
1860                                         op_t      *phi_op = get_irn_link(phi);
1861                                         ilp_var_t  copy = phi_op->attr.live_range.args.copies[pos];
1862
1863                                         lpp_set_factor_fast(si->lpp, cst, copy, 1.0);
1864                                 }
1865                         }
1866                 }
1867         }
1868
1869         if(opt_memcopies)
1870                 insert_mem_copy_position(si, live, bb);
1871
1872         /*
1873          * assure the remat args are available
1874          */
1875         foreach_pre_remat(si, bb, tmp) {
1876                 op_t     *remat_op = get_irn_link(tmp);
1877                 int       n;
1878
1879                 for (n=get_irn_arity(tmp)-1; n>=0; --n) {
1880                         ir_node        *remat_arg = get_irn_n(tmp, n);
1881                         op_t           *arg_op = get_irn_link(remat_arg);
1882
1883                         if(!has_reg_class(si, remat_arg)) continue;
1884
1885                         spill = set_find_spill(spill_bb->ilp, remat_arg);
1886                         assert(spill);
1887
1888                         /* arguments of remats have to be live until the very end of the block
1889                          * remat = reg_out(remat_arg) and (reload(remat_arg) or live_range(remat_arg)),
1890                          * no remats, they could be in wrong order
1891                          */
1892
1893                         ir_snprintf(buf, sizeof(buf), "req_remat_%N_arg_%N", tmp, remat_arg);
1894                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
1895
1896                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 3.0);
1897                         lpp_set_factor_fast(si->lpp, cst, spill->reg_out, -2.0);
1898                         lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, -1.0);
1899
1900                         /* use reload placed for this argument */
1901                         if(spill_bb->reloads) {
1902                                 keyval_t *keyval = set_find_keyval(spill_bb->reloads, remat_arg);
1903
1904                                 if(keyval) {
1905                                         ilp_var_t       reload = PTR_TO_INT(keyval->val);
1906
1907                                         lpp_set_factor_fast(si->lpp, cst, reload, -1.0);
1908                                 }
1909                         }
1910                 }
1911         }
1912         DBG((si->dbg, LEVEL_4, "\t   %d values live at end of block %+F\n", pset_count(live), bb));
1913
1914
1915
1916
1917         /**************************************
1918          *    B A S I C  B L O C K  B O D Y
1919          **************************************/
1920
1921         sched_foreach_reverse_from(sched_block_last_noncf(si, bb), irn) {
1922                 op_t       *op;
1923                 op_t       *tmp_op;
1924                 int         n,
1925                                         u = 0,
1926                                         d = 0;
1927                 ilp_cst_t       check_pre,
1928                                         check_post;
1929                 set        *args;
1930                 pset       *used;
1931                 pset       *remat_defs;
1932                 keyval_t   *keyval;
1933                 ilp_cst_t   one_memoperand = -1;
1934
1935                 /* iterate only until first phi */
1936                 if(is_Phi(irn))
1937                         break;
1938
1939                 op = get_irn_link(irn);
1940                 /* skip remats */
1941                 if(op->is_remat) continue;
1942
1943                 DBG((si->dbg, LEVEL_4, "\t  at node %+F\n", irn));
1944
1945                 /* collect defined values */
1946                 if(has_reg_class(si, irn)) {
1947                         pset_insert_ptr(defs, irn);
1948                 }
1949
1950                 /* skip projs */
1951                 if(is_Proj(irn)) continue;
1952
1953                 /*
1954                  * init set of irn's arguments
1955                  * and all possibly used values around this op
1956                  * and values defined by post remats
1957                  */
1958                 args =       new_set(cmp_keyval, get_irn_arity(irn));
1959                 used =       pset_new_ptr(pset_count(live) + get_irn_arity(irn));
1960                 remat_defs = pset_new_ptr(pset_count(live));
1961
1962                 if(!is_start_block(bb) || !be_is_Barrier(irn)) {
1963                         for (n=get_irn_arity(irn)-1; n>=0; --n) {
1964                                 ir_node        *irn_arg = get_irn_n(irn, n);
1965                                 if(has_reg_class(si, irn_arg)) {
1966                                         set_insert_keyval(args, irn_arg, (void*)n);
1967                                         pset_insert_ptr(used, irn_arg);
1968                                 }
1969                         }
1970                         foreach_post_remat(irn, tmp) {
1971                                 op_t    *remat_op = get_irn_link(tmp);
1972
1973                                 pset_insert_ptr(remat_defs, remat_op->attr.remat.remat->value);
1974
1975                                 for (n=get_irn_arity(tmp)-1; n>=0; --n) {
1976                                         ir_node        *remat_arg = get_irn_n(tmp, n);
1977                                         if(has_reg_class(si, remat_arg)) {
1978                                                 pset_insert_ptr(used, remat_arg);
1979                                         }
1980                                 }
1981                         }
1982                         foreach_pre_remat(si, irn, tmp) {
1983                                 for (n=get_irn_arity(tmp)-1; n>=0; --n) {
1984                                         ir_node        *remat_arg = get_irn_n(tmp, n);
1985                                         if(has_reg_class(si, remat_arg)) {
1986                                                 pset_insert_ptr(used, remat_arg);
1987                                         }
1988                                 }
1989                         }
1990                 }
1991
1992                 /**********************************
1993                  *   I N  E P I L O G  O F  irn
1994                  **********************************/
1995
1996                 /* ensure each dying value is used by only one post remat */
1997                 pset_foreach(used, tmp) {
1998                         ir_node     *value = tmp;
1999                         op_t        *value_op = get_irn_link(value);
2000                         ir_node     *remat;
2001                         int          n_remats = 0;
2002
2003                         cst = ILP_UNDEF;
2004                         foreach_post_remat(irn, remat) {
2005                                 op_t  *remat_op = get_irn_link(remat);
2006
2007                                 for(n=get_irn_arity(remat)-1; n>=0; --n) {
2008                                         ir_node   *remat_arg = get_irn_n(remat, n);
2009
2010                                         /* if value is used by this remat add it to constraint */
2011                                         if(remat_arg == value) {
2012                                                 if(n_remats == 0) {
2013                                                         /* sum remat2s <= 1 + n_remats*live_range */
2014                                                         ir_snprintf(buf, sizeof(buf), "dying_lr_%N_%N", value, irn);
2015                                                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2016                                                 }
2017
2018                                                 n_remats++;
2019                                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2020                                                 break;
2021                                         }
2022                                 }
2023                         }
2024
2025                         if(pset_find_ptr(live, value) && cst != ILP_UNDEF) {
2026                                 lpp_set_factor_fast(si->lpp, cst, value_op->attr.live_range.ilp, -n_remats);
2027                         }
2028                 }
2029
2030         /* ensure at least one value dies at post remat */
2031         foreach_post_remat(irn, tmp) {
2032             op_t     *remat_op = get_irn_link(tmp);
2033             pset     *remat_args = pset_new_ptr(get_irn_arity(tmp));
2034             ir_node  *remat_arg;
2035
2036             for(n=get_irn_arity(tmp)-1; n>=0; --n) {
2037                 remat_arg = get_irn_n(tmp, n);
2038
2039                 if(has_reg_class(si, remat_arg)) {
2040
2041                     /* does arg always die at this op? */
2042                     if(!pset_find_ptr(live, remat_arg))
2043                         goto skip_one_must_die;
2044
2045                     pset_insert_ptr(remat_args, remat_arg);
2046                 }
2047             }
2048
2049             /* remat + \sum live_range(remat_arg) <= |args| */
2050             ir_snprintf(buf, sizeof(buf), "one_must_die_%+F", tmp);
2051             cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, pset_count(remat_args));
2052             lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2053
2054             pset_foreach(remat_args, remat_arg) {
2055                 op_t  *arg_op = get_irn_link(remat_arg);
2056
2057                 lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, 1.0);
2058             }
2059
2060 skip_one_must_die:
2061             del_pset(remat_args);
2062         }
2063
2064                 /* new live ranges for values from L\U defined by post remats */
2065                 pset_foreach(live, tmp) {
2066                         ir_node     *value = tmp;
2067                         op_t        *value_op = get_irn_link(value);
2068
2069                         if(!set_find_keyval(args, value) && !pset_find_ptr(defs, value)) {
2070                                 ilp_var_t    prev_lr = ILP_UNDEF;
2071                                 ir_node     *remat;
2072
2073                                 if(pset_find_ptr(remat_defs, value)) {
2074
2075                                         /* next_live_range <= prev_live_range + sum remat2s */
2076                                         ir_snprintf(buf, sizeof(buf), "next_lr_%N_%N", value, irn);
2077                                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2078
2079                                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", value, irn);
2080                                         prev_lr = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2081
2082                                         lpp_set_factor_fast(si->lpp, cst, value_op->attr.live_range.ilp, 1.0);
2083                                         lpp_set_factor_fast(si->lpp, cst, prev_lr, -1.0);
2084
2085                                         foreach_post_remat(irn, remat) {
2086                                                 op_t        *remat_op = get_irn_link(remat);
2087
2088                                                 /* if value is being rematerialized by this remat */
2089                                                 if(value == remat_op->attr.remat.remat->value) {
2090                                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
2091                                                 }
2092                                         }
2093
2094                                         value_op->attr.live_range.ilp = prev_lr;
2095                                         value_op->attr.live_range.op = irn;
2096                                 }
2097                         }
2098                 }
2099
2100                 /* requirements for post remats and start live ranges from L/U' for values dying here */
2101                 foreach_post_remat(irn, tmp) {
2102                         op_t        *remat_op = get_irn_link(tmp);
2103                         int          n;
2104
2105                         for (n=get_irn_arity(tmp)-1; n>=0; --n) {
2106                                 ir_node        *remat_arg = get_irn_n(tmp, n);
2107                                 op_t           *arg_op = get_irn_link(remat_arg);
2108
2109                                 if(!has_reg_class(si, remat_arg)) continue;
2110
2111                                 /* only for values in L\U (TODO and D?), the others are handled with post_use */
2112                                 if(!pset_find_ptr(used, remat_arg)) {
2113                                         /* remat <= live_range(remat_arg) */
2114                                         ir_snprintf(buf, sizeof(buf), "req_remat2_%N_arg_%N", tmp, remat_arg);
2115                                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
2116
2117                                         /* if value is becoming live through use by remat2 */
2118                                         if(!pset_find_ptr(live, remat_arg)) {
2119                                                 ilp_var_t     lr;
2120
2121                                                 ir_snprintf(buf, sizeof(buf), "lr_%N_%N", remat_arg, irn);
2122                                                 lr = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2123
2124                                                 arg_op->attr.live_range.ilp = lr;
2125                                                 arg_op->attr.live_range.op = irn;
2126
2127                                                 DBG((si->dbg, LEVEL_3, "  value %+F becoming live through use by remat2 %+F\n", remat_arg, tmp));
2128
2129                                                 pset_insert_ptr(live, remat_arg);
2130                                                 add_to_spill_bb(si, bb, remat_arg);
2131                                         }
2132
2133                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2134                                         lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, -1.0);
2135                                 }
2136                         }
2137                 }
2138
2139                 d = pset_count(defs);
2140                 DBG((si->dbg, LEVEL_4, "\t   %+F produces %d values in my register class\n", irn, d));
2141
2142                 /* count how many regs irn needs for arguments */
2143                 u = set_count(args);
2144
2145
2146                 /* check the register pressure in the epilog */
2147                 /* sum_{L\U'} lr + sum_{U'} post_use <= k - |D| */
2148                 ir_snprintf(buf, sizeof(buf), "check_post_%N", irn);
2149                 check_post = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs - d);
2150
2151                 /* add L\U' to check_post */
2152                 pset_foreach(live, tmp) {
2153                         if(!pset_find_ptr(used, tmp) && !pset_find_ptr(defs, tmp)) {
2154                                 /* if a live value is not used by irn */
2155                                 tmp_op = get_irn_link(tmp);
2156                                 lpp_set_factor_fast(si->lpp, check_post, tmp_op->attr.live_range.ilp, 1.0);
2157                         }
2158                 }
2159
2160                 /***********************************************************
2161                  *  I T E R A T I O N  O V E R  U S E S  F O R  E P I L O G
2162                  **********************************************************/
2163
2164
2165                 pset_foreach(used, tmp) {
2166                         ilp_var_t       prev_lr;
2167                         ilp_var_t       post_use;
2168                         int             p = 0;
2169                         spill_t        *spill;
2170                         ir_node        *arg = tmp;
2171                         op_t           *arg_op = get_irn_link(arg);
2172                         ir_node        *remat;
2173
2174                         spill = add_to_spill_bb(si, bb, arg);
2175
2176                         /* new live range for each used value */
2177                         ir_snprintf(buf, sizeof(buf), "lr_%N_%N", arg, irn);
2178                         prev_lr = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2179
2180                         /* the epilog stuff - including post_use, check_post, check_post_remat */
2181                         ir_snprintf(buf, sizeof(buf), "post_use_%N_%N", arg, irn);
2182                         post_use = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2183
2184                         lpp_set_factor_fast(si->lpp, check_post, post_use, 1.0);
2185
2186                         /* arg is live throughout epilog if the next live_range is in a register */
2187                         if(pset_find_ptr(live, arg)) {
2188                                 DBG((si->dbg, LEVEL_3, "\t  arg %+F is possibly live in epilog of %+F\n", arg, irn));
2189
2190                                 /* post_use >= next_lr + remat */
2191                                 ir_snprintf(buf, sizeof(buf), "post_use_%N_%N-%d", arg, irn, p++);
2192                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2193                                 lpp_set_factor_fast(si->lpp, cst, post_use, -1.0);
2194                                 lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, 1.0);
2195                         }
2196
2197                         /* forall post remat which use arg add a similar cst */
2198                         foreach_post_remat(irn, remat) {
2199                                 int      n;
2200
2201                                 for (n=get_irn_arity(remat)-1; n>=0; --n) {
2202                                         ir_node    *remat_arg = get_irn_n(remat, n);
2203                                         op_t       *remat_op = get_irn_link(remat);
2204
2205                                         if(remat_arg == arg) {
2206                                                 DBG((si->dbg, LEVEL_3, "\t  found remat with arg %+F in epilog of %+F\n", arg, irn));
2207
2208                                                 /* post_use >= remat */
2209                                                 ir_snprintf(buf, sizeof(buf), "post_use_%N_%N-%d", arg, irn, p++);
2210                                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2211                                                 lpp_set_factor_fast(si->lpp, cst, post_use, -1.0);
2212                                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2213                                         }
2214                                 }
2215                         }
2216
2217                         /* if value is not an arg of op and not possibly defined by post remat
2218                          * then it may only die and not become live
2219                          */
2220                         if(!set_find_keyval(args, arg)) {
2221                                 /* post_use <= prev_lr */
2222                                 ir_snprintf(buf, sizeof(buf), "req_post_use_%N_%N", arg, irn);
2223                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2224                                 lpp_set_factor_fast(si->lpp, cst, post_use, 1.0);
2225                                 lpp_set_factor_fast(si->lpp, cst, prev_lr, -1.0);
2226
2227                                 if(!pset_find_ptr(remat_defs, arg) && pset_find_ptr(live, arg)) {
2228                                         /* next_lr <= prev_lr */
2229                                         ir_snprintf(buf, sizeof(buf), "next_lr_%N_%N", arg, irn);
2230                                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2231                                         lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, 1.0);
2232                                         lpp_set_factor_fast(si->lpp, cst, prev_lr, -1.0);
2233                                 }
2234                         }
2235
2236                         if(opt_memoperands && (!is_start_block(bb) || be_is_Barrier(irn))) {
2237                                 for(n = get_irn_arity(irn)-1; n>=0; --n) {
2238                                         if(get_irn_n(irn, n) == arg && arch_possible_memory_operand(arch_env, irn, n)) {
2239                                                 ilp_var_t       memoperand;
2240
2241                                                 ir_snprintf(buf, sizeof(buf), "memoperand_%N_%d", irn, n);
2242                                                 memoperand = lpp_add_var_default(si->lpp, buf, lpp_binary, opt_cost_memoperand*execution_frequency(si, bb), 0.0);
2243                                                 set_insert_memoperand(si->memoperands, irn, n, memoperand);
2244
2245                                                 ir_snprintf(buf, sizeof(buf), "nolivepost_%N_%d", irn, n);
2246                                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2247
2248                                                 lpp_set_factor_fast(si->lpp, cst, memoperand, 1.0);
2249                                                 lpp_set_factor_fast(si->lpp, cst, post_use, 1.0);
2250                                         }
2251                                 }
2252                         }
2253
2254                         /* new live range begins for each used value */
2255                         arg_op->attr.live_range.ilp = prev_lr;
2256                         arg_op->attr.live_range.op = irn;
2257
2258                         pset_insert_ptr(live, arg);
2259                 }
2260
2261                 /* just to be sure */
2262                 check_post = ILP_UNDEF;
2263
2264                 /* allow original defintions to be removed */
2265                 if(opt_repair_schedule) {
2266                         pset_foreach(defs, tmp) {
2267                                 op_t      *tmp_op = get_irn_link(tmp);
2268                                 spill_t   *spill = set_find_spill(spill_bb->ilp, tmp);
2269 #if 1
2270                                 ilp_var_t  delete;
2271                                 assert(spill);
2272
2273                                 ir_snprintf(buf, sizeof(buf), "delete_%N", tmp);
2274                                 delete = lpp_add_var_default(si->lpp, buf, lpp_binary, -1.0*get_cost(si, irn)*execution_frequency(si, bb), 0.0);
2275
2276                                 /* op may not be killed if its first live_range is 1 */
2277                                 ir_snprintf(buf, sizeof(buf), "killorig-lr_%N", tmp);
2278                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2279                                 lpp_set_factor_fast(si->lpp, cst, delete, 1.0);
2280                                 lpp_set_factor_fast(si->lpp, cst, tmp_op->attr.live_range.ilp, 1.0);
2281
2282                                 /* op may not be killed if it is spilled after the definition */
2283                                 ir_snprintf(buf, sizeof(buf), "killorig-spill_%N", tmp);
2284                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2285                                 lpp_set_factor_fast(si->lpp, cst, delete, 1.0);
2286                                 lpp_set_factor_fast(si->lpp, cst, spill->spill, 1.0);
2287 #else
2288                                 ilp_var_t  keep;
2289                                 assert(spill);
2290
2291                                 ir_snprintf(buf, sizeof(buf), "keep_%N", tmp);
2292                                 keep = lpp_add_var_default(si->lpp, buf, lpp_binary, get_cost(si, irn)*execution_frequency(si, bb), 1.0);
2293
2294                                 /* op may not be killed if its first live_range is 1 */
2295                                 ir_snprintf(buf, sizeof(buf), "killorig-lr_%N", tmp);
2296                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_greater, 0.0);
2297                                 lpp_set_factor_fast(si->lpp, cst, keep, 1.0);
2298                                 lpp_set_factor_fast(si->lpp, cst, tmp_op->attr.live_range.ilp, -1.0);
2299
2300                                 /* op may not be killed if it is spilled after the definition */
2301                                 ir_snprintf(buf, sizeof(buf), "killorig-spill_%N", tmp);
2302                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_greater, 0.0);
2303                                 lpp_set_factor_fast(si->lpp, cst, keep, 1.0);
2304                                 lpp_set_factor_fast(si->lpp, cst, spill->spill, -1.0);
2305 #endif
2306                         }
2307                 } else {
2308 #if 0
2309                         pset_foreach(defs, tmp) {
2310                                 op_t      *tmp_op = get_irn_link(tmp);
2311                                 spill_t   *spill = set_find_spill(spill_bb->ilp, tmp);
2312                                 assert(spill);
2313
2314                                 /* live_range or spill should be 1
2315                                    TODO: lr should be live until first use */
2316                                 ir_snprintf(buf, sizeof(buf), "nokillorig_%N", tmp);
2317                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_greater, 1.0);
2318                                 lpp_set_factor_fast(si->lpp, cst, tmp_op->attr.live_range.ilp, 1.0);
2319                                 lpp_set_factor_fast(si->lpp, cst, spill->spill, 1.0);
2320                         }
2321 #endif
2322                 }
2323
2324
2325                 /******************
2326                  *   P R O L O G
2327                  ******************/
2328
2329                 /* check the register pressure in the prolog */
2330                 /* sum_{L\U} lr <= k - |U| */
2331                 ir_snprintf(buf, sizeof(buf), "check_pre_%N", irn);
2332                 check_pre = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs - u);
2333
2334                 /* for the prolog remove defined values from the live set */
2335                 pset_foreach(defs, tmp) {
2336                         pset_remove_ptr(live, tmp);
2337                 }
2338
2339                 if(opt_memoperands && (!is_start_block(bb) || be_is_Barrier(irn))) {
2340                         ir_snprintf(buf, sizeof(buf), "one_memoperand_%N", irn);
2341                         one_memoperand = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2342                 }
2343
2344                 /***********************************************************
2345                  *  I T E R A T I O N  O V E R  A R G S  F O R  P R O L O G
2346                  **********************************************************/
2347
2348
2349                 set_foreach(args, keyval) {
2350                         spill_t          *spill;
2351                         const ir_node    *arg = keyval->key;
2352                         int               i = PTR_TO_INT(keyval->val);
2353                         op_t             *arg_op = get_irn_link(arg);
2354                         ilp_cst_t         requirements;
2355                         int               n_memoperands;
2356
2357                         spill = set_find_spill(spill_bb->ilp, arg);
2358                         assert(spill);
2359
2360                         ir_snprintf(buf, sizeof(buf), "reload_%N_%N", arg, irn);
2361                         op->attr.live_range.args.reloads[i] = lpp_add_var_default(si->lpp, buf, lpp_binary, opt_cost_reload*execution_frequency(si, bb), 1.0);
2362
2363                         /* reload <= mem_out */
2364                         ir_snprintf(buf, sizeof(buf), "req_reload_%N_%N", arg, irn);
2365                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2366                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.args.reloads[i], 1.0);
2367                         lpp_set_factor_fast(si->lpp, cst, spill->mem_out, -1.0);
2368
2369                         /* requirement: arg must be in register for use */
2370                         /* reload + remat + live_range == 1 */
2371                         ir_snprintf(buf, sizeof(buf), "req_%N_%N", irn, arg);
2372                         requirements = lpp_add_cst_uniq(si->lpp, buf, lpp_equal, 1.0);
2373
2374                         lpp_set_factor_fast(si->lpp, requirements, arg_op->attr.live_range.ilp, 1.0);
2375                         lpp_set_factor_fast(si->lpp, requirements, op->attr.live_range.args.reloads[i], 1.0);
2376                         foreach_pre_remat(si, irn, tmp) {
2377                                 op_t     *remat_op = get_irn_link(tmp);
2378                                 if(remat_op->attr.remat.remat->value == arg) {
2379                                         lpp_set_factor_fast(si->lpp, requirements, remat_op->attr.remat.ilp, 1.0);
2380                                 }
2381                         }
2382
2383                         if(opt_memoperands && (!is_start_block(bb) || be_is_Barrier(irn))) {
2384                                 n_memoperands = 0;
2385                                 for(n = get_irn_arity(irn)-1; n>=0; --n) {
2386                                         if(get_irn_n(irn, n) == arg) {
2387                                                 n_memoperands++;
2388                                         }
2389                                 }
2390                                 for(n = get_irn_arity(irn)-1; n>=0; --n) {
2391                                         if(get_irn_n(irn, n) == arg && arch_possible_memory_operand(arch_env, irn, n)) {
2392                                                 memoperand_t  *memoperand;
2393                                                 memoperand = set_find_memoperand(si->memoperands, irn, n);
2394
2395                                                 /* memoperand <= mem_out */
2396                                                 ir_snprintf(buf, sizeof(buf), "req_memoperand_%N_%d", irn, n);
2397                                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2398                                                 lpp_set_factor_fast(si->lpp, cst, memoperand->ilp, 1.0);
2399                                                 lpp_set_factor_fast(si->lpp, cst, spill->mem_out, -1.0);
2400
2401                                                 /* the memoperand is only sufficient if it is used once by the op */
2402                                                 if(n_memoperands == 1)
2403                                                         lpp_set_factor_fast(si->lpp, requirements, memoperand->ilp, 1.0);
2404
2405                                                 lpp_set_factor_fast(si->lpp, one_memoperand, memoperand->ilp, 1.0);
2406
2407                                                 /* we have one more free register if we use a memory operand */
2408                                                 lpp_set_factor_fast(si->lpp, check_pre, memoperand->ilp, -1.0);
2409                                         }
2410                                 }
2411                         }
2412                 }
2413
2414                 /* iterate over L\U */
2415                 pset_foreach(live, tmp) {
2416                         if(!set_find_keyval(args, tmp)) {
2417                                 /* if a live value is not used by irn */
2418                                 tmp_op = get_irn_link(tmp);
2419                                 lpp_set_factor_fast(si->lpp, check_pre, tmp_op->attr.live_range.ilp, 1.0);
2420                         }
2421                 }
2422
2423                 /* requirements for remats */
2424                 foreach_pre_remat(si, irn, tmp) {
2425                         op_t        *remat_op = get_irn_link(tmp);
2426                         int          n;
2427
2428                         for (n=get_irn_arity(tmp)-1; n>=0; --n) {
2429                                 ir_node        *remat_arg = get_irn_n(tmp, n);
2430                                 op_t           *arg_op = get_irn_link(remat_arg);
2431
2432                                 if(!has_reg_class(si, remat_arg)) continue;
2433
2434                                 /* remat <= live_rang(remat_arg) [ + reload(remat_arg) ] */
2435                                 ir_snprintf(buf, sizeof(buf), "req_remat_%N_arg_%N", tmp, remat_arg);
2436                                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
2437
2438                                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2439                                 lpp_set_factor_fast(si->lpp, cst, arg_op->attr.live_range.ilp, -1.0);
2440
2441                                 /* if remat arg is also used by current op then we can use reload placed for this argument */
2442                                 if((keyval = set_find_keyval(args, remat_arg)) != NULL) {
2443                                         int    index = (int)keyval->val;
2444
2445                                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.args.reloads[index], -1.0);
2446                                 }
2447                         }
2448                 }
2449
2450
2451
2452
2453                 /*************************
2454                  *  D O N E  W I T H  O P
2455                  *************************/
2456
2457                 DBG((si->dbg, LEVEL_4, "\t   %d values live at %+F\n", pset_count(live), irn));
2458
2459                 pset_foreach(live, tmp) {
2460                         assert(has_reg_class(si, tmp));
2461                 }
2462
2463 #ifndef NDEBUG
2464                 for (n=get_irn_arity(irn)-1; n>=0; --n) {
2465                         ir_node        *arg = get_irn_n(irn, n);
2466
2467                         assert(!find_post_remat(arg, irn) && "there should be no post remat for an argument of an op");
2468                 }
2469 #endif
2470
2471                 del_pset(remat_defs);
2472                 del_pset(used);
2473                 del_set(args);
2474                 del_pset(defs);
2475                 defs = pset_new_ptr_default();
2476
2477                 /* skip everything above barrier in start block */
2478                 if(is_start_block(bb) && be_is_Barrier(irn)) {
2479                         assert(pset_count(live) == 0);
2480                         break;
2481                 }
2482
2483         }
2484         del_pset(defs);
2485
2486
2487
2488         /***************************************
2489          *   B E G I N N I N G  O F  B L O C K
2490          ***************************************/
2491
2492
2493         /* we are now at the beginning of the basic block, there are only \Phis in front of us */
2494         DBG((si->dbg, LEVEL_3, "\t   %d values live at beginning of block %+F\n", pset_count(live), bb));
2495
2496         pset_foreach(live, irn) {
2497                 assert(is_Phi(irn) || get_nodes_block(irn) != bb);
2498         }
2499
2500         /* construct mem_outs for all values */
2501         set_foreach(spill_bb->ilp, spill) {
2502                 ir_snprintf(buf, sizeof(buf), "mem_out_%N_%N", spill->irn, bb);
2503                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2504
2505                 lpp_set_factor_fast(si->lpp, cst, spill->mem_out, 1.0);
2506                 lpp_set_factor_fast(si->lpp, cst, spill->spill, -1.0);
2507
2508                 if(pset_find_ptr(live, spill->irn)) {
2509                         int default_spilled;
2510                         DBG((si->dbg, LEVEL_5, "\t     %+F live at beginning of block %+F\n", spill->irn, bb));
2511
2512                         ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N", spill->irn, bb);
2513                         default_spilled = be_is_live_in(si->lv, bb, spill->irn) || is_Phi(spill->irn);
2514                         spill->mem_in   = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, default_spilled);
2515                         lpp_set_factor_fast(si->lpp, cst, spill->mem_in, -1.0);
2516
2517                         if(opt_memcopies && is_Phi(spill->irn) && get_nodes_block(spill->irn) == bb) {
2518                                 int   n;
2519                                 op_t *op = get_irn_link(spill->irn);
2520
2521                                 for(n=get_irn_arity(spill->irn)-1; n>=0; --n) {
2522                                         const ir_node  *arg = get_irn_n(spill->irn, n);
2523                                         double          freq=0.0;
2524                                         int             m;
2525                                         ilp_var_t       var;
2526
2527
2528                                         /* argument already done? */
2529                                         if(op->attr.live_range.args.copies[n] != ILP_UNDEF) continue;
2530
2531                                         /* get sum of execution frequencies of blocks with the same phi argument */
2532                                         for(m=n; m>=0; --m) {
2533                                                 const ir_node  *arg2 = get_irn_n(spill->irn, m);
2534
2535                                                 if(arg==arg2) {
2536                                                         freq += execution_frequency(si, get_Block_cfgpred_block(bb, m));
2537                                                 }
2538                                         }
2539
2540                                         /* copies are not for free */
2541                                         ir_snprintf(buf, sizeof(buf), "copy_%N_%N", arg, spill->irn);
2542                                         var = lpp_add_var_default(si->lpp, buf, lpp_binary, opt_cost_spill * freq, 1.0);
2543
2544                                         for(m=n; m>=0; --m) {
2545                                                 const ir_node  *arg2 = get_irn_n(spill->irn, m);
2546
2547                                                 if(arg==arg2) {
2548                                                         op->attr.live_range.args.copies[m] = var;
2549                                                 }
2550                                         }
2551
2552 #if 0
2553                                         /* copy <= mem_in */
2554                                         ir_snprintf(buf, sizeof(buf), "nocopy_%N_%N", arg, spill->irn);
2555                                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2556                                         lpp_set_factor_fast(si->lpp, cst, var, 1.0);
2557                                         lpp_set_factor_fast(si->lpp, cst, spill->mem_in, -1.0);
2558 #endif
2559                                 }
2560                         }
2561                 }
2562         }
2563
2564         foreach_post_remat(bb, tmp) {
2565                 int         n;
2566                 op_t       *remat_op = get_irn_link(tmp);
2567                 pset       *remat_args = pset_new_ptr(get_irn_arity(tmp));
2568                 ir_node    *remat_arg;
2569
2570                 for (n=get_irn_arity(tmp)-1; n>=0; --n) {
2571                         remat_arg = get_irn_n(tmp, n);
2572
2573                         if(has_reg_class(si, remat_arg)) {
2574                                 pset_insert_ptr(remat_args, remat_arg);
2575                         }
2576                 }
2577
2578                 /* remat + \sum live_range(remat_arg) <= |args| */
2579                 ir_snprintf(buf, sizeof(buf), "one_must_die_%N", tmp);
2580                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, pset_count(remat_args));
2581                 lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2582
2583                 pset_foreach(remat_args, remat_arg) {
2584                         if(pset_find_ptr(live, remat_arg)) {
2585                                 op_t       *remat_arg_op = get_irn_link(remat_arg);
2586                                 lpp_set_factor_fast(si->lpp, cst, remat_arg_op->attr.live_range.ilp, 1.0);
2587                         }
2588                 }
2589                 del_pset(remat_args);
2590         }
2591
2592         foreach_post_remat(bb, tmp) {
2593                 int  n;
2594
2595                 for(n=get_irn_arity(tmp)-1; n>=0; --n) {
2596                         ir_node  *remat_arg = get_irn_n(tmp, n);
2597
2598                         /* if value is becoming live through use by remat2 */
2599                         if(has_reg_class(si, remat_arg) && !pset_find_ptr(live, remat_arg)) {
2600                                 op_t       *remat_arg_op = get_irn_link(remat_arg);
2601                                 ilp_cst_t   nomem;
2602
2603                                 DBG((si->dbg, LEVEL_3, "  value %+F becoming live through use by remat2 at bb start %+F\n", remat_arg, tmp));
2604
2605                                 pset_insert_ptr(live, remat_arg);
2606                                 spill = add_to_spill_bb(si, bb, remat_arg);
2607                                 remat_arg_op->attr.live_range.ilp = ILP_UNDEF;
2608
2609                                 /* we need reg_in and mem_in for this value; they will be referenced later */
2610                                 ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N", remat_arg, bb);
2611                                 spill->reg_in = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2612                                 ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N", remat_arg, bb);
2613                                 spill->mem_in = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
2614
2615
2616                                 /* optimization: all memory stuff should be 0, for we do not want to insert reloads for remats */
2617                                 ir_snprintf(buf, sizeof(buf), "nomem_%N_%N", remat_arg, bb);
2618                                 nomem = lpp_add_cst_uniq(si->lpp, buf, lpp_equal, 0.0);
2619                                 lpp_set_factor_fast(si->lpp, nomem, spill->spill, 1.0);
2620                         }
2621                 }
2622         }
2623
2624         /* L\U is empty at bb start */
2625         /* arg is live throughout epilog if it is reg_in into this block */
2626
2627         /* check the register pressure at the beginning of the block
2628          * including remats
2629          */
2630         /* reg_in entspricht post_use */
2631
2632         ir_snprintf(buf, sizeof(buf), "check_start_%N", bb);
2633         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, si->n_regs);
2634
2635         pset_foreach(live, irn) {
2636         ilp_cst_t  nospill;
2637
2638                 spill = set_find_spill(spill_bb->ilp, irn);
2639                 assert(spill);
2640
2641                 ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N", irn, bb);
2642                 spill->reg_in = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 0.0);
2643
2644                 lpp_set_factor_fast(si->lpp, cst, spill->reg_in, 1.0);
2645
2646                 /* spill + mem_in <= 1 */
2647                 ir_snprintf(buf, sizeof(buf), "nospill_%N_%N", irn, bb);
2648                 nospill = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1);
2649
2650                 lpp_set_factor_fast(si->lpp, nospill, spill->mem_in, 1.0);
2651                 lpp_set_factor_fast(si->lpp, nospill, spill->spill, 1.0);
2652
2653         } /* post_remats are NOT included in register pressure check because
2654            they do not increase regpressure */
2655
2656         /* mem_in/reg_in for live_in values, especially phis and their arguments */
2657         pset_foreach(live, irn) {
2658                 int          p = 0,
2659                                          n;
2660
2661                 spill = set_find_spill(spill_bb->ilp, irn);
2662                 assert(spill && spill->irn == irn);
2663
2664                 if(is_Phi(irn) && get_nodes_block(irn) == bb) {
2665                         for (n=get_Phi_n_preds(irn)-1; n>=0; --n) {
2666                                 ilp_cst_t       mem_in,
2667                                                                 reg_in;
2668                                 ir_node        *phi_arg = get_Phi_pred(irn, n);
2669                                 ir_node        *bb_p = get_Block_cfgpred_block(bb, n);
2670                                 spill_bb_t     *spill_bb_p = get_irn_link(bb_p);
2671                                 spill_t        *spill_p;
2672                                 op_t           *op = get_irn_link(irn);
2673
2674                                 /* although the phi is in the right regclass one or more of
2675                                  * its arguments can be in a different one or at least to
2676                                  * ignore
2677                                  */
2678                                 if(has_reg_class(si, phi_arg)) {
2679                                         /* mem_in < mem_out_arg + copy */
2680                                         ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N-%d", irn, bb, p);
2681                                         mem_in = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2682
2683                                         /* reg_in < reg_out_arg */
2684                                         ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N-%d", irn, bb, p++);
2685                                         reg_in = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2686
2687                                         lpp_set_factor_fast(si->lpp, mem_in, spill->mem_in, 1.0);
2688                                         lpp_set_factor_fast(si->lpp, reg_in, spill->reg_in, 1.0);
2689
2690                                         spill_p = set_find_spill(spill_bb_p->ilp, phi_arg);
2691                                         assert(spill_p);
2692
2693                                         lpp_set_factor_fast(si->lpp, mem_in, spill_p->mem_out, -1.0);
2694                                         if(opt_memcopies)
2695                                                 lpp_set_factor_fast(si->lpp, mem_in, op->attr.live_range.args.copies[n], -1.0);
2696
2697                                         lpp_set_factor_fast(si->lpp, reg_in, spill_p->reg_out, -1.0);
2698                                 }
2699                         }
2700                 } else {
2701                         /* else assure the value arrives on all paths in the same resource */
2702
2703                         for (n=get_Block_n_cfgpreds(bb)-1; n>=0; --n) {
2704                                 ilp_cst_t       mem_in,
2705                                                                 reg_in;
2706                                 ir_node        *bb_p = get_Block_cfgpred_block(bb, n);
2707                                 spill_bb_t     *spill_bb_p = get_irn_link(bb_p);
2708                                 spill_t        *spill_p;
2709
2710                                 ir_snprintf(buf, sizeof(buf), "mem_in_%N_%N-%d", irn, bb, p);
2711                                 mem_in = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2712                                 ir_snprintf(buf, sizeof(buf), "reg_in_%N_%N-%d", irn, bb, p++);
2713                                 reg_in = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2714
2715                                 lpp_set_factor_fast(si->lpp, mem_in, spill->mem_in, 1.0);
2716                                 lpp_set_factor_fast(si->lpp, reg_in, spill->reg_in, 1.0);
2717
2718                                 spill_p = set_find_spill(spill_bb_p->ilp, irn);
2719                                 assert(spill_p);
2720
2721                                 lpp_set_factor_fast(si->lpp, mem_in, spill_p->mem_out, -1.0);
2722                                 lpp_set_factor_fast(si->lpp, reg_in, spill_p->reg_out, -1.0);
2723                         }
2724                 }
2725         }
2726
2727         foreach_post_remat(bb, tmp) {
2728                 int         n;
2729
2730                 for (n=get_irn_arity(tmp)-1; n>=0; --n) {
2731                         ir_node    *remat_arg = get_irn_n(tmp, n);
2732                         op_t       *remat_op = get_irn_link(tmp);
2733
2734                         if(!has_reg_class(si, remat_arg)) continue;
2735
2736                         spill = set_find_spill(spill_bb->ilp, remat_arg);
2737                         assert(spill);
2738
2739                         ir_snprintf(buf, sizeof(buf), "req_remat2_%N_%N_arg_%N", tmp, bb, remat_arg);
2740                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
2741                         lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
2742                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2743                 }
2744         }
2745
2746         pset_foreach(live, irn) {
2747                 const op_t      *op = get_irn_link(irn);
2748                 const ir_node   *remat;
2749                 int              n_remats = 0;
2750
2751                 cst = ILP_UNDEF;
2752
2753                 foreach_post_remat(bb, remat) {
2754                         int   n;
2755
2756                         for (n=get_irn_arity(remat)-1; n>=0; --n) {
2757                                 const ir_node  *arg = get_irn_n(remat, n);
2758
2759                                 if(arg == irn) {
2760                                         const op_t   *remat_op = get_irn_link(remat);
2761
2762                                         if(cst == ILP_UNDEF) {
2763                                                 /* sum remat2s <= 1 + n_remats*live_range */
2764                                                 ir_snprintf(buf, sizeof(buf), "dying_lr_%N_%N", irn, bb);
2765                                                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1.0);
2766                                         }
2767                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, 1.0);
2768                                         ++n_remats;
2769                                         break;
2770                                 }
2771                         }
2772                 }
2773                 if(cst != ILP_UNDEF && op->attr.live_range.ilp != ILP_UNDEF) {
2774                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, -n_remats);
2775                 }
2776         }
2777
2778         /* first live ranges from reg_ins */
2779         pset_foreach(live, irn) {
2780                 op_t      *op = get_irn_link(irn);
2781
2782                 if(op->attr.live_range.ilp != ILP_UNDEF) {
2783
2784                         spill = set_find_spill(spill_bb->ilp, irn);
2785                         assert(spill && spill->irn == irn);
2786
2787                         ir_snprintf(buf, sizeof(buf), "first_lr_%N_%N", irn, bb);
2788                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2789                         lpp_set_factor_fast(si->lpp, cst, op->attr.live_range.ilp, 1.0);
2790                         lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
2791
2792                         foreach_post_remat(bb, tmp) {
2793                                 op_t     *remat_op = get_irn_link(tmp);
2794
2795                                 if(remat_op->attr.remat.remat->value == irn) {
2796                                         lpp_set_factor_fast(si->lpp, cst, remat_op->attr.remat.ilp, -1.0);
2797                                 }
2798                         }
2799                 }
2800         }
2801
2802         /* walk forward now and compute constraints for placing spills */
2803         /* this must only be done for values that are not defined in this block */
2804         pset_foreach(live, irn) {
2805                 /*
2806                  * if value is defined in this block we can anways place the spill directly after the def
2807                  *    -> no constraint necessary
2808                  */
2809                 if(!is_Phi(irn) && get_nodes_block(irn) == bb) {
2810                         assert(0);
2811                 }
2812
2813
2814                 spill = set_find_spill(spill_bb->ilp, irn);
2815                 assert(spill);
2816
2817                 ir_snprintf(buf, sizeof(buf), "req_spill_%N_%N", irn, bb);
2818                 cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0.0);
2819
2820                 lpp_set_factor_fast(si->lpp, cst, spill->spill, 1.0);
2821                 if(is_diverge_edge(bb)) lpp_set_factor_fast(si->lpp, cst, spill->reg_in, -1.0);
2822
2823                 if(!is_Phi(irn)) {
2824                         sched_foreach_op(bb, tmp) {
2825                                 op_t   *op = get_irn_link(tmp);
2826
2827                                 if(is_Phi(tmp)) continue;
2828                                 assert(!is_Proj(tmp));
2829
2830                                 if(op->is_remat) {
2831                                         const ir_node   *value = op->attr.remat.remat->value;
2832
2833                                         if(value == irn) {
2834                                                 /* only collect remats up to the first real use of a value */
2835                                                 lpp_set_factor_fast(si->lpp, cst, op->attr.remat.ilp, -1.0);
2836                                         }
2837                                 } else {
2838                                         int   n;
2839
2840                                         for (n=get_irn_arity(tmp)-1; n>=0; --n) {
2841                                                 ir_node    *arg = get_irn_n(tmp, n);
2842
2843                                                 if(arg == irn) {
2844                                                         /* if a value is used stop collecting remats */
2845                             goto next_live;
2846                                                 }
2847                                         }
2848                                 }
2849                         }
2850                 }
2851 next_live: ;
2852         }
2853
2854         del_pset(live);
2855 }
2856
2857 typedef struct _irnlist_t {
2858         struct list_head   list;
2859         ir_node           *irn;
2860 } irnlist_t;
2861
2862 typedef struct _interference_t {
2863         struct list_head    blocklist;
2864         ir_node            *a;
2865         ir_node            *b;
2866 } interference_t;
2867
2868 static int
2869 cmp_interference(const void *a, const void *b, size_t size)
2870 {
2871         const interference_t *p = a;
2872         const interference_t *q = b;
2873
2874         return !(p->a == q->a && p->b == q->b);
2875 }
2876
2877 static interference_t *
2878 set_find_interference(set * set, ir_node * a, ir_node * b)
2879 {
2880         interference_t     query;
2881
2882         query.a = (a>b)?a:b;
2883         query.b = (a>b)?b:a;
2884
2885         return set_find(set, &query, sizeof(query), HASH_PTR(PTR_TO_INT(a) ^ PTR_TO_INT(b)));
2886 }
2887
2888 static interference_t *
2889 set_insert_interference(spill_ilp_t * si, set * set, ir_node * a, ir_node * b, ir_node * bb)
2890 {
2891         interference_t     query,
2892                                           *result;
2893         irnlist_t         *list = obstack_alloc(si->obst, sizeof(*list));
2894
2895         list->irn = bb;
2896
2897         result = set_find_interference(set, a, b);
2898         if(result) {
2899
2900                 list_add(&list->list, &result->blocklist);
2901                 return result;
2902         }
2903
2904         query.a = (a>b)?a:b;
2905         query.b = (a>b)?b:a;
2906
2907         result = set_insert(set, &query, sizeof(query), HASH_PTR(PTR_TO_INT(a) ^ PTR_TO_INT(b)));
2908
2909         INIT_LIST_HEAD(&result->blocklist);
2910         list_add(&list->list, &result->blocklist);
2911
2912         return result;
2913 }
2914
2915 static
2916 int values_interfere_in_block(const spill_ilp_t *si, const ir_node *bb, const ir_node *a, const ir_node *b)
2917 {
2918         const ir_edge_t *edge;
2919
2920         if (get_nodes_block(a) != bb && get_nodes_block(b) != bb) {
2921                 /* both values are live in, so they interfere */
2922                 return 1;
2923         }
2924
2925         /* ensure a dominates b */
2926         if (value_dominates(b, a)) {
2927                 const ir_node *t;
2928                 t = b;
2929                 b = a;
2930                 a = t;
2931         }
2932         assert(get_nodes_block(b) == bb && "at least b should be defined here in this block");
2933
2934
2935         /* the following code is stolen from bera.c */
2936         if (be_is_live_end(si->lv, bb, a))
2937                 return 1;
2938
2939         foreach_out_edge(a, edge) {
2940                 const ir_node *user = edge->src;
2941                 if (get_nodes_block(user) == bb
2942                                 && ! is_Phi(user)
2943                                 && b != user
2944                                 && ! pset_find_ptr(si->inverse_ops, user)
2945                                 && value_dominates(b, user))
2946                         return 1;
2947         }
2948
2949         return 0;
2950 }
2951
2952 /**
2953  * Walk all irg blocks and collect interfering values inside of phi classes
2954  */
2955 static void
2956 luke_interferencewalker(ir_node * bb, void * data)
2957 {
2958         spill_ilp_t    *si = (spill_ilp_t*)data;
2959         int             l1, l2;
2960
2961         be_lv_foreach(si->lv, bb, be_lv_state_end | be_lv_state_out | be_lv_state_in, l1) {
2962                 ir_node        *a = be_lv_get_irn(si->lv, bb, l1);
2963                 op_t           *a_op = get_irn_link(a);
2964
2965
2966                 /* a is only interesting if it is in my register class and if it is inside a phi class */
2967                 if (has_reg_class(si, a) && get_phi_class(si->pc, a)) {
2968                         if (a_op->is_remat || pset_find_ptr(si->inverse_ops, a))
2969                                 continue;
2970
2971                         for (l2 = _be_lv_next_irn(si->lv, bb, 0xff, l1 + 1); l2 >= 0; l2 = _be_lv_next_irn(si->lv, bb, 0xff, l2 + 1)) {
2972                                 ir_node *b    = be_lv_get_irn(si->lv, bb, l2);
2973                                 op_t    *b_op = get_irn_link(b);
2974
2975                                 /* a and b are only interesting if they are in the same phi class */
2976                                 if (has_reg_class(si, b) && get_phi_class(si->pc, a) == get_phi_class(si->pc, b)) {
2977                                         if (b_op->is_remat || pset_find_ptr(si->inverse_ops, b))
2978                                                 continue;
2979
2980                                         if (values_interfere_in_block(si, bb, a, b)) {
2981                                                 DBG((si->dbg, LEVEL_4, "\tvalues interfere in %+F: %+F, %+F\n", bb, a, b));
2982                                                 set_insert_interference(si, si->interferences, a, b, bb);
2983                                         }
2984                                 }
2985                         }
2986                 }
2987         }
2988 }
2989
2990 static unsigned int copy_path_id = 0;
2991
2992 static void
2993 write_copy_path_cst(spill_ilp_t *si, pset * copies, ilp_var_t any_interfere)
2994 {
2995         ilp_cst_t  cst;
2996         ilp_var_t  copy;
2997         char       buf[256];
2998         void      *ptr;
2999
3000         ir_snprintf(buf, sizeof(buf), "copy_path-%d", copy_path_id++);
3001         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0);
3002
3003         lpp_set_factor_fast(si->lpp, cst, any_interfere, 1.0);
3004
3005         pset_foreach(copies, ptr) {
3006                 copy = PTR_TO_INT(ptr);
3007                 lpp_set_factor_fast(si->lpp, cst, copy, -1.0);
3008         }
3009 }
3010
3011 /**
3012  * @parameter copies   contains a path of copies which lead us to irn
3013  * @parameter visited  contains a set of nodes already visited on this path
3014  */
3015 static int
3016 find_copy_path(spill_ilp_t * si, const ir_node * irn, const ir_node * target, ilp_var_t any_interfere, pset * copies, pset * visited)
3017 {
3018         const ir_edge_t *edge;
3019         op_t            *op = get_irn_link(irn);
3020     pset            *visited_users = pset_new_ptr_default();
3021         int              paths = 0;
3022
3023         if(op->is_remat) return 0;
3024
3025         pset_insert_ptr(visited, irn);
3026
3027         if(is_Phi(irn)) {
3028                 int    n;
3029         pset  *visited_operands = pset_new_ptr(get_irn_arity(irn));
3030
3031                 /* visit all operands */
3032                 for(n=get_irn_arity(irn)-1; n>=0; --n) {
3033                         ir_node  *arg = get_irn_n(irn, n);
3034                         ilp_var_t  copy = op->attr.live_range.args.copies[n];
3035
3036                         if(!has_reg_class(si, arg)) continue;
3037             if(pset_find_ptr(visited_operands, arg)) continue;
3038             pset_insert_ptr(visited_operands, arg);
3039
3040                         if(arg == target) {
3041                                 if(++paths > MAX_PATHS && pset_count(copies) != 0) {
3042                                         del_pset(visited_operands);
3043                                         del_pset(visited_users);
3044                                         pset_remove_ptr(visited, irn);
3045                                         return paths;
3046                                 }
3047                                 pset_insert(copies, INT_TO_PTR(copy), copy);
3048                                 write_copy_path_cst(si, copies, any_interfere);
3049                                 pset_remove(copies, INT_TO_PTR(copy), copy);
3050                         } else if(!pset_find_ptr(visited, arg)) {
3051                                 pset_insert(copies, INT_TO_PTR(copy), copy);
3052                                 paths += find_copy_path(si, arg, target, any_interfere, copies, visited);
3053                                 pset_remove(copies, INT_TO_PTR(copy), copy);
3054
3055                 if(paths > MAX_PATHS) {
3056                     if(pset_count(copies) == 0) {
3057                         ilp_cst_t  cst;
3058                         char       buf[256];
3059
3060                         ir_snprintf(buf, sizeof(buf), "always_copy-%d-%d", any_interfere, copy);
3061                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_equal, 0);
3062                         lpp_set_factor_fast(si->lpp, cst, any_interfere, -1.0);
3063                         lpp_set_factor_fast(si->lpp, cst, copy, 1.0);
3064                         DBG((si->dbg, LEVEL_1, "ALWAYS COPYING %d FOR INTERFERENCE %d\n", copy, any_interfere));
3065
3066                         paths = 0;
3067                     } else {
3068                         del_pset(visited_operands);
3069                         del_pset(visited_users);
3070                         pset_remove_ptr(visited, irn);
3071                         return paths;
3072                     }
3073                 } else if(pset_count(copies) == 0) {
3074                                         paths = 0;
3075                                 }
3076                         }
3077                 }
3078
3079         del_pset(visited_operands);
3080         }
3081
3082         /* visit all uses which are phis */
3083         foreach_out_edge(irn, edge) {
3084                 ir_node  *user = edge->src;
3085                 int       pos  = edge->pos;
3086                 op_t     *op = get_irn_link(user);
3087                 ilp_var_t copy;
3088
3089                 if(!is_Phi(user)) continue;
3090                 if(!has_reg_class(si, user)) continue;
3091         if(pset_find_ptr(visited_users, user)) continue;
3092         pset_insert_ptr(visited_users, user);
3093
3094                 copy = op->attr.live_range.args.copies[pos];
3095
3096                 if(user == target) {
3097                         if(++paths > MAX_PATHS && pset_count(copies) != 0) {
3098                                 del_pset(visited_users);
3099                                 pset_remove_ptr(visited, irn);
3100                                 return paths;
3101                         }
3102                         pset_insert(copies, INT_TO_PTR(copy), copy);
3103                         write_copy_path_cst(si, copies, any_interfere);
3104                         pset_remove(copies, INT_TO_PTR(copy), copy);
3105                 } else if(!pset_find_ptr(visited, user)) {
3106                         pset_insert(copies, INT_TO_PTR(copy), copy);
3107                         paths += find_copy_path(si, user, target, any_interfere, copies, visited);
3108                         pset_remove(copies, INT_TO_PTR(copy), copy);
3109
3110             if(paths > MAX_PATHS) {
3111                 if(pset_count(copies) == 0) {
3112                     ilp_cst_t  cst;
3113                     char       buf[256];
3114
3115                     ir_snprintf(buf, sizeof(buf), "always_copy-%d-%d", any_interfere, copy);
3116                     cst = lpp_add_cst_uniq(si->lpp, buf, lpp_equal, 0);
3117                     lpp_set_factor_fast(si->lpp, cst, any_interfere, -1.0);
3118                     lpp_set_factor_fast(si->lpp, cst, copy, 1.0);
3119                     DBG((si->dbg, LEVEL_1, "ALWAYS COPYING %d FOR INTERFERENCE %d\n", copy, any_interfere));
3120
3121                     paths = 0;
3122                 } else {
3123                     del_pset(visited_users);
3124                     pset_remove_ptr(visited, irn);
3125                     return paths;
3126                 }
3127             } else if(pset_count(copies) == 0) {
3128                                 paths = 0;
3129                         }
3130                 }
3131         }
3132
3133     del_pset(visited_users);
3134         pset_remove_ptr(visited, irn);
3135         return paths;
3136 }
3137
3138 static void
3139 gen_copy_constraints(spill_ilp_t * si, const ir_node * a, const ir_node * b, ilp_var_t any_interfere)
3140 {
3141         pset * copies = pset_new_ptr_default();
3142         pset * visited = pset_new_ptr_default();
3143
3144         find_copy_path(si, a, b, any_interfere, copies, visited);
3145
3146         del_pset(visited);
3147         del_pset(copies);
3148 }
3149
3150
3151 static void
3152 memcopyhandler(spill_ilp_t * si)
3153 {
3154         interference_t   *interference;
3155         char              buf[256];
3156         /* teste Speicherwerte auf Interferenz */
3157
3158         DBG((si->dbg, LEVEL_2, "\t calling interferencewalker\n"));
3159         irg_block_walk_graph(si->birg->irg, luke_interferencewalker, NULL, si);
3160
3161         /* now lets emit the ILP unequations for the crap */
3162         set_foreach(si->interferences, interference) {
3163                 irnlist_t      *irnlist;
3164                 ilp_var_t      interfere, any_interfere;
3165                 ilp_cst_t      any_interfere_cst, cst;
3166                 const ir_node  *a  = interference->a;
3167                 const ir_node  *b  = interference->b;
3168
3169                 /* any_interf <= \sum interf */
3170                 ir_snprintf(buf, sizeof(buf), "interfere_%N_%N", a, b);
3171                 any_interfere_cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0);
3172                 any_interfere     = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
3173
3174                 lpp_set_factor_fast(si->lpp, any_interfere_cst, any_interfere, 1.0);
3175
3176                 list_for_each_entry(irnlist_t, irnlist, &interference->blocklist, list) {
3177                         const ir_node  *bb = irnlist->irn;
3178                         spill_bb_t     *spill_bb = get_irn_link(bb);
3179                         spill_t        *spilla,
3180                                                    *spillb;
3181                         char           buf[256];
3182
3183                         spilla = set_find_spill(spill_bb->ilp, a);
3184                         assert(spilla);
3185
3186                         spillb = set_find_spill(spill_bb->ilp, b);
3187                         assert(spillb);
3188
3189                         /* interfere <-> (mem_in_a or spill_a) and (mem_in_b or spill_b): */
3190                         /* 1:   mem_in_a + mem_in_b + spill_a + spill_b - interfere <= 1 */
3191                         /* 2: - mem_in_a - spill_a + interfere <= 0 */
3192                         /* 3: - mem_in_b - spill_b + interfere <= 0 */
3193                         ir_snprintf(buf, sizeof(buf), "interfere_%N_%N_%N", bb, a, b);
3194                         interfere = lpp_add_var_default(si->lpp, buf, lpp_binary, 0.0, 1.0);
3195
3196                         ir_snprintf(buf, sizeof(buf), "interfere_%N_%N_%N-1", bb, a, b);
3197                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 1);
3198
3199                         lpp_set_factor_fast(si->lpp, cst, interfere, -1.0);
3200                         if(spilla->mem_in != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, spilla->mem_in, 1.0);
3201                         lpp_set_factor_fast(si->lpp, cst, spilla->spill, 1.0);
3202                         if(spillb->mem_in != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, spillb->mem_in, 1.0);
3203                         lpp_set_factor_fast(si->lpp, cst, spillb->spill, 1.0);
3204
3205                         ir_snprintf(buf, sizeof(buf), "interfere_%N_%N_%N-2", bb, a, b);
3206                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0);
3207
3208                         lpp_set_factor_fast(si->lpp, cst, interfere, 1.0);
3209                         if(spilla->mem_in != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, spilla->mem_in, -1.0);
3210                         lpp_set_factor_fast(si->lpp, cst, spilla->spill, -1.0);
3211
3212                         ir_snprintf(buf, sizeof(buf), "interfere_%N_%N_%N-3", bb, a, b);
3213                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0);
3214
3215                         lpp_set_factor_fast(si->lpp, cst, interfere, 1.0);
3216                         if(spillb->mem_in != ILP_UNDEF) lpp_set_factor_fast(si->lpp, cst, spillb->mem_in, -1.0);
3217                         lpp_set_factor_fast(si->lpp, cst, spillb->spill, -1.0);
3218
3219
3220                         lpp_set_factor_fast(si->lpp, any_interfere_cst, interfere, -1.0);
3221
3222                         /* any_interfere >= interf */
3223                         ir_snprintf(buf, sizeof(buf), "interfere_%N_%N-%N", a, b, bb);
3224                         cst = lpp_add_cst_uniq(si->lpp, buf, lpp_less, 0);
3225
3226                         lpp_set_factor_fast(si->lpp, cst, interfere, 1.0);
3227                         lpp_set_factor_fast(si->lpp, cst, any_interfere, -1.0);
3228                 }
3229
3230                 /* now that we know whether the two values interfere in memory we can drop constraints to enforce copies */
3231                 gen_copy_constraints(si,a,b,any_interfere);
3232         }
3233 }
3234
3235
3236 static INLINE int
3237 is_zero(double x)
3238 {
3239         return fabs(x) < 0.00001;
3240 }
3241
3242 static int mark_remat_nodes_hook(FILE *F, ir_node *n, ir_node *l)
3243 {
3244         spill_ilp_t *si = get_irg_link(current_ir_graph);
3245
3246         if(pset_find_ptr(si->all_possible_remats, n)) {
3247                 op_t   *op = (op_t*)get_irn_link(n);
3248                 assert(op && op->is_remat);
3249
3250                 if(!op->attr.remat.remat->inverse) {
3251                         if(op->attr.remat.pre) {
3252                                 ir_fprintf(F, "color:red info3:\"remat value: %+F\"", op->attr.remat.remat->value);
3253                         } else {
3254                                 ir_fprintf(F, "color:orange info3:\"remat2 value: %+F\"", op->attr.remat.remat->value);
3255                         }
3256
3257                         return 1;
3258                 } else {
3259                         op_t   *op = (op_t*)get_irn_link(n);
3260                         assert(op && op->is_remat);
3261
3262                         if(op->attr.remat.pre) {
3263                                 ir_fprintf(F, "color:cyan info3:\"remat inverse value: %+F\"", op->attr.remat.remat->value);
3264                         } else {
3265                                 ir_fprintf(F, "color:lightcyan info3:\"remat2 inverse value: %+F\"", op->attr.remat.remat->value);
3266                         }
3267
3268                         return 1;
3269                 }
3270         }
3271
3272         return 0;
3273 }
3274
3275 static void
3276 dump_graph_with_remats(ir_graph * irg, const char * suffix)
3277 {
3278         set_dump_node_vcgattr_hook(mark_remat_nodes_hook);
3279         be_dump(irg, suffix, dump_ir_block_graph_sched);
3280         set_dump_node_vcgattr_hook(NULL);
3281 }
3282
3283 /**
3284  * Edge hook to dump the schedule edges with annotated register pressure.
3285  */
3286 static int
3287 sched_pressure_edge_hook(FILE *F, ir_node *irn)
3288 {
3289         if(sched_is_scheduled(irn) && sched_has_prev(irn)) {
3290                 ir_node *prev = sched_prev(irn);
3291                 fprintf(F, "edge:{sourcename:\"");
3292                 PRINT_NODEID(irn);
3293                 fprintf(F, "\" targetname:\"");
3294                 PRINT_NODEID(prev);
3295                 fprintf(F, "\" label:\"%d", (int)get_irn_link(irn));
3296                 fprintf(F, "\" color:magenta}\n");
3297         }
3298         return 1;
3299 }
3300
3301 static void
3302 dump_ir_block_graph_sched_pressure(ir_graph *irg, const char *suffix)
3303 {
3304         DUMP_NODE_EDGE_FUNC old_edge_hook = get_dump_node_edge_hook();
3305
3306         dump_consts_local(0);
3307         set_dump_node_edge_hook(sched_pressure_edge_hook);
3308         dump_ir_block_graph(irg, suffix);
3309         set_dump_node_edge_hook(old_edge_hook);
3310 }
3311
3312 static void
3313 walker_pressure_annotator(ir_node * bb, void * data)
3314 {
3315         spill_ilp_t  *si = data;
3316         ir_node      *irn;
3317         int           n, i;
3318         pset         *live = pset_new_ptr_default();
3319         int           projs = 0;
3320
3321         be_lv_foreach(si->lv, bb, be_lv_state_end, i) {
3322                 irn = be_lv_get_irn(si->lv, bb, i);
3323
3324                 if (has_reg_class(si, irn)) {
3325                         pset_insert_ptr(live, irn);
3326                 }
3327         }
3328
3329         set_irn_link(bb, INT_TO_PTR(pset_count(live)));
3330
3331         sched_foreach_reverse(bb, irn) {
3332                 if(is_Phi(irn)) {
3333                         set_irn_link(irn, INT_TO_PTR(pset_count(live)));
3334                         continue;
3335                 }
3336
3337                 if(has_reg_class(si, irn)) {
3338                         pset_remove_ptr(live, irn);
3339                         if(is_Proj(irn)) ++projs;
3340                 }
3341
3342                 if(!is_Proj(irn)) projs = 0;
3343
3344                 for (n=get_irn_arity(irn)-1; n>=0; --n) {
3345                         ir_node    *arg = get_irn_n(irn, n);
3346
3347                         if(has_reg_class(si, arg)) pset_insert_ptr(live, arg);
3348                 }
3349                 set_irn_link(irn, INT_TO_PTR(pset_count(live)+projs));
3350         }
3351
3352         del_pset(live);
3353 }
3354
3355 static void
3356 dump_pressure_graph(spill_ilp_t * si, const char *suffix)
3357 {
3358         be_dump(si->birg->irg, suffix, dump_ir_block_graph_sched_pressure);
3359 }
3360
3361 static void
3362 connect_all_remats_with_keep(spill_ilp_t * si)
3363 {
3364         ir_node   *irn;
3365         ir_node  **ins,
3366                          **pos;
3367         int        n_remats;
3368
3369
3370         n_remats = pset_count(si->all_possible_remats);
3371         if(n_remats) {
3372                 ins = obstack_alloc(si->obst, n_remats * sizeof(*ins));
3373
3374                 pos = ins;
3375                 pset_foreach(si->all_possible_remats, irn) {
3376                         *pos = irn;
3377                         ++pos;
3378                 }
3379
3380                 si->keep = be_new_Keep(si->cls, si->birg->irg, get_irg_end_block(si->birg->irg), n_remats, ins);
3381
3382                 obstack_free(si->obst, ins);
3383         }
3384 }
3385
3386 static void
3387 connect_all_spills_with_keep(spill_ilp_t * si)
3388 {
3389         ir_node   *irn;
3390         ir_node  **ins,
3391                          **pos;
3392         int        n_spills;
3393         ir_node   *keep;
3394
3395
3396         n_spills = pset_count(si->spills);
3397         if(n_spills) {
3398                 ins = obstack_alloc(si->obst, n_spills * sizeof(*ins));
3399
3400                 pos = ins;
3401                 pset_foreach(si->spills, irn) {
3402                         *pos = irn;
3403                         ++pos;
3404                 }
3405
3406                 keep = be_new_Keep(si->cls, si->birg->irg, get_irg_end_block(si->birg->irg), n_spills, ins);
3407
3408                 obstack_free(si->obst, ins);
3409         }
3410 }
3411
3412 /** insert a spill at an arbitrary position */
3413 ir_node *be_spill2(const arch_env_t *arch_env, ir_node *irn, ir_node *insert)
3414 {
3415         ir_node  *bl    = is_Block(insert) ? insert : get_nodes_block(insert);
3416         ir_graph *irg   = get_irn_irg(bl);
3417         ir_node  *frame = get_irg_frame(irg);
3418         ir_node  *spill;
3419         ir_node  *next;
3420         const arch_register_class_t *cls       = arch_get_irn_reg_class(arch_env, irn, -1);
3421         const arch_register_class_t *cls_frame = arch_get_irn_reg_class(arch_env, frame, -1);
3422
3423         spill = be_new_Spill(cls, cls_frame, irg, bl, frame, irn);
3424
3425         /*
3426          * search the right insertion point. a spill of a phi cannot be put
3427          * directly after the phi, if there are some phis behind the one which
3428          * is spilled. Also, a spill of a Proj must be after all Projs of the
3429          * same tuple node.
3430          *
3431          * Here's one special case:
3432          * If the spill is in the start block, the spill must be after the frame
3433          * pointer is set up. This is done by setting insert to the end of the block
3434          * which is its default initialization (see above).
3435          */
3436
3437         if (bl == get_irg_start_block(irg) && sched_get_time_step(frame) >= sched_get_time_step(insert))
3438                 insert = frame;
3439
3440         for (next = sched_next(insert); is_Phi(next) || is_Proj(next); next = sched_next(insert))
3441                 insert = next;
3442
3443         sched_add_after(insert, spill);
3444         return spill;
3445 }
3446
3447 static void
3448 delete_remat(spill_ilp_t * si, ir_node * remat) {
3449         int       n;
3450         ir_node  *bad = get_irg_bad(si->birg->irg);
3451
3452         sched_remove(remat);
3453
3454         /* kill links to operands */
3455         for (n=get_irn_arity(remat)-1; n>=-1; --n) {
3456                 set_irn_n(remat, n, bad);
3457         }
3458 }
3459
3460 static void
3461 clean_remat_info(spill_ilp_t * si)
3462 {
3463         int            n;
3464         remat_t       *remat;
3465         remat_info_t  *remat_info;
3466         ir_node       *bad = get_irg_bad(si->birg->irg);
3467
3468         set_foreach(si->remat_info, remat_info) {
3469                 if(!remat_info->remats) continue;
3470
3471                 pset_foreach(remat_info->remats, remat)
3472                 {
3473                         if(remat->proj && get_irn_n_edges(remat->proj) == 0) {
3474                                 if(sched_is_scheduled(remat->proj)) {
3475                                         sched_remove((ir_node*)remat->proj);
3476                                 }
3477                                 set_irn_n((ir_node*)remat->proj, -1, bad);
3478                                 set_irn_n((ir_node*)remat->proj, 0, bad);
3479                         }
3480
3481                         if(get_irn_n_edges(remat->op) == 0) {
3482                                 if(sched_is_scheduled(remat->op)) {
3483                                         sched_remove((ir_node*)remat->op);
3484                                 }
3485                                 for (n=get_irn_arity(remat->op)-1; n>=-1; --n) {
3486                                         set_irn_n((ir_node*)remat->op, n, bad);
3487                                 }
3488                         }
3489                 }
3490
3491                 if(remat_info->remats) del_pset(remat_info->remats);
3492                 if(remat_info->remats_by_operand) del_pset(remat_info->remats_by_operand);
3493         }
3494 }
3495
3496 static void
3497 delete_unnecessary_remats(spill_ilp_t * si)
3498 {
3499         if(opt_keep_alive & KEEPALIVE_REMATS) {
3500                 int       n;
3501                 ir_node  *bad = get_irg_bad(si->birg->irg);
3502
3503                 if(si->keep) {
3504                         for (n=get_irn_arity(si->keep)-1; n>=0; --n) {
3505                                 ir_node        *keep_arg = get_irn_n(si->keep, n);
3506                                 op_t           *arg_op = get_irn_link(keep_arg);
3507                                 lpp_name_t     *name;
3508
3509                                 assert(arg_op->is_remat);
3510
3511                                 name = si->lpp->vars[arg_op->attr.remat.ilp];
3512
3513                                 if(is_zero(name->value)) {
3514                                         DBG((si->dbg, LEVEL_3, "\t  deleting remat %+F\n", keep_arg));
3515                                         /* TODO check whether reload is preferred over remat (could be bug) */
3516                                         delete_remat(si, keep_arg);
3517                                 } else {
3518                                         if(!arg_op->attr.remat.remat->inverse) {
3519                                                 if(arg_op->attr.remat.pre) {
3520                                                         DBG((si->dbg, LEVEL_2, "\t**remat kept: %+F\n", keep_arg));
3521                                                 } else {
3522                                                         DBG((si->dbg, LEVEL_2, "\t%%%%remat2 kept: %+F\n", keep_arg));
3523                                                 }
3524                                         } else {
3525                                                 if(arg_op->attr.remat.pre) {
3526                                                         DBG((si->dbg, LEVEL_2, "\t**INVERSE remat kept: %+F\n", keep_arg));
3527                                                 } else {
3528                                                         DBG((si->dbg, LEVEL_2, "\t%%%%INVERSE remat2 kept: %+F\n", keep_arg));
3529                                                 }
3530                                         }
3531                                 }
3532
3533                                 set_irn_n(si->keep, n, bad);
3534                         }
3535                 } else {
3536                         DBG((si->dbg, LEVEL_2, "\t  no remats to delete (none have been inserted)\n"));
3537                 }
3538         } else {
3539                 ir_node  *remat;
3540
3541                 pset_foreach(si->all_possible_remats, remat) {
3542                         op_t           *remat_op = get_irn_link(remat);
3543                         lpp_name_t     *name = si->lpp->vars[remat_op->attr.remat.ilp];
3544
3545                         if(is_zero(name->value)) {
3546                                 DBG((si->dbg, LEVEL_3, "\t  deleting remat %+F\n", remat));
3547                                 /* TODO check whether reload is preferred over remat (could be bug) */
3548                                 delete_remat(si, remat);
3549                         } else {
3550                                 if(!remat_op->attr.remat.remat->inverse) {
3551                                         if(remat_op->attr.remat.pre) {
3552                                                 DBG((si->dbg, LEVEL_2, "\t**remat kept: %+F\n", remat));
3553                                         } else {
3554                                                 DBG((si->dbg, LEVEL_2, "\t%%%%remat2 kept: %+F\n", remat));
3555                                         }
3556                                 } else {
3557                                         if(remat_op->attr.remat.pre) {
3558                                                 DBG((si->dbg, LEVEL_2, "\t**INVERSE remat kept: %+F\n", remat));
3559                                         } else {
3560                                                 DBG((si->dbg, LEVEL_2, "\t%%%%INVERSE remat2 kept: %+F\n", remat));
3561                                         }
3562                                 }
3563                         }
3564                 }
3565         }
3566 }
3567
3568 static pset *
3569 get_spills_for_value(spill_ilp_t * si, const ir_node * value)
3570 {
3571         pset     *spills = pset_new_ptr_default();
3572
3573         const ir_node  *next;
3574         defs_t         *defs;
3575
3576         defs = set_find_def(si->values, value);
3577
3578         if(defs && defs->spills) {
3579                 for(next = defs->spills; next; next = get_irn_link(next)) {
3580                         pset_insert_ptr(spills, next);
3581                 }
3582         }
3583
3584         return spills;
3585 }
3586
3587 static ir_node *
3588 new_r_PhiM_nokeep(ir_graph * irg, ir_node *block, int arity, ir_node **in)
3589 {
3590         ir_node  *res;
3591
3592         assert( get_irn_arity(block) == arity );
3593
3594         res = new_ir_node(NULL, irg, block, op_Phi, mode_M, arity, in);
3595         res->attr.phi_backedge = new_backedge_arr(irg->obst, arity);
3596
3597         return res;
3598 }
3599
3600 /**
3601  * @param before   The node after which the spill will be placed in the schedule
3602  */
3603 static ir_node *
3604 insert_spill(spill_ilp_t * si, ir_node * irn, const ir_node * value, ir_node * before)
3605 {
3606         defs_t   *defs;
3607         ir_node  *spill;
3608         const arch_env_t *arch_env = si->birg->main_env->arch_env;
3609
3610         DBG((si->dbg, LEVEL_3, "\t  inserting spill for value %+F after %+F\n", irn, before));
3611
3612         spill = be_spill2(arch_env, irn, before);
3613
3614         defs = set_insert_def(si->values, value);
3615         assert(defs);
3616
3617         /* enter into the linked list */
3618         set_irn_link(spill, defs->spills);
3619         defs->spills = spill;
3620
3621         if(opt_keep_alive & KEEPALIVE_SPILLS)
3622                 pset_insert_ptr(si->spills, spill);
3623
3624         return spill;
3625 }
3626
3627 /**
3628  * @param before   The Phi node which has to be spilled
3629  */
3630 static ir_node *
3631 insert_mem_phi(spill_ilp_t * si, ir_node * phi)
3632 {
3633         ir_node   *mem_phi;
3634         ir_node  **ins;
3635         defs_t    *defs;
3636         int        n;
3637
3638         NEW_ARR_A(ir_node*, ins, get_irn_arity(phi));
3639
3640         for(n=get_irn_arity(phi)-1; n>=0; --n) {
3641                 ins[n] = si->m_unknown;
3642         }
3643
3644         mem_phi =  new_r_PhiM_nokeep(si->birg->irg, get_nodes_block(phi), get_irn_arity(phi), ins);
3645
3646         defs = set_insert_def(si->values, phi);
3647         assert(defs);
3648
3649         /* enter into the linked list */
3650         set_irn_link(mem_phi, defs->spills);
3651         defs->spills = mem_phi;
3652
3653 #ifdef SCHEDULE_PHIM
3654         sched_add_after(phi, mem_phi);
3655 #else
3656         pset_insert_ptr(si->phims, mem_phi);
3657 #endif
3658
3659         if(opt_keep_alive & KEEPALIVE_SPILLS)
3660                 pset_insert_ptr(si->spills, mem_phi);
3661
3662
3663         return mem_phi;
3664 }
3665
3666 /**
3667  * Add remat to list of defs, destroys link field!
3668  */
3669 static void
3670 insert_remat(spill_ilp_t * si, ir_node * remat)
3671 {
3672         defs_t   *defs;
3673         op_t     *remat_op = get_irn_link(remat);
3674
3675         assert(remat_op->is_remat);
3676
3677         defs = set_insert_def(si->values, remat_op->attr.remat.remat->value);
3678         assert(defs);
3679
3680         /* enter into the linked list */
3681         set_irn_link(remat, defs->remats);
3682         defs->remats = remat;
3683 }
3684
3685
3686 /**
3687  * Add reload before operation and add to list of defs
3688  */
3689 static ir_node *
3690 insert_reload(spill_ilp_t * si, const ir_node * value, ir_node * after)
3691 {
3692         defs_t   *defs;
3693         ir_node  *reload,
3694                          *spill;
3695         const arch_env_t *arch_env = si->birg->main_env->arch_env;
3696
3697         DBG((si->dbg, LEVEL_3, "\t  inserting reload for value %+F before %+F\n", value, after));
3698
3699         defs = set_find_def(si->values, value);
3700
3701         spill = defs->spills;
3702         assert(spill && "no spill placed before reload");
3703
3704         reload = be_reload(arch_env, si->cls, after, get_irn_mode(value), spill);
3705
3706         /* enter into the linked list */
3707         set_irn_link(reload, defs->remats);
3708         defs->remats = reload;
3709
3710         return reload;
3711 }
3712
3713 void perform_memory_operand(spill_ilp_t * si, memoperand_t * memoperand)
3714 {
3715         defs_t           *defs;
3716         ir_node          *value = get_irn_n(memoperand->irn, memoperand->pos);
3717         ir_node          *spill;
3718         const arch_env_t *arch_env = si->birg->main_env->arch_env;
3719
3720         DBG((si->dbg, LEVEL_2, "\t  inserting memory operand for value %+F at %+F\n", value, memoperand->irn));
3721
3722         defs = set_find_def(si->values, value);
3723
3724         spill = defs->spills;
3725         assert(spill && "no spill placed before reload");
3726
3727         arch_perform_memory_operand(arch_env, memoperand->irn, spill, memoperand->pos);
3728 }
3729
3730 void insert_memoperands(spill_ilp_t * si)
3731 {
3732         memoperand_t   *memoperand;
3733         lpp_name_t     *name;
3734
3735         set_foreach(si->memoperands, memoperand) {
3736                 name = si->lpp->vars[memoperand->ilp];
3737                 if(!is_zero(name->value)) {
3738                         perform_memory_operand(si, memoperand);
3739                 }
3740         }
3741 }
3742
3743 static void
3744 walker_spill_placer(ir_node * bb, void * data) {
3745         spill_ilp_t   *si = (spill_ilp_t*)data;
3746         ir_node       *irn;
3747         spill_bb_t    *spill_bb = get_irn_link(bb);
3748         pset          *spills_to_do = pset_new_ptr_default();
3749         spill_t       *spill;
3750
3751         set_foreach(spill_bb->ilp, spill) {
3752                 lpp_name_t    *name;
3753
3754                 if(is_Phi(spill->irn) && get_nodes_block(spill->irn) == bb) {
3755                         name = si->lpp->vars[spill->mem_in];
3756                         if(!is_zero(name->value)) {
3757                                 ir_node   *mem_phi;
3758
3759                                 mem_phi = insert_mem_phi(si, spill->irn);
3760
3761                                 DBG((si->dbg, LEVEL_2, "\t >>spilled Phi %+F -> %+F\n", spill->irn, mem_phi));
3762                         }
3763                 }
3764
3765                 name = si->lpp->vars[spill->spill];
3766                 if(!is_zero(name->value)) {
3767                         /* place spill directly after definition */
3768                         if(get_nodes_block(spill->irn) == bb) {
3769                                 insert_spill(si, spill->irn, spill->irn, spill->irn);
3770                                 continue;
3771                         }
3772
3773                         /* place spill at bb start */
3774                         if(spill->reg_in > 0) {
3775                                 name = si->lpp->vars[spill->reg_in];
3776                                 if(!is_zero(name->value)) {
3777                                         insert_spill(si, spill->irn, spill->irn, bb);
3778                                         continue;
3779                                 }
3780                         }
3781                         /* place spill after a remat */
3782                         pset_insert_ptr(spills_to_do, spill->irn);
3783                 }
3784         }
3785         DBG((si->dbg, LEVEL_3, "\t  %d spills to do in block %+F\n", pset_count(spills_to_do), bb));
3786
3787
3788         for(irn = sched_block_first_nonphi(bb); !sched_is_end(irn); irn = sched_next(irn)) {
3789                 op_t     *op = get_irn_link(irn);
3790
3791                 if(be_is_Spill(irn)) continue;
3792
3793                 if(op->is_remat) {
3794                         /* TODO fix this if we want to support remats with more than two nodes */
3795                         if(get_irn_mode(irn) != mode_T && pset_find_ptr(spills_to_do, op->attr.remat.remat->value)) {
3796                                 pset_remove_ptr(spills_to_do, op->attr.remat.remat->value);
3797
3798                                 insert_spill(si, irn, op->attr.remat.remat->value, irn);
3799                         }
3800                 } else {
3801                         if(pset_find_ptr(spills_to_do, irn)) {
3802                                 pset_remove_ptr(spills_to_do, irn);
3803
3804                                 insert_spill(si, irn, irn, irn);
3805                         }
3806                 }
3807
3808         }
3809
3810         assert(pset_count(spills_to_do) == 0);
3811
3812         /* afterwards free data in block */
3813         del_pset(spills_to_do);
3814 }
3815
3816 static ir_node *
3817 insert_mem_copy(spill_ilp_t * si, ir_node * bb, ir_node * value)
3818 {
3819         ir_node          *insert_pos = bb;
3820         ir_node          *spill;
3821         const arch_env_t *arch_env = si->birg->main_env->arch_env;
3822
3823         /* find last definition of arg value in block */
3824         ir_node  *next;
3825         defs_t   *defs;
3826         int       last = 0;
3827
3828         defs = set_find_def(si->values, value);
3829
3830         if(defs && defs->remats) {
3831                 for(next = defs->remats; next; next = get_irn_link(next)) {
3832                         if(get_nodes_block(next) == bb && sched_get_time_step(next) > last) {
3833                                 last = sched_get_time_step(next);
3834                                 insert_pos = next;
3835                         }
3836                 }
3837         }
3838
3839         if(get_nodes_block(value) == bb && sched_get_time_step(value) > last) {
3840                 last = sched_get_time_step(value);
3841                 insert_pos = value;
3842         }
3843
3844         DBG((si->dbg, LEVEL_2, "\t  inserting mem copy for value %+F after %+F\n", value, insert_pos));
3845
3846         spill = be_spill2(arch_env, is_Block(insert_pos)?value:insert_pos, insert_pos);
3847
3848         return spill;
3849 }
3850
3851 static void
3852 phim_fixer(spill_ilp_t *si) {
3853         defs_t  *defs;
3854
3855         set_foreach(si->values, defs) {
3856                 const ir_node  *phi = defs->value;
3857                 op_t           *op = get_irn_link(phi);
3858                 ir_node        *phi_m = NULL;
3859                 ir_node        *next = defs->spills;
3860                 int             n;
3861
3862                 if(!is_Phi(phi)) continue;
3863
3864                 while(next) {
3865                         if(is_Phi(next) && get_irn_mode(next) == mode_M) {
3866                                 phi_m = next;
3867                                 break;
3868                         } else {
3869                                 next = get_irn_link(next);
3870                         }
3871                 }
3872                 if(!phi_m) continue;
3873
3874                 for(n=get_irn_arity(phi)-1; n>=0; --n) {
3875                         ir_node        *value = get_irn_n(phi, n);
3876                         defs_t         *val_defs = set_find_def(si->values, value);
3877
3878                         /* a spill of this value */
3879                         ir_node      *spill;
3880
3881
3882                         if(opt_memcopies) {
3883                                 ir_node    *pred = get_Block_cfgpred_block(get_nodes_block(phi), n);
3884                                 lpp_name_t *name = si->lpp->vars[op->attr.live_range.args.copies[n]];
3885
3886                                 if(!is_zero(name->value)) {
3887                                         spill = insert_mem_copy(si, pred, value);
3888                                 } else {
3889                                         spill = val_defs->spills;
3890                                 }
3891                         } else {
3892                                 spill = val_defs->spills;
3893                         }
3894
3895                         assert(spill && "no spill placed before PhiM");
3896                         set_irn_n(phi_m, n, spill);
3897                 }
3898         }
3899 }
3900
3901 static void
3902 walker_reload_placer(ir_node * bb, void * data) {
3903         spill_ilp_t   *si = (spill_ilp_t*)data;
3904         ir_node       *irn;
3905         spill_bb_t    *spill_bb = get_irn_link(bb);
3906
3907         /* reloads at end of block */
3908         if(spill_bb->reloads) {
3909                 keyval_t    *keyval;
3910
3911                 set_foreach(spill_bb->reloads, keyval) {
3912                         ir_node        *irn = (ir_node*)keyval->key;
3913                         ilp_var_t       reload = PTR_TO_INT(keyval->val);
3914                         lpp_name_t     *name;
3915
3916                         name = si->lpp->vars[reload];
3917                         if(!is_zero(name->value)) {
3918                                 ir_node    *reload;
3919                                 ir_node    *insert_pos = bb;
3920                                 ir_node    *prev = sched_block_last_noncf(si, bb);
3921                                 op_t       *prev_op = get_irn_link(prev);
3922
3923                                 while(be_is_Spill(prev)) {
3924                                         prev = sched_prev(prev);
3925                                 }
3926
3927                                 prev_op = get_irn_link(prev);
3928
3929                                 /* insert reload before pre-remats */
3930                                 while(!sched_is_end(prev) && !be_is_Reload(prev) && !is_Phi(prev)
3931                                                 && prev_op->is_remat && prev_op->attr.remat.pre) {
3932                                         insert_pos = prev;
3933
3934                                         do {
3935                                                 prev = sched_prev(prev);
3936                                         } while(be_is_Spill(prev));
3937
3938                                         prev_op = get_irn_link(prev);
3939
3940                                 }
3941
3942                                 reload = insert_reload(si, irn, insert_pos);
3943
3944                                 if(opt_keep_alive & KEEPALIVE_RELOADS)
3945                                         pset_insert_ptr(si->spills, reload);
3946                         }
3947                 }
3948         }
3949
3950         /* walk and insert more reloads and collect remats */
3951         sched_foreach_reverse(bb, irn) {
3952                 op_t     *op = get_irn_link(irn);
3953
3954                 if(be_is_Reload(irn) || be_is_Spill(irn)) continue;
3955                 if(is_Phi(irn)) break;
3956
3957                 if(op->is_remat) {
3958                         if(get_irn_mode(irn) != mode_T) {
3959                                 insert_remat(si, irn);
3960                         }
3961                 } else {
3962                         int    n;
3963
3964                         for (n=get_irn_arity(irn)-1; n>=0; --n) {
3965                                 ir_node    *arg = get_irn_n(irn, n);
3966
3967                                 if(op->attr.live_range.args.reloads && op->attr.live_range.args.reloads[n] != ILP_UNDEF) {
3968                                         lpp_name_t    *name;
3969
3970                                         name = si->lpp->vars[op->attr.live_range.args.reloads[n]];
3971                                         if(!is_zero(name->value)) {
3972                                                 ir_node    *reload;
3973                                                 ir_node    *insert_pos = irn;
3974                                                 ir_node    *prev = sched_prev(insert_pos);
3975                                                 op_t       *prev_op;
3976
3977                                                 while(be_is_Spill(prev)) {
3978                                                         prev = sched_prev(prev);
3979                                                 }
3980
3981                                                 prev_op = get_irn_link(prev);
3982
3983                                                 /* insert reload before pre-remats */
3984                                                 while(!sched_is_end(prev) && !be_is_Reload(prev) && !is_Phi(prev)
3985                                                                 && prev_op->is_remat && prev_op->attr.remat.pre) {
3986                                                         insert_pos = prev;
3987
3988                                                         do {
3989                                                                 prev = sched_prev(prev);
3990                                                         } while(be_is_Spill(prev));
3991
3992                                                         prev_op = get_irn_link(prev);
3993
3994                                                 }
3995
3996                                                 reload = insert_reload(si, arg, insert_pos);
3997
3998                                                 assert(reload && "no reload returned");
3999                                                 set_irn_n(irn, n, reload);
4000
4001                                                 if(opt_keep_alive & KEEPALIVE_RELOADS)
4002                                                         pset_insert_ptr(si->spills, reload);
4003                                         }
4004                                 }
4005                         }
4006                 }
4007         }
4008
4009         del_set(spill_bb->ilp);
4010         if(spill_bb->reloads) del_set(spill_bb->reloads);
4011 }
4012
4013 static void
4014 walker_collect_used(ir_node * irn, void * data)
4015 {
4016         bitset_t   *used = data;
4017
4018         bitset_set(used, get_irn_idx(irn));
4019 }
4020
4021 struct kill_helper {
4022         bitset_t  *used;
4023         spill_ilp_t  *si;
4024 };
4025
4026 static void
4027 walker_kill_unused(ir_node * bb, void * data)
4028 {
4029         struct kill_helper *kh = data;
4030         ir_node            *bad = get_irg_bad(get_irn_irg(bb));
4031         ir_node            *irn;
4032
4033
4034         for(irn=sched_first(bb); !sched_is_end(irn);) {
4035                 ir_node     *next = sched_next(irn);
4036                 int          n;
4037
4038                 if(!bitset_is_set(kh->used, get_irn_idx(irn))) {
4039                         if(be_is_Spill(irn) || be_is_Reload(irn)) {
4040                                 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)));
4041 #if 0
4042                                 assert(lpp_get_sol_state(kh->si->lpp) != lpp_optimal && "optimal solution is suboptimal?");
4043 #endif
4044                         }
4045
4046                         sched_remove(irn);
4047
4048                         set_nodes_block(irn, bad);
4049                         for (n=get_irn_arity(irn)-1; n>=0; --n) {
4050                                 set_irn_n(irn, n, bad);
4051                         }
4052                 }
4053                 irn = next;
4054         }
4055 }
4056
4057 #ifndef SCHEDULE_PHIM
4058 static void
4059 kill_unused_phims(spill_ilp_t * si, struct kill_helper * kh)
4060 {
4061         ir_node  *phi;
4062         ir_node  *bad = get_irg_bad(si->birg->irg);
4063         int       n;
4064
4065         pset_foreach(si->phims, phi) {
4066                 if(!bitset_is_set(kh->used, get_irn_idx(phi))) {
4067
4068                         set_nodes_block(phi, bad);
4069                         for (n=get_irn_arity(phi)-1; n>=0; --n) {
4070                                 set_irn_n(phi, n, bad);
4071                         }
4072                 }
4073         }
4074 }
4075 #endif
4076
4077 static void
4078 kill_all_unused_values_in_schedule(spill_ilp_t * si)
4079 {
4080         struct kill_helper  kh;
4081
4082         kh.used = bitset_malloc(get_irg_last_idx(si->birg->irg));
4083         kh.si = si;
4084
4085         irg_walk_graph(si->birg->irg, walker_collect_used, NULL, kh.used);
4086 #ifndef SCHEDULE_PHIM
4087         kill_unused_phims(si, &kh);
4088 #endif
4089         irg_block_walk_graph(si->birg->irg, walker_kill_unused, NULL, &kh);
4090
4091         bitset_free(kh.used);
4092 }
4093
4094 void
4095 print_irn_pset(pset * p)
4096 {
4097         ir_node   *irn;
4098
4099         pset_foreach(p, irn) {
4100                 ir_printf("%+F\n", irn);
4101         }
4102 }
4103
4104 void
4105 dump_phi_class(spill_ilp_t *si, ir_node **phiclass, const char * file)
4106 {
4107     FILE           *f = fopen(file, "w");
4108     ir_node        *irn;
4109     interference_t *interference;
4110     int            i;
4111
4112     set_break(si->interferences);
4113
4114     ir_fprintf(f, "digraph phiclass {\n");
4115
4116     for (i = ARR_LEN(phiclass) - 1; i >= 0; --i) {
4117         irn = phiclass[i];
4118         if (is_Phi(irn))
4119             ir_fprintf(f, "  %F%N [shape=box]\n", irn, irn);
4120     }
4121
4122     for (i = ARR_LEN(phiclass) - 1; i >= 0; --i) {
4123         int n;
4124
4125         irn = phiclass[i];
4126         if (! is_Phi(irn))
4127             continue;
4128
4129         for (n = get_irn_arity(irn) - 1; n >= 0; --n) {
4130             ir_node  *arg = get_irn_n(irn, n);
4131
4132             ir_fprintf(f, "  %F%N -> %F%N\n", irn, irn, arg, arg);
4133         }
4134     }
4135
4136     set_foreach(si->interferences, interference) {
4137         const ir_node *a = interference->a;
4138         const ir_node *b = interference->b;
4139         if (get_phi_class(si->pc, (ir_node *)a) == phiclass) {
4140             ir_fprintf(f, "  %F%N -> %F%N [color=red,dir=none,style=bold]\n", a, a, b, b);
4141         }
4142     }
4143
4144     ir_fprintf(f, "}");
4145     fclose(f);
4146 }
4147
4148 static void
4149 rewire_uses(spill_ilp_t * si)
4150 {
4151         defs_t               *defs;
4152         ir_nodeset_t         ignore;
4153
4154         ir_nodeset_init(&ignore);
4155         ir_nodeset_insert(&ignore, get_irg_end(si->birg->irg));
4156
4157         /* then fix uses of spills */
4158         set_foreach(si->values, defs) {
4159                 pset           *reloads;
4160                 pset           *spills;
4161                 const ir_node  *next = defs->remats;
4162                 int remats = 0;
4163
4164                 reloads = pset_new_ptr_default();
4165
4166                 while(next) {
4167                         if(be_is_Reload(next)) {
4168                                 pset_insert_ptr(reloads, next);
4169                         } else {
4170                                 ++remats;
4171                         }
4172                         next = get_irn_link(next);
4173                 }
4174
4175                 spills = get_spills_for_value(si, defs->value);
4176                 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));
4177                 if(pset_count(spills) > 1) {
4178                         be_ssa_construction_env_t senv;
4179                         ir_node *node;
4180                         //assert(pset_count(reloads) > 0);
4181                         //                              print_irn_pset(spills);
4182                         //                              print_irn_pset(reloads);
4183
4184                         be_ssa_construction_init(&senv, si->birg);
4185                         be_ssa_construction_set_ignore_uses(&senv, &ignore);
4186                         pset_foreach(spills, node) {
4187                                 be_ssa_construction_add_copy(&senv, node);
4188                         }
4189                         pset_foreach(spills, node) {
4190                                 be_ssa_construction_fix_users(&senv, node);
4191                         }
4192                         be_ssa_construction_update_liveness_phis(&senv, si->lv);
4193                         pset_foreach(spills, node) {
4194                                 be_liveness_update(si->lv, node);
4195                         }
4196                         be_ssa_construction_destroy(&senv);
4197                 }
4198
4199                 del_pset(reloads);
4200                 del_pset(spills);
4201         }
4202
4203         /* first fix uses of remats and reloads */
4204         set_foreach(si->values, defs) {
4205                 const ir_node  *next = defs->remats;
4206                 int             orig_kept = 0;
4207
4208                 if(next) {
4209                         be_ssa_construction_env_t senv;
4210
4211                         be_ssa_construction_init(&senv, si->birg);
4212
4213                         if(sched_is_scheduled(defs->value)) {
4214                                 be_ssa_construction_add_copy(&senv, (ir_node*) defs->value);
4215                                 orig_kept = 1;
4216                         }
4217
4218                         next = defs->remats;
4219                         while(next) {
4220                                 be_ssa_construction_add_copy(&senv, (ir_node*) next);
4221                                 next = get_irn_link(next);
4222                         }
4223
4224                         if(sched_is_scheduled(defs->value)) {
4225                                 be_ssa_construction_fix_users(&senv, (ir_node*) defs->value);
4226                         }
4227
4228                         next = defs->remats;
4229                         while(next) {
4230                                 be_ssa_construction_fix_users(&senv, (ir_node*) next);
4231                                 next = get_irn_link(next);
4232                         }
4233
4234                         be_ssa_construction_update_liveness_phis(&senv, si->lv);
4235                         if(sched_is_scheduled(defs->value)) {
4236                                 be_liveness_update(si->lv, (ir_node*) defs->value);
4237                         }
4238
4239                         next = defs->remats;
4240                         while(next) {
4241                                 be_liveness_update(si->lv, (ir_node*) next);
4242                                 next = get_irn_link(next);
4243                         }
4244
4245                         be_ssa_construction_destroy(&senv);
4246                 }
4247         }
4248
4249         ir_nodeset_destroy(&ignore);
4250 //      remove_unused_defs(si);
4251 }
4252
4253
4254 static void
4255 writeback_results(spill_ilp_t * si)
4256 {
4257         /* walk through the graph and collect all spills, reloads and remats for a value */
4258
4259         si->values = new_set(cmp_defs, 4096);
4260
4261         DBG((si->dbg, LEVEL_1, "Applying results\n"));
4262         delete_unnecessary_remats(si);
4263         si->m_unknown = new_r_Unknown(si->birg->irg, mode_M);
4264         irg_block_walk_graph(si->birg->irg, walker_spill_placer, NULL, si);
4265         irg_block_walk_graph(si->birg->irg, walker_reload_placer, NULL, si);
4266         if(opt_memoperands)
4267                 insert_memoperands(si);
4268         phim_fixer(si);
4269
4270         /* clean the remat info! there are still back-edges leading there! */
4271         clean_remat_info(si);
4272
4273         rewire_uses(si);
4274
4275         connect_all_spills_with_keep(si);
4276
4277         del_set(si->values);
4278 }
4279
4280 static int
4281 get_n_regs(spill_ilp_t * si)
4282 {
4283         int       arch_n_regs = arch_register_class_n_regs(si->cls);
4284
4285         bitset_t *arch_regs = bitset_malloc(arch_n_regs);
4286         bitset_t *abi_regs = bitset_malloc(arch_n_regs);
4287
4288         arch_put_non_ignore_regs(si->birg->main_env->arch_env, si->cls, arch_regs);
4289     be_abi_put_ignore_regs(si->birg->abi, si->cls, abi_regs);
4290
4291         bitset_andnot(arch_regs, abi_regs);
4292         arch_n_regs = bitset_popcnt(arch_regs);
4293
4294         bitset_free(arch_regs);
4295         bitset_free(abi_regs);
4296
4297         DBG((si->dbg, LEVEL_1, "\tArchitecture has %d free registers in class %s\n", arch_n_regs, si->cls->name));
4298         return arch_n_regs;
4299 }
4300
4301 static void
4302 walker_reload_mover(ir_node * bb, void * data)
4303 {
4304         spill_ilp_t   *si = data;
4305         ir_node           *tmp;
4306
4307         sched_foreach(bb, tmp) {
4308                 if(be_is_Reload(tmp) && has_reg_class(si, tmp)) {
4309                         ir_node       *reload = tmp;
4310                         ir_node       *irn = tmp;
4311
4312                         /* move reload upwards */
4313
4314                         int pressure = (int)get_irn_link(reload);
4315                         if(pressure < si->n_regs) {
4316                                 irn = sched_prev(reload);
4317                                 DBG((si->dbg, LEVEL_5, "regpressure before %+F: %d\n", reload, pressure));
4318                                 sched_remove(reload);
4319                                 pressure = (int)get_irn_link(irn);
4320
4321                                 while(pressure < si->n_regs) {
4322                                         if( sched_is_end(irn) ||
4323                                            (be_is_Reload(irn) && has_reg_class(si, irn)) ||
4324                                            /* do not move reload before its spill */
4325                                            (irn == be_get_Reload_mem(reload)) ||
4326                                            /* do not move before phi */
4327                                            is_Phi(irn)) break;
4328
4329                                         set_irn_link(irn, INT_TO_PTR(pressure+1));
4330                                         DBG((si->dbg, LEVEL_5, "new regpressure before %+F: %d\n", irn, pressure+1));
4331                                         irn = sched_prev(irn);
4332
4333                                         pressure = (int)get_irn_link(irn);
4334                                 }
4335
4336                                 DBG((si->dbg, LEVEL_3, "putting reload %+F after %+F\n", reload, irn));
4337                                 sched_put_after(irn, reload);
4338                         }
4339                 }
4340         }
4341 }
4342
4343 static void
4344 move_reloads_upward(spill_ilp_t * si)
4345 {
4346         irg_block_walk_graph(si->birg->irg, walker_reload_mover, NULL, si);
4347 }
4348
4349
4350 /**
4351  * Walk all irg blocks and check for interfering spills inside of phi classes
4352  */
4353 static void
4354 luke_meminterferencechecker(ir_node * bb, void * data)
4355 {
4356         spill_ilp_t *si = (spill_ilp_t*)data;
4357         int         l1, l2;
4358
4359         be_lv_foreach(si->lv, bb, be_lv_state_end | be_lv_state_out | be_lv_state_in, l1) {
4360                 ir_node        *a = be_lv_get_irn(si->lv, bb, l1);
4361
4362                 if (! be_is_Spill(a) && (!is_Phi(a) || get_irn_mode(a) != mode_T))
4363                         continue;
4364
4365                 /* a is only interesting if it is in my register class and if it is inside a phi class */
4366                 if (has_reg_class(si, a) && get_phi_class(si->pc, a)) {
4367                         for (l2 = _be_lv_next_irn(si->lv, bb, 0xff, l1 + 1); l2 >= 0; l2 = _be_lv_next_irn(si->lv, bb, 0xff, l2 + 1)) {
4368                                 ir_node *b = be_lv_get_irn(si->lv, bb, l2);
4369
4370                                 if (! be_is_Spill(b) && (! is_Phi(b) || get_irn_mode(b) != mode_T))
4371                                         continue;
4372
4373                                 /* a and b are only interesting if they are in the same phi class */
4374                                 if (has_reg_class(si, b) && get_phi_class(si->pc, a) == get_phi_class(si->pc, b)) {
4375                                         if (values_interfere_in_block(si, bb, a, b)) {
4376                                                 ir_fprintf(stderr, "$$ Spills interfere in %+F: %+F, %+F \t$$\n", bb, a, b);
4377                                         }
4378                                 }
4379                         }
4380                 }
4381         }
4382 }
4383
4384 static void
4385 verify_phiclasses(spill_ilp_t * si)
4386 {
4387         /* analyze phi classes */
4388         phi_class_free(si->pc);
4389         si->pc = phi_class_new_from_irg(si->birg->irg, 0);
4390
4391         DBG((si->dbg, LEVEL_2, "\t calling memory interference checker\n"));
4392         irg_block_walk_graph(si->birg->irg, luke_meminterferencechecker, NULL, si);
4393 }
4394
4395 void
4396 be_spill_remat(be_irg_t *birg, const arch_register_class_t *cls)
4397 {
4398         char            buf[256];
4399         char            problem_name[256];
4400         char            dump_suffix[256];
4401         char            dump_suffix2[256];
4402         struct obstack  obst;
4403         spill_ilp_t     si;
4404         ir_graph       *irg = be_get_birg_irg(birg);
4405
4406         ir_snprintf(problem_name, sizeof(problem_name), "%F_%s", irg, cls->name);
4407         ir_snprintf(dump_suffix, sizeof(dump_suffix), "-%s-remats", cls->name);
4408         ir_snprintf(dump_suffix2, sizeof(dump_suffix2), "-%s-pressure", cls->name);
4409
4410         FIRM_DBG_REGISTER(si.dbg, "firm.be.ra.spillremat");
4411         DBG((si.dbg, LEVEL_1, "\n\n\t\t===== Processing %s =====\n\n", problem_name));
4412
4413         if(opt_verify & VERIFY_DOMINANCE)
4414                 be_check_dominance(irg);
4415
4416         be_assure_dom_front(birg);
4417         be_assure_liveness(birg);
4418
4419         obstack_init(&obst);
4420         si.obst                = &obst;
4421         si.birg                = birg;
4422         si.cls                 = cls;
4423         si.lpp                 = new_lpp(problem_name, lpp_minimize);
4424         si.remat_info          = new_set(cmp_remat_info, 4096);
4425         si.interferences       = new_set(cmp_interference, 32);
4426         si.memoperands         = new_set(cmp_memoperands, 128);
4427         si.all_possible_remats = pset_new_ptr_default();
4428         si.spills              = pset_new_ptr_default();
4429         si.inverse_ops         = pset_new_ptr_default();
4430         si.lv                  = birg->lv;
4431         si.keep                = NULL;
4432         si.n_regs              = get_n_regs(&si);
4433
4434         set_irg_link(irg, &si);
4435         compute_doms(irg);
4436
4437         /* compute phi classes */
4438         // phi_class_compute(irg);
4439
4440         if(opt_dump_flags & DUMP_STATS)
4441                 be_analyze_regpressure(birg, cls, "-pre");
4442
4443         DBG((si.dbg, LEVEL_2, "\t initializing\n"));
4444         irg_block_walk_graph(irg, luke_initializer, NULL, &si);
4445
4446         if(opt_remats) {
4447                 /* collect remats */
4448                 DBG((si.dbg, LEVEL_1, "Collecting remats\n"));
4449                 irg_walk_graph(irg, walker_remat_collector, NULL, &si);
4450         }
4451
4452         /* insert possible remats */
4453         DBG((si.dbg, LEVEL_1, "Inserting possible remats\n"));
4454         irg_block_walk_graph(irg, walker_remat_insertor, NULL, &si);
4455         DBG((si.dbg, LEVEL_2, " -> inserted %d possible remats\n", pset_count(si.all_possible_remats)));
4456
4457         if(opt_keep_alive & KEEPALIVE_REMATS) {
4458                 DBG((si.dbg, LEVEL_1, "Connecting remats with keep and dumping\n"));
4459                 connect_all_remats_with_keep(&si);
4460                 /* dump graph with inserted remats */
4461                 dump_graph_with_remats(irg, dump_suffix);
4462         }
4463
4464         /* insert copies for phi arguments not in my regclass */
4465         irg_walk_graph(irg, walker_regclass_copy_insertor, NULL, &si);
4466
4467         /* recompute liveness */
4468         DBG((si.dbg, LEVEL_1, "Recomputing liveness\n"));
4469         be_liveness_recompute(si.lv);
4470
4471         /* build the ILP */
4472         DBG((si.dbg, LEVEL_1, "\tBuilding ILP\n"));
4473         DBG((si.dbg, LEVEL_2, "\t endwalker\n"));
4474         irg_block_walk_graph(irg, luke_endwalker, NULL, &si);
4475
4476         DBG((si.dbg, LEVEL_2, "\t blockwalker\n"));
4477         irg_block_walk_graph(irg, luke_blockwalker, NULL, &si);
4478
4479         si.pc = phi_class_new_from_irg(birg->irg, 0);
4480         if (opt_memcopies) {
4481                 DBG((si.dbg, LEVEL_2, "\t memcopyhandler\n"));
4482                 memcopyhandler(&si);
4483         }
4484
4485         if (opt_dump_flags & DUMP_PROBLEM) {
4486                 FILE           *f;
4487                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.ilp", problem_name);
4488                 if ((f = fopen(buf, "wt")) != NULL) {
4489                         lpp_dump_plain(si.lpp, f);
4490                         fclose(f);
4491                 }
4492         }
4493
4494         if (opt_dump_flags & DUMP_MPS) {
4495                 FILE *f;
4496
4497                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.mps", problem_name);
4498                 if ((f = fopen(buf, "wt")) != NULL) {
4499                         mps_write_mps(si.lpp, s_mps_fixed, f);
4500                         fclose(f);
4501                 }
4502
4503                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.mst", problem_name);
4504                 if ((f = fopen(buf, "wt")) != NULL) {
4505                         mps_write_mst(si.lpp, s_mps_fixed, f);
4506                         fclose(f);
4507                 }
4508         }
4509
4510         lpp_check_startvals(si.lpp);
4511
4512 #ifdef SOLVE
4513         DBG((si.dbg, LEVEL_1, "\tSolving %s (%d variables, %d constraints)\n", problem_name, si.lpp->var_next, si.lpp->cst_next));
4514         lpp_set_time_limit(si.lpp, opt_timeout);
4515
4516         if(opt_log)
4517                 lpp_set_log(si.lpp, stdout);
4518
4519 #ifdef SOLVE_LOCAL
4520         lpp_solve_cplex(si.lpp);
4521 #else
4522         lpp_solve_net(si.lpp, LPP_SERVER, LPP_SOLVER);
4523 #endif
4524         assert(lpp_is_sol_valid(si.lpp)
4525                && "solution of ILP must be valid");
4526
4527         DBG((si.dbg, LEVEL_1, "\t%s: iterations: %d, solution time: %g, objective function: %g, best bound: %g\n", problem_name, si.lpp->iterations, si.lpp->sol_time, is_zero(si.lpp->objval)?0.0:si.lpp->objval, is_zero(si.lpp->best_bound)?0.0:si.lpp->best_bound));
4528
4529         if(opt_dump_flags & DUMP_SOLUTION) {
4530                 FILE           *f;
4531                 char            buf[256];
4532
4533                 ir_snprintf(buf, sizeof(buf), "%s-spillremat.sol", problem_name);
4534                 if ((f = fopen(buf, "wt")) != NULL) {
4535                         int             i;
4536                         for (i = 0; i < si.lpp->var_next; ++i) {
4537                                 lpp_name_t     *name = si.lpp->vars[i];
4538                                 fprintf(f, "%20s %4d %10f\n", name->name, name->nr, name->value);
4539                         }
4540                         fclose(f);
4541                 }
4542         }
4543
4544 #ifndef SCHEDULE_PHIM
4545         si.phims = pset_new_ptr_default();
4546 #endif
4547         writeback_results(&si);
4548
4549
4550 #endif                          /* SOLVE */
4551
4552         kill_all_unused_values_in_schedule(&si);
4553
4554 #if !defined(SCHEDULE_PHIM) && defined(SOLVE)
4555         del_pset(si.phims);
4556 #endif
4557
4558         if(opt_keep_alive & (KEEPALIVE_SPILLS | KEEPALIVE_RELOADS))
4559                 be_dump(irg, "-spills-placed", dump_ir_block_graph);
4560
4561         // move reloads upwards
4562         be_liveness_recompute(si.lv);
4563         irg_block_walk_graph(irg, walker_pressure_annotator, NULL, &si);
4564         move_reloads_upward(&si);
4565
4566         if(opt_memcopies) {
4567                 verify_phiclasses(&si);
4568         }
4569
4570         irg_block_walk_graph(irg, walker_pressure_annotator, NULL, &si);
4571
4572         if(opt_dump_flags & DUMP_PRESSURE)
4573                 dump_pressure_graph(&si, dump_suffix2);
4574
4575         if(opt_dump_flags & DUMP_STATS)
4576                 be_analyze_regpressure(birg, cls, "-post");
4577
4578         if(opt_verify & VERIFY_DOMINANCE)
4579                 be_check_dominance(irg);
4580
4581         free_dom(irg);
4582         del_set(si.interferences);
4583         del_pset(si.inverse_ops);
4584         del_pset(si.all_possible_remats);
4585         del_set(si.memoperands);
4586         del_pset(si.spills);
4587         free_lpp(si.lpp);
4588         phi_class_free(si.pc);
4589         obstack_free(&obst, NULL);
4590         DBG((si.dbg, LEVEL_1, "\tdone.\n"));
4591 }
4592
4593 void be_init_spillremat(void)
4594 {
4595         static be_spiller_t remat_spiller = {
4596                 be_spill_remat
4597         };
4598         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
4599         lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
4600         lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
4601         lc_opt_entry_t *remat_grp = lc_opt_get_grp(chordal_grp, "remat");
4602
4603         be_register_spiller("remat", &remat_spiller);
4604         lc_opt_add_table(remat_grp, options);
4605 }
4606
4607 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_spillremat);
4608
4609 #else                           /* WITH_ILP */
4610
4611 static void INLINE
4612 only_that_you_can_compile_without_WITH_ILP_defined(void)
4613 {
4614 }
4615
4616 #endif                          /* WITH_ILP */