belive: Avoid duplicate map lookups when calculating the liveness of a node in a...
[libfirm] / ir / be / bespilldaemel.c
1 /*
2  * Copyright (C) 1995-2011 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       Naive spilling algorithm
23  * @author      Matthias Braun
24  * @date        20.09.2005
25  * @brief
26  *   This implements a naive spilling algorithm. It is designed to produce
27  *   similar effects to the spill decisions produced by traditional graph
28  *   coloring register allocators that spill while they are coloring the graph.
29  *
30  *   This spiller walks over all blocks and looks for places with too high
31  *   register pressure where it spills the values that are cheapest to spill.
32  *   Spilling in this context means placing a spill instruction behind the
33  *   definition of the value and a reload before each usage.
34  */
35 #include "config.h"
36
37 #include "debug.h"
38
39 #include "irnodeset.h"
40 #include "irgwalk.h"
41 #include "irprintf.h"
42 #include "iredges_t.h"
43 #include "error.h"
44
45 #include "beirg.h"
46 #include "bespill.h"
47 #include "bespillutil.h"
48 #include "bemodule.h"
49 #include "besched.h"
50 #include "bearch.h"
51 #include "be_t.h"
52 #include "benode.h"
53 #include "belive.h"
54
55 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
56
57 static spill_env_t                 *spill_env;
58 static unsigned                     n_regs;
59 static const arch_register_class_t *cls;
60 static const be_lv_t               *lv;
61 static bitset_t                    *spilled_nodes;
62
63 typedef struct spill_candidate_t spill_candidate_t;
64 struct spill_candidate_t {
65         double   costs;
66         ir_node *node;
67 };
68
69 static int compare_spill_candidates_desc(const void *d1, const void *d2)
70 {
71         const spill_candidate_t *c1 = (const spill_candidate_t*)d1;
72         const spill_candidate_t *c2 = (const spill_candidate_t*)d2;
73
74         return (int) (c1->costs - c2->costs);
75 }
76
77 static double get_spill_costs(ir_node *node)
78 {
79         ir_node *spill_place = skip_Proj(node);
80         double   costs       = be_get_spill_costs(spill_env, node, spill_place);
81
82         foreach_out_edge(node, edge) {
83                 ir_node *use = get_edge_src_irn(edge);
84
85                 /* keeps should be directly below the node */
86                 if (be_is_Keep(use)) {
87                         continue;
88                 }
89
90                 if (is_Phi(use)) {
91                         int      in    = get_edge_src_pos(edge);
92                         ir_node *block = get_nodes_block(use);
93
94                         costs += be_get_reload_costs_on_edge(spill_env, node, block, in);
95                 } else {
96                         costs += be_get_reload_costs(spill_env, node, use);
97                 }
98         }
99
100         return costs;
101 }
102
103 /**
104  * spills a node by placing a reload before each usage
105  */
106 static void spill_node(ir_node *node)
107 {
108         DBG((dbg, LEVEL_3, "\tspilling %+F\n", node));
109
110         foreach_out_edge(node, edge) {
111                 ir_node *use = get_edge_src_irn(edge);
112                 if (is_Anchor(use))
113                         continue;
114                 if (be_is_Keep(use))
115                         continue;
116
117                 if (is_Phi(use)) {
118                         int      in    = get_edge_src_pos(edge);
119                         ir_node *block = get_nodes_block(use);
120
121                         be_add_reload_on_edge(spill_env, node, block, in, cls, 1);
122                 } else {
123                         be_add_reload(spill_env, node, use, cls, 1);
124                 }
125         }
126
127         bitset_set(spilled_nodes, get_irn_idx(node));
128 }
129
130 static unsigned get_value_width(const ir_node *node)
131 {
132         const arch_register_req_t *req = arch_get_irn_register_req(node);
133         return req->width;
134 }
135
136 /**
137  * spill @p n nodes from a nodeset. Removes the nodes from the nodeset and
138  * sets the spilled bits in spilled_nodes.
139  */
140 static void do_spilling(ir_nodeset_t *live_nodes, ir_node *node)
141 {
142         size_t values_defined = 0;
143         be_foreach_definition(node, cls, value, req,
144                 (void)value;
145                 assert(req->width >= 1);
146                 values_defined += req->width;
147         );
148
149         /* we need registers for the non-live argument values */
150         size_t free_regs_needed = 0;
151         be_foreach_use(node, cls, in_req_, use, pred_req_,
152                 if (!ir_nodeset_contains(live_nodes, use)) {
153                         free_regs_needed += get_value_width(use);
154                 }
155         );
156
157         /* we can reuse all reloaded values for the defined values, but we might
158          * need even more registers */
159         if (values_defined > free_regs_needed)
160                 free_regs_needed = values_defined;
161
162         size_t n_live_nodes  = ir_nodeset_size(live_nodes);
163         int    spills_needed = (n_live_nodes + free_regs_needed) - n_regs;
164         if (spills_needed <= 0)
165                 return;
166         DBG((dbg, LEVEL_2, "\tspills needed after %+F: %d\n", node, spills_needed));
167
168         spill_candidate_t *candidates = ALLOCAN(spill_candidate_t, n_live_nodes);
169
170         /* construct array with spill candidates and calculate their costs */
171         size_t c = 0;
172         foreach_ir_nodeset(live_nodes, n, iter) {
173                 spill_candidate_t *candidate = & candidates[c];
174
175                 assert(!bitset_is_set(spilled_nodes, get_irn_idx(n)));
176
177                 candidate->node  = n;
178                 candidate->costs = get_spill_costs(n);
179                 ++c;
180         }
181         assert(c == n_live_nodes);
182
183         /* sort spill candidates */
184         qsort(candidates, n_live_nodes, sizeof(candidates[0]),
185               compare_spill_candidates_desc);
186
187         /* spill cheapest ones */
188         size_t cand_idx = 0;
189         while (spills_needed > 0) {
190                 if (cand_idx >= n_live_nodes) {
191                         panic("can't spill enough values for node %+F", node);
192                 }
193
194                 spill_candidate_t *candidate = &candidates[cand_idx];
195                 ir_node           *cand_node = candidate->node;
196                 ++cand_idx;
197
198                 if (arch_irn_is(skip_Proj_const(cand_node), dont_spill))
199                         continue;
200
201                 /* make sure the node is not an argument of the instruction */
202                 bool is_use = false;
203                 int arity = get_irn_arity(node);
204                 for (int i = 0; i < arity; ++i) {
205                         ir_node *in = get_irn_n(node, i);
206                         if (in == cand_node) {
207                                 is_use = true;
208                                 break;
209                         }
210                 }
211                 if (is_use)
212                         continue;
213
214                 spill_node(cand_node);
215                 ir_nodeset_remove(live_nodes, cand_node);
216                 spills_needed -= get_value_width(cand_node);
217         }
218 }
219
220 /**
221  * removes all values from the nodeset that are defined by node
222  */
223 static void remove_defs(ir_node *node, ir_nodeset_t *nodeset)
224 {
225         /* You must break out of your loop when hitting the first phi function. */
226         assert(!is_Phi(node));
227
228         be_foreach_definition(node, cls, value, req,
229                 ir_nodeset_remove(nodeset, value);
230         );
231 }
232
233 static void add_uses(ir_node *node, ir_nodeset_t *nodeset)
234 {
235         int arity = get_irn_arity(node);
236         for (int i = 0; i < arity; ++i) {
237                 ir_node *op = get_irn_n(node, i);
238
239                 if (arch_irn_consider_in_reg_alloc(cls, op) &&
240                                 !bitset_is_set(spilled_nodes, get_irn_idx(op))) {
241                         ir_nodeset_insert(nodeset, op);
242                 }
243         }
244 }
245
246 static __attribute__((unused))
247 void print_nodeset(ir_nodeset_t *nodeset)
248 {
249         foreach_ir_nodeset(nodeset, node, iter) {
250                 ir_fprintf(stderr, "%+F ", node);
251         }
252         fprintf(stderr, "\n");
253 }
254
255 /**
256  * make sure register pressure in a block is always equal or below the number
257  * of available registers
258  */
259 static void spill_block(ir_node *block, void *data)
260 {
261         (void) data;
262         DBG((dbg, LEVEL_1, "spilling block %+F\n", block));
263
264         /* construct set of live nodes at end of block */
265         ir_nodeset_t live_nodes;
266         ir_nodeset_init(&live_nodes);
267         be_liveness_end_of_block(lv, cls, block, &live_nodes);
268
269         /* remove already spilled nodes from liveset */
270         foreach_ir_nodeset(&live_nodes, node, iter) {
271                 DBG((dbg, LEVEL_2, "\t%+F is live-end... ", node));
272                 if (bitset_is_set(spilled_nodes, get_irn_idx(node))) {
273                         DBG((dbg, LEVEL_2, "but spilled; removing.\n"));
274                         ir_nodeset_remove_iterator(&live_nodes, &iter);
275                 } else {
276                         DBG((dbg, LEVEL_2, "keeping.\n"));
277                 }
278         }
279
280         /* walk schedule backwards and spill until register pressure is fine at
281          * each node */
282         sched_foreach_reverse(block, node) {
283                 if (is_Phi(node))
284                         break;
285
286                 remove_defs(node, &live_nodes);
287                 do_spilling(&live_nodes, node);
288                 add_uses(node, &live_nodes);
289         }
290
291         /* until now only the values of some phis have been spilled the phis itself
292          * are still there and occupy registers, so we need to count them and might
293          * have to spill some of them. */
294         int n_phi_values_spilled = 0;
295         sched_foreach(block, node) {
296                 if (!is_Phi(node))
297                         break;
298
299                 if (bitset_is_set(spilled_nodes, get_irn_idx(node))) {
300                         n_phi_values_spilled += get_value_width(node);
301                 }
302         }
303
304         int live_nodes_pressure = 0;
305         foreach_ir_nodeset(&live_nodes, node, iter) {
306                 live_nodes_pressure += get_value_width(node);
307         }
308
309         /* calculate how many of the phis need to be spilled */
310         int regpressure       = live_nodes_pressure + n_phi_values_spilled;
311         int phi_spills_needed = regpressure - n_regs;
312         DBG((dbg, LEVEL_3, "Regpressure before phis: %d phispills: %d\n",
313              regpressure, phi_spills_needed));
314
315         /* spill as many phis as needed */
316         /* TODO: we should really estimate costs of the phi spill as well...
317          * and preferably spill phis with lower costs... */
318         sched_foreach(block, node) {
319                 if (!is_Phi(node))
320                         break;
321                 if (phi_spills_needed <= 0)
322                         break;
323
324                 if (!bitset_is_set(spilled_nodes, get_irn_idx(node)))
325                         continue;
326
327                 be_spill_phi(spill_env, node);
328                 phi_spills_needed -= get_value_width(node);
329         }
330         assert(phi_spills_needed <= 0);
331
332         ir_nodeset_destroy(&live_nodes);
333 }
334
335 static void be_spill_daemel(ir_graph *irg, const arch_register_class_t *new_cls)
336 {
337         n_regs = be_get_n_allocatable_regs(irg, new_cls);
338         if (n_regs == 0)
339                 return;
340
341         be_assure_live_sets(irg);
342
343         spill_env     = be_new_spill_env(irg);
344         cls           = new_cls;
345         lv            = be_get_irg_liveness(irg);
346         spilled_nodes = bitset_malloc(get_irg_last_idx(irg));
347
348         DBG((dbg, LEVEL_1, "*** RegClass %s\n", cls->name));
349
350         irg_block_walk_graph(irg, spill_block, NULL, NULL);
351
352         bitset_free(spilled_nodes);
353
354         be_insert_spills_reloads(spill_env);
355         be_delete_spill_env(spill_env);
356 }
357
358 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_daemelspill)
359 void be_init_daemelspill(void)
360 {
361         static be_spiller_t daemel_spiller = {
362                 be_spill_daemel
363         };
364
365         be_register_spiller("daemel", &daemel_spiller);
366         FIRM_DBG_REGISTER(dbg, "firm.be.spilldaemel");
367 }