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