*** empty log message ***
[libfirm] / ir / be / bespillilp.c
1 /**
2  * @file   bespillilp.c
3  * @date   15.07.2005
4  * @author Sebastian Hack
5  *
6  * ILP based spilling
7  *
8  * Copyright (C) 2005 Universitaet Karlsruhe
9  * Released under the GPL
10  */
11 #include <math.h>
12
13 #include "hashptr.h"
14 #include "debug.h"
15 #include "obst.h"
16 #include "set.h"
17 #include "list.h"
18 #include "pmap.h"
19
20 #include "irprintf.h"
21 #include "irgwalk.h"
22 #include "irnode_t.h"
23 #include "ircons_t.h"
24
25 #include <lpp/lpp.h>
26 #include <lpp/lpp_net.h>
27 #include <lpp/lpp_cplex.h>
28
29 #include "be_t.h"
30 #include "belive_t.h"
31 #include "besched_t.h"
32 #include "beirgmod.h"
33 #include "bearch.h"
34 #include "benode_t.h"
35 #include "beutil.h"
36 #include "bespillilp.h"
37
38 #define BIGM 1000.0
39
40 #define MAX(a,b) ((a) > (b) ? (a) : (b))
41
42 #define DBG_LEVEL SET_LEVEL_4
43
44 #define DUMP_SOLUTION
45 #define DUMP_ILP
46 #undef  DUMP_STATS
47
48 #undef  SOLVE_LOCAL
49 #define LPP_SERVER "i44pc52"
50 #define LPP_SOLVER "cplex"
51
52 #define COST_LOAD      10
53 #define COST_STORE     50
54 #define COST_REMAT     (-9)
55
56 #define is_end_of_block_use(lr) (is_Block((lr)->user))
57
58 /**
59  * Reloads on edges.
60  */
61 typedef struct _edge_reload_t {
62         ir_node *irn;
63         ir_node *bl;
64         int pos;
65         int in_mem_var;
66         struct _edge_reload_t *next;
67 } edge_reload_t;
68
69 typedef struct _spill_stat_t {
70         int n_spills;
71         int n_reloads;
72         int n_remat;
73 } spill_stat_t;
74
75 typedef struct _spill_ilp_t {
76         const arch_register_class_t *cls;
77         const be_main_session_env_t *session;
78         firm_dbg_module_t *dbg;
79         lpp_t *lpp;
80         set *irn_use_heads;
81         set *live_ranges;
82         set *first_uses;
83         spill_env_t *senv;
84         edge_reload_t *edges;
85         struct obstack *obst;
86         int enable_store : 1;
87         int enable_remat : 1;
88 } spill_ilp_t;
89
90 typedef struct _live_range_t live_range_t;
91
92 typedef struct _irn_use_head_t {
93         struct list_head head;
94         ir_node *irn;
95         int spill_var;
96         int n_uses;
97         live_range_t *closest_use;
98 } irn_use_head_t;
99
100 struct _live_range_t {
101   struct list_head list;
102         irn_use_head_t *use_head;
103   ir_node *user;
104   ir_node *irn;
105         int pos;
106   int in_mem_var;
107   int is_remat_var;
108 };
109
110 /*
111  * Associates the first use of a live-in in a block
112  * with its live range.
113  */
114 typedef struct _first_use_t {
115         ir_node *bl;
116         ir_node *irn;       /**< A value live in at bl. */
117         live_range_t *lr;   /**< The live range for the first use of irn in bl. */
118 } first_use_t;
119
120
121
122 static int has_reg_class(const spill_ilp_t *si, const ir_node *irn)
123 {
124   return arch_irn_has_reg_class(si->session->main_env->arch_env,
125       irn, arch_pos_make_out(0), si->cls);
126 }
127
128 static int cmp_live_range(const void *a, const void *b, size_t n)
129 {
130   const live_range_t *p = a;
131   const live_range_t *q = b;
132
133   return !(p->user == q->user && p->irn == q->irn && p->pos == q->pos);
134 }
135
136 static int cmp_irn_use_head(const void *a, const void *b, size_t n)
137 {
138   const irn_use_head_t *p = a;
139   const irn_use_head_t *q = b;
140
141         return !(p->irn == q->irn);
142 }
143
144 static irn_use_head_t *get_use_head(spill_ilp_t *si, const ir_node *irn)
145 {
146         irn_use_head_t templ;
147         templ.irn = (ir_node *) irn;
148         return set_find(si->irn_use_heads, &templ, sizeof(templ), HASH_PTR(irn));
149 }
150
151 static int cmp_first_use(const void *a, const void *b, size_t n)
152 {
153   const first_use_t *p = a;
154   const first_use_t *q = b;
155
156   return !(p->irn == q->irn && p->bl == q->bl);
157 }
158
159 static void add_first_use(spill_ilp_t *si, ir_node *bl, ir_node *irn, live_range_t *lr)
160 {
161         first_use_t templ;
162         templ.bl    = bl;
163         templ.irn   = irn;
164         templ.lr    = lr;
165
166         set_insert(si->first_uses, &templ, sizeof(templ),
167                         HASH_COMBINE(HASH_PTR(bl), HASH_PTR(irn)));
168 }
169
170 static live_range_t *get_first_use_lr(spill_ilp_t *si, ir_node *bl, ir_node *irn)
171 {
172         first_use_t *res;
173         first_use_t templ;
174         templ.bl    = bl;
175         templ.irn   = irn;
176
177         res = set_find(si->first_uses, &templ, sizeof(templ),
178                         HASH_COMBINE(HASH_PTR(bl), HASH_PTR(irn)));
179
180         return res ? res->lr : NULL;
181 }
182
183 /**
184  * Checks, if a vertain node can be recomputed at a certain position.
185  * @param si    The spill ILP environment.
186  * @param irn   The node to recompute.
187  * @param live  The nodes live at the place where @p irn shall be
188  *              recomputed.
189  * @return      1, if irn can be recomputed, 0 if not.
190  */
191 static INLINE int can_remat(const spill_ilp_t *si, const ir_node *irn, pset *live)
192 {
193         int i, n;
194   const arch_env_t *arch_env    = si->session->main_env->arch_env;
195         int remat = (arch_irn_get_flags(arch_env, irn) & arch_irn_flags_rematerializable) != 0;
196
197         for(i = 0, n = get_irn_arity(irn); i < n && remat; ++i) {
198                 ir_node *op = get_irn_n(irn, i);
199                 remat &= !has_reg_class(si, op) || pset_find_ptr(live, op);
200         }
201
202         return remat;
203 }
204
205 static live_range_t *get_live_range(spill_ilp_t *si, ir_node *irn, ir_node *user, int pos)
206 {
207   live_range_t lr, *res;
208         irn_use_head_t iuh, *head;
209         int is_new;
210   unsigned hash = HASH_COMBINE(HASH_PTR(irn), HASH_PTR(user));
211
212   lr.user    = user;
213   lr.irn     = irn;
214   lr.pos     = pos;
215   lr.in_mem_var = -1;
216         lr.is_remat_var = -1;
217
218   res = set_insert(si->live_ranges, &lr, sizeof(lr), hash);
219         is_new = res->in_mem_var == -1;
220
221   if(is_new) {
222     char buf[128];
223     ir_snprintf(buf, sizeof(buf), "m_%s%N_%N_%d",
224                                 is_Phi(irn) ? "phi_" : "", irn, user, MAX(pos, 0));
225     res->in_mem_var = lpp_add_var(si->lpp, buf, lpp_binary, pos >= 0 ? COST_LOAD : 0.0);
226   }
227
228         memset(&iuh, 0, sizeof(iuh));
229         iuh.irn = irn;
230         iuh.n_uses = -1;
231         head = set_insert(si->irn_use_heads, &iuh, sizeof(iuh), HASH_PTR(irn));
232         if(head->n_uses == -1) {
233                 head->n_uses = 0;
234                 INIT_LIST_HEAD(&head->head);
235         }
236
237         if(is_new) {
238                 list_add_tail(&res->list, &head->head);
239                 head->n_uses++;
240         }
241
242         res->use_head = head;
243
244   return res;
245 }
246
247 static ir_node *process_irn(spill_ilp_t *si, pset *live, ir_node *irn, int *demand)
248 {
249         int i, n;
250         int relevant_args = 0, results = 0;
251
252         DBG((si->dbg, LEVEL_1, "at %+F\n", irn));
253
254         while(is_Proj(irn)) {
255                 if(has_reg_class(si, irn)) {
256                         assert(pset_find_ptr(live, irn) && "node must be live");
257                         pset_remove_ptr(live, irn);
258                         results++;
259                 }
260
261                 DBG((si->dbg, LEVEL_1, "skipped proj %+F\n", irn));
262                 irn = sched_prev(irn);
263         }
264
265         DBG((si->dbg, LEVEL_1, "\tlanded at irn %+F\n", irn));
266
267         if(results > 0)
268                 assert(get_irn_mode(irn) == mode_T && "node before projs must be tuple");
269
270         if(has_reg_class(si, irn)) {
271                 assert( pset_find_ptr(live, irn) && "node must be live");
272                 pset_remove_ptr(live, irn);
273                 results = 1;
274         }
275
276         for(i = 0, n = get_irn_arity(irn); i < n; ++i) {
277                 ir_node *op = get_irn_n(irn, i);
278                 if(has_reg_class(si, op) && !pset_find_ptr(live, op)) {
279                         relevant_args++;
280                         DBG((si->dbg, LEVEL_1, "\trelevant arg %+F\n", op));
281                 }
282         }
283
284         *demand = MAX(results, relevant_args);
285         DBG((si->dbg, LEVEL_1, "\tdemand: %d\n", *demand));
286         return irn;
287 }
288
289 static void process_block(ir_node *bl, void *data)
290 {
291         char buf[128];
292         int i, n;
293   spill_ilp_t *si  = data;
294   int step         = 0;
295   int n_regs       = arch_register_class_n_regs(si->cls);
296         int n_preds      = get_irn_arity(bl);
297   pset *live       = pset_new_ptr_default();
298   irn_live_t *li;
299   ir_node *irn;
300
301   /* as always, bring the live end nodes to life here */
302   live_foreach(bl, li) {
303     if(live_is_end(li) && has_reg_class(si, li->irn)) {
304       ir_node *irn = (ir_node *) li->irn;
305       pset_insert_ptr(live, irn);
306
307       /*
308        * The "user" of the live range to the end of a block
309        * is the block itself. This is quite arbitrary.
310        */
311       set_irn_link(irn, get_live_range(si, irn, bl, -1));
312     }
313   }
314
315         for(irn = sched_last(bl); !sched_is_begin(irn) && !is_Phi(irn); irn = sched_prev(irn)) {
316                 ir_node *l;
317                 int cst;
318                 int demand;
319                 int n_live;
320                 int must_be_in_mem;
321
322                 /* We handle phi togther with live ins after this loop (see below). */
323                 if(is_Phi(irn))
324                         break;
325
326 #if 0
327                 if(has_reg_class(si, irn))
328                         pset_remove_ptr(live, irn);
329
330                 demand = register_demand(si, live, irn);
331                 n_live = pset_count(live);
332 #endif
333
334                 irn = process_irn(si, live, irn, &demand);
335                 n_live = pset_count(live);
336
337                 /*
338                  * Determine, how many values (which are not used at the label)
339                  * must be in memory.
340                  * demand means the number of registers, the operation will consume.
341                  * So there are n_regs - demand registers available to store values
342                  * which are not used at this label. The rest must reside in memory.
343                  */
344                 must_be_in_mem = MAX(n_live + demand - n_regs, 0);
345
346                 DBG((si->dbg, LEVEL_1, "%+F: demand: %d, live: %d, in mem: %d\n",
347                                         irn, demand, n_live, must_be_in_mem));
348
349                 if(must_be_in_mem > 0) {
350
351                         /*
352                          * The constraint limiting the pressure at this label to
353                          * the number of free registers.
354                          */
355                         ir_snprintf(buf, sizeof(buf), "cp_%N_%N_%d", bl, irn, step);
356                         cst = lpp_add_cst(si->lpp, buf, lpp_greater, must_be_in_mem);
357
358                         for(l = pset_first(live); l; l = pset_next(live)) {
359                                 live_range_t *lr = get_irn_link(l);
360                                 lpp_set_factor_fast(si->lpp, cst, lr->in_mem_var, 1.0);
361                         }
362                 }
363
364                 for(i = 0, n = get_irn_arity(irn); i < n; ++i) {
365                         ir_node *op = get_irn_n(irn, i);
366
367                         if(has_reg_class(si, op)) {
368                                 live_range_t *op_lr = get_live_range(si, op, irn, i);
369
370                                 set_irn_link(op, op_lr);
371
372                                 /*
373                                  * The operand is reloaded at its usage, so it must not occur
374                                  * in the constraint which determines which values live at the
375                                  * instruction must reside in memory.
376                                  */
377                                 if(must_be_in_mem > 0)
378                                         lpp_set_factor_fast(si->lpp, cst, op_lr->in_mem_var, 0.0);
379
380                                 /*
381                                  * Check, if the node is a rematerializable node and
382                                  * if its operands are live here.
383                                  */
384                                 if(si->enable_remat && can_remat(si, op, live)) {
385                                         int cst;
386                                         int j, n;
387                                         int n_operands = 0;
388
389                                         for(j = 0, n = get_irn_arity(op); j < n; ++j)
390                                                 n_operands += has_reg_class(si, get_irn_n(op, j));
391
392                                         /* Make the remat constraint for this operand */
393                                         ir_snprintf(buf, sizeof(buf), "ce1_%N_%N_%d", op, irn, i);
394                                         cst = lpp_add_cst(si->lpp, buf, lpp_less, n_operands);
395
396                                         /* Make the rematerialize variable for the operand */
397                                         ir_snprintf(buf, sizeof(buf), "e_%N_%N_%d", op, irn, i);
398                                         op_lr->is_remat_var = lpp_add_var(si->lpp, buf, lpp_binary, COST_REMAT);
399                                         lpp_set_factor_fast(si->lpp, cst, op_lr->is_remat_var, n_operands);
400
401                                         for(j = 0, n = get_irn_arity(op); j < n; ++j) {
402                                                 ir_node *oop = get_irn_n(op, j);
403                                                 if(has_reg_class(si, oop)) {
404                                                         live_range_t *lr = get_irn_link(oop);
405                                                         lpp_set_factor_fast(si->lpp, cst, lr->in_mem_var, 1.0);
406                                                 }
407                                         }
408
409                                         ir_snprintf(buf, sizeof(buf), "ce2_%N_%N_%d", op, irn, i);
410                                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
411                                         lpp_set_factor_fast(si->lpp, cst, op_lr->is_remat_var, 1.0);
412                                         lpp_set_factor_fast(si->lpp, cst, op_lr->in_mem_var, -1.0);
413                                 }
414                         }
415                 }
416
417                         for(i = 0, n = get_irn_arity(irn); i < n; ++i) {
418                                 ir_node *op = get_irn_n(irn, i);
419                                 if(has_reg_class(si, op) && !is_Phi(irn))
420                                         pset_insert_ptr(live, op);
421                         }
422
423                 step++;
424         }
425
426         if(bl == get_irg_start_block(get_irn_irg(bl)))
427                 goto end;
428
429         /*
430          * Here, only the phis in the block and the values live in are in the
431          * live set.
432          *
433          * If a value is live in, it must be in a register in all predecessor
434          * blocks or in memory at the end of all predecessor blocks. Also, the
435          * closest use in the current block must then be from register or
436          * memory, respectively.
437          */
438         for(irn = pset_first(live); irn; irn = pset_next(live)) {
439                 live_range_t *lr = get_irn_link(irn);
440                 int is_phi = is_Phi(irn) && get_nodes_block(irn) == bl;
441                 int cst;
442
443                 /* Deprecated: Can be done with the first uses map */
444                 if(is_phi)
445                         lr->use_head->closest_use = lr;
446
447                 /*
448                  * Remind the liverange of the first use of a live (or phi) in the
449                  * current block.
450                  */
451                 add_first_use(si, bl, irn, lr);
452
453                 assert(has_reg_class(si, irn));
454                 assert(is_Phi(irn) || is_live_in(bl, irn));
455
456                 for(i = 0; i < n_preds; ++i) {
457                         ir_node *pred_bl     = get_Block_cfgpred_block(bl, i);
458                         ir_node *end_node    = is_phi ? get_irn_n(irn, i) : irn;
459                         live_range_t *op_lr  = get_live_range(si, end_node, pred_bl, -1);
460                         edge_reload_t *edge  = obstack_alloc(si->obst, sizeof(edge[0]));
461
462                         ir_snprintf(buf, sizeof(buf), "edge_%N_%N_%N_%N",
463                                         bl, pred_bl, end_node, op_lr->irn);
464                         edge->in_mem_var = lpp_add_var(si->lpp, buf, lpp_binary, COST_LOAD);
465                         edge->bl         = bl;
466                         edge->irn        = end_node;
467                         edge->pos        = i;
468
469
470                         ir_snprintf(buf, sizeof(buf), "cedge_%N_%N_%N_%N",
471                                         bl, pred_bl, end_node, op_lr->irn);
472                         cst = lpp_add_cst(si->lpp, buf, lpp_less, 0.0);
473                         lpp_set_factor_fast(si->lpp, cst, op_lr->in_mem_var, 1.0);
474                         lpp_set_factor_fast(si->lpp, cst, lr->in_mem_var, -1.0);
475                         lpp_set_factor_fast(si->lpp, cst, edge->in_mem_var, -1.0);
476                 }
477         }
478
479 end:
480
481   del_pset(live);
482 }
483
484 /**
485  * Add the costs for a store.
486  *
487  * If one of the uses is from memory, add additional costs for the
488  * spill.
489  *
490  * m_1 + ... + m_n - M * s <= 0
491  *
492  * @param si The ILP spilling environment.
493  */
494 static void add_store_costs(spill_ilp_t *si)
495 {
496         char buf[64];
497         irn_use_head_t *uh;
498         double costs = si->enable_store ? COST_STORE : 0.0;
499
500         for(uh = set_first(si->irn_use_heads); uh; uh = set_next(si->irn_use_heads)) {
501                 int cst;
502                 live_range_t *lr;
503
504                 ir_snprintf(buf, sizeof(buf), "cs_%N", uh->irn);
505                 cst = lpp_add_cst(si->lpp, buf, lpp_less, 0);
506
507                 ir_snprintf(buf, sizeof(buf), "s_%N", uh->irn);
508                 uh->spill_var = lpp_add_var(si->lpp, buf, lpp_binary, costs);
509                 lpp_set_factor_fast(si->lpp, cst, uh->spill_var, -BIGM);
510
511     list_for_each_entry(live_range_t, lr, &uh->head, list)
512                         lpp_set_factor_fast(si->lpp, cst, lr->in_mem_var, 1.0);
513         }
514 }
515
516 static INLINE int is_zero(double x)
517 {
518   return fabs(x) < 0.00001;
519 }
520
521 static int is_spilled(const spill_ilp_t *si, const live_range_t *lr)
522 {
523         return !is_zero(lpp_get_var_sol(si->lpp, lr->in_mem_var));
524 }
525
526 static int is_mem_phi(const ir_node *phi, void *data)
527 {
528         spill_ilp_t *si = data;
529         return is_spilled(si, get_use_head(si, phi)->closest_use);
530 }
531
532
533 static void writeback_results(spill_ilp_t *si)
534 {
535         irn_use_head_t *uh;
536         edge_reload_t *edge;
537
538         /* Look at each node and examine the usages. */
539         for(uh = set_first(si->irn_use_heads); uh; uh = set_next(si->irn_use_heads)) {
540                 live_range_t *lr;
541
542                 /* Go through all live ranges of the node. */
543                 list_for_each_entry(live_range_t, lr, &uh->head, list) {
544                         if(is_spilled(si, lr) && !is_end_of_block_use(lr))
545                                 be_add_reload(si->senv, lr->irn, lr->user);
546                 }
547         }
548
549         for(edge = si->edges; edge; edge = edge->next) {
550                 if(!is_zero(edge->in_mem_var))
551                         be_add_reload_on_edge(si->senv, edge->irn, edge->bl, edge->pos);
552         }
553
554         be_insert_spills_reloads(si->senv, NULL, is_mem_phi, si);
555 }
556
557 void be_spill_ilp(const be_main_session_env_t *session_env,
558     const arch_register_class_t *cls)
559 {
560         char problem_name[256];
561         struct obstack obst;
562         spill_ilp_t si;
563
564         ir_snprintf(problem_name, sizeof(problem_name), "%F_%s", session_env->irg, cls->name);
565
566         obstack_init(&obst);
567         si.session         = session_env;
568         si.obst            = &obst;
569         si.dbg             = firm_dbg_register("be.ra.spillilp");
570         si.senv            = be_new_spill_env(si.dbg, session_env, cls);
571         si.cls             = cls;
572         si.lpp             = new_lpp(problem_name, lpp_minimize);
573         si.irn_use_heads   = new_set(cmp_irn_use_head, 4096);
574         si.live_ranges     = new_set(cmp_live_range, 16384);
575         si.first_uses      = new_set(cmp_first_use, 4096);
576         si.edges           = NULL;
577         si.enable_remat    = 0;
578         si.enable_store    = 0;
579
580         firm_dbg_set_mask(si.dbg, DBG_LEVEL);
581         irg_block_walk_graph(session_env->irg, process_block, NULL, &si);
582         if(si.enable_store)
583                 add_store_costs(&si);
584
585 #ifdef DUMP_ILP
586         {
587                 FILE *f;
588                 char buf[256];
589
590                 ir_snprintf(buf, sizeof(buf), "spill-%s.ilp", problem_name);
591                 if((f = fopen(buf, "wt")) != NULL) {
592                         lpp_dump_plain(si.lpp, f);
593                         fclose(f);
594                 }
595         }
596 #endif
597
598         DBG((si.dbg, LEVEL_1, "%F\n", session_env->irg));
599 #ifdef SOLVE_LOCAL
600         lpp_solve_cplex(si.lpp);
601 #else
602         lpp_solve_net(si.lpp, LPP_SERVER, LPP_SOLVER);
603 #endif
604         assert(lpp_is_sol_valid(si.lpp) && "solution of ILP must be valid");
605
606         DBG((si.dbg, LEVEL_1, "\tnodes: %d, vars: %d, csts: %d\n",
607                                 set_count(si.irn_use_heads), si.lpp->var_next, si.lpp->cst_next));
608         DBG((si.dbg, LEVEL_1, "\titerations: %d, solution time: %g\n",
609                                 si.lpp->iterations, si.lpp->sol_time));
610
611 #ifdef DUMP_SOLUTION
612         {
613                 FILE *f;
614                 char buf[256];
615
616                 ir_snprintf(buf, sizeof(buf), "spill-%s.sol", problem_name);
617                 if((f = fopen(buf, "wt")) != NULL) {
618                         int i;
619                         for(i = 0; i < si.lpp->var_next; ++i) {
620                                 lpp_name_t *name = si.lpp->vars[i];
621                                 fprintf(f, "%20s %4d %10f\n", name->name, name->nr, name->value);
622                         }
623                         fclose(f);
624                 }
625         }
626 #endif
627
628   writeback_results(&si);
629
630 #ifdef DUMP_STATS
631         {
632                 FILE *f;
633
634                 ir_snprintf(buf, sizeof(buf), "%s-spill.stat", problem_name);
635                 if((f = fopen(buf, "wt")) != NULL) {
636                         fprintf(f, "%20s: %d\n", "nodes", set_count(si.irn_use_heads));
637                         fprintf(f, "%20s: %d\n", "vars", si.lpp->var_next);
638                         fprintf(f, "%20s: %d\n", "csts", si.lpp->cst_next);
639                         fprintf(f, "%20s: %f\n", "sol time", si.lpp->sol_time);
640                         fprintf(f, "%20s: %d\n", "spills", si->stats.n_spills);
641                         fprintf(f, "%20s: %d\n", "reloads", si->stats.n_reloads);
642                         fprintf(f, "%20s: %d\n", "remats", si->stats.n_remat);
643                         fclose(f);
644                 }
645         }
646 #endif
647
648   del_set(si.irn_use_heads);
649   del_set(si.live_ranges);
650   free_lpp(si.lpp);
651   obstack_free(&obst, NULL);
652 }