Corrected setting register classes of Return and Barrier nodes
[libfirm] / ir / be / beraextern.c
1 /**
2  * Author:      Daniel Grund
3  * Date:                17.01.2006
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  *
7  * Implementation of the RA-Interface for an external, (non-SSA) register allocator.
8  *
9  * The external register allocator is a program:
10  *    PROG -i INPUTFILE -o OUTPUTFILE
11  *
12  *   1) Input file defines the interference graph
13  *   2) Output file contains the instructions to perform
14  *
15
16
17 The input file format
18 ----------------------
19
20 inputfile       ::= regs nodes interf affinities .
21
22 regs            ::= 'regs' regcount .                                           // Anzahl der register (0..regcount-1), die zur Verfuegung stehen
23
24 nodes           ::= 'nodes' '{' node* '}' .                                     // All nodes in the graph
25
26 node            ::= node-info
27                           | node-info '<' reg-nr '>' .                          // Reg-nr is present in case of constraints
28
29 node-info       ::= node-nr spill-costs .
30
31 interf          ::= 'interferences' '{' i-edge* '}' .           // Interference edges of the graph
32
33 i-edge          ::= '(' node-nr ',' node-nr ')' .
34
35 affinities      ::= 'affinities' '{' a-edge* '}' .                      // Affinity edges of the graph
36
37 a-edge          ::= '(' node-nr ',' node-nr ',' weight ')' .
38
39
40 weight, regcount, node-nr ::= int32 .
41 spill-costs ::= int32 .                                                                 // negative spill costs indicate unspillable
42
43 The output file format
44 -----------------------
45
46 outputfile      ::= spills | allocs .
47
48 spills          ::= 'spills' node-nr+ .
49
50 allocs          ::= 'allocs' alloc* .
51
52 alloc           ::= node-nr reg-nr .
53
54
55 ******** End of file format docu ********/
56
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
60
61 #ifdef WIN32
62 #include <malloc.h>
63 #else
64 #include <alloca.h>
65 #endif
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <limits.h>
70 #ifdef WITH_LIBCORE
71 #include <libcore/lc_opts.h>
72 #include <libcore/lc_opts_enum.h>
73 #endif
74
75 #include "set.h"
76 #include "pset.h"
77 #include "pmap.h"
78 #include "bitset.h"
79
80 #include "irprintf_t.h"
81 #include "irnode_t.h"
82 #include "irgraph_t.h"
83 #include "irgwalk.h"
84 #include "iredges_t.h"
85 #include "irdom_t.h"
86 #include "phiclass.h"
87
88 #include "beraextern.h"
89 #include "beabi.h"
90 #include "bearch.h"
91 #include "benode_t.h"
92 #include "beirgmod.h"
93 #include "besched_t.h"
94 #include "beutil.h"
95 #include "belive_t.h"
96
97 #define DBG_LEVEL 2
98
99 typedef struct _var_info_t var_info_t;
100
101 /**
102  * Environment with all the needed stuff
103  */
104 typedef struct _be_raext_env_t {
105         firm_dbg_module_t *dbg;
106         arch_env_t *aenv;
107         const arch_register_class_t *cls;
108         ir_graph *irg;
109         dom_front_info_t *dom_info;
110
111         FILE *f;                                /**< file handle used for out- and input file */
112         set *vars;                              /**< contains all var_info_t */
113         int n_cls_vars;                 /**< length of the array cls_vars */
114         var_info_t **cls_vars;  /**< only the var_infos for current cls. needed for double iterating */
115 } be_raext_env_t;
116
117
118
119 /******************************************************************************
120     _    _      _
121    | |  | |    | |
122    | |__| | ___| |_ __   ___ _ __ ___
123    |  __  |/ _ \ | '_ \ / _ \ '__/ __|
124    | |  | |  __/ | |_) |  __/ |  \__ \
125    |_|  |_|\___|_| .__/ \___|_|  |___/
126                  | |
127                  |_|
128  *****************************************************************************/
129
130
131 #define pset_foreach(pset, irn)  for(irn=pset_first(pset); irn; irn=pset_next(pset))
132 #define set_foreach(set, e)  for(e=set_first(set); e; e=set_next(set))
133
134 /**
135  * Checks if _the_ result of the irn belongs to the
136  * current register class (raenv->cls)
137  * NOTE: Only the first result is checked.
138  */
139 #define is_res_in_reg_class(irn) arch_irn_has_reg_class(raenv->aenv, irn, -1, raenv->cls)
140
141 static INLINE ir_node *get_first_non_phi(pset *s) {
142         ir_node *irn;
143
144         pset_foreach(s, irn)
145                 if (!is_Phi(irn)) {
146                         pset_break(s);
147                         return irn;
148                 }
149
150         assert(0 && "There must be a non-phi-irn in this");
151         return NULL;
152 }
153
154 static INLINE ir_node *get_first_phi(pset *s) {
155         ir_node *irn;
156
157         pset_foreach(s, irn)
158                 if (is_Phi(irn)) {
159                         pset_break(s);
160                         return irn;
161                 }
162
163         assert(0 && "There must be a phi in this");
164         return NULL;
165 }
166
167 static int get_loop_weight(ir_node *irn) {
168         int cost = 0;
169         ir_loop *loop = get_irn_loop(get_nodes_block(irn));
170
171         if (loop) {
172                 int d = get_loop_depth(loop);
173                 cost = d*d;
174         }
175         return cost+1;
176 }
177
178 #define get_const_weight(irn) (1)
179
180 #define get_spill_weight(irn)    get_loop_weight(irn)
181 #define get_reload_weight(irn)   get_loop_weight(irn)
182 #define get_affinity_weight(irn) get_loop_weight(irn)
183
184 /******************************************************************************
185     _____                _            _____            _
186    / ____|              | |          / ____|          (_)
187   | |     ___  _ __  ___| |_ _ __   | |     ___  _ __  _  ___  ___
188   | |    / _ \| '_ \/ __| __| '__|  | |    / _ \| '_ \| |/ _ \/ __|
189   | |___| (_) | | | \__ \ |_| |     | |___| (_) | |_) | |  __/\__ \
190    \_____\___/|_| |_|___/\__|_|      \_____\___/| .__/|_|\___||___/
191                                                 | |
192                                                 |_|
193  *****************************************************************************/
194
195 static void handle_constraints_walker(ir_node *irn, void *env) {
196         be_raext_env_t *raenv = env;
197         arch_register_req_t req;
198         int pos, max;
199
200         /* handle output constraints
201          * user -> irn    becomes    user -> cpy -> irn
202          */
203         arch_get_register_req(raenv->aenv, &req, irn, -1);
204         if (arch_register_req_is(&req, limited)) {
205                 ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), irn);
206
207                 /* all users of the irn use the copy instead */
208                 sched_add_after(irn, cpy);
209                 edges_reroute(irn, cpy, raenv->irg);
210         }
211
212
213         /* handle input constraints by converting them into output constraints
214          * of copies of the former argument
215          * irn -> arg   becomes  irn -> copy -> arg
216      */
217         for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
218                 arch_get_register_req(raenv->aenv, &req, irn, pos);
219                 if (arch_register_req_is(&req, limited)) {
220                         ir_node *arg = get_irn_n(irn, pos);
221                         ir_node *cpy = be_new_Copy(req.cls, raenv->irg, get_nodes_block(irn), arg);
222
223                         /* use the copy instead */
224                         sched_add_before(irn, cpy);
225                         set_irn_n(irn, pos, cpy);
226
227                         /* set an out constraint for the copy */
228                         be_set_constr_limited(cpy, -1, &req);
229                 }
230         }
231 }
232
233 static void handle_constraints(be_raext_env_t *raenv) {
234         irg_walk_graph(raenv->irg, NULL, handle_constraints_walker, raenv);
235 }
236
237
238 /******************************************************************************
239      _____ _____              _____            _
240     / ____/ ____|  /\        |  __ \          | |
241    | (___| (___   /  \ ______| |  | | ___  ___| |_ _ __
242     \___ \\___ \ / /\ \______| |  | |/ _ \/ __| __| '__|
243     ____) |___) / ____ \     | |__| |  __/\__ \ |_| |
244    |_____/_____/_/    \_\    |_____/ \___||___/\__|_|
245
246  *****************************************************************************/
247
248 #define mark_as_done(irn, pos)                  set_irn_link(irn, INT_TO_PTR(pos+1))
249 #define has_been_done(irn, pos)                 (PTR_TO_INT(get_irn_link(irn)) > pos)
250
251 /**
252  * Insert a copy for the argument of @p start_phi found at position @p pos.
253  * Also searches a phi-loop of arbitrary length to detect and resolve
254  *   the class of phi-swap-problems. To search for a loop recursion is used.
255  *
256  * 1) Simplest case (phi with a non-phi arg):
257  *     A single copy is inserted.
258  *
259  * 2) Phi chain (phi (with phi-arg)* with non=phi arg):
260  *     Several copies are placed, each after returning from recursion.
261  *
262  * 3) Phi-loop:
263  *     On detection a loop breaker is inserted, which is a copy of the start_phi.
264  *     This copy then pretends beeing the argumnent of the last phi.
265  *     Now case 2) can be used.
266  *
267  * The values of @p start_phi and @p pos never change during recursion.
268  *
269  * @p raenv      Environment with all the stuff needed
270  * @p start_phi  Phi node to process
271  * @p pos        Argument position to insert copy/copies for
272  * @p curr_phi   Phi node currently processed during recursion. Equals start_phi on initial call
273  *
274  * @return NULL  If no copy is necessary
275  *         NULL  If the phi has already been processed at this pos
276  *               Link field is used to keep track of processed positions
277  *         In all other cases the ir_node *copy which was placed is returned.
278  */
279 static ir_node *insert_copies(be_raext_env_t *raenv, ir_node *start_phi, int pos, ir_node *curr_phi) {
280         ir_node *arg = get_irn_n(curr_phi, pos);
281         ir_node *arg_blk = get_nodes_block(arg);
282         ir_node *pred_blk = get_Block_cfgpred_block(get_nodes_block(curr_phi), pos);
283         ir_node *curr_cpy, *last_cpy;
284
285         assert(is_Phi(start_phi) && is_Phi(curr_phi));
286
287         if (has_been_done(start_phi, pos))
288                 return NULL;
289
290         /* In case this is a 'normal' phi we insert at the
291          * end of the pred block before cf nodes */
292         last_cpy = sched_skip(pred_blk, 0, sched_skip_cf_predicator, raenv->aenv);
293         last_cpy = sched_next(last_cpy);
294
295         /* If we detect a loop stop recursion. */
296         if (arg == start_phi) {
297                 ir_node *loop_breaker;
298                 if (start_phi == curr_phi) {
299                         /* Phi directly uses itself. No copy necessary */
300                         return NULL;
301                 }
302
303                 /* At least 2 phis are involved */
304                 /* Insert a loop breaking copy (an additional variable T) */
305                 loop_breaker = be_new_Copy(raenv->cls, raenv->irg, pred_blk, start_phi);
306                 sched_add_before(last_cpy, loop_breaker);
307
308                 arg = loop_breaker;
309         }
310
311         /* If arg is a phi in the same block we have to continue search */
312         if (is_Phi(arg) && arg_blk == get_nodes_block(start_phi))
313                 last_cpy = insert_copies(raenv, start_phi, pos, arg);
314
315         /* Insert copy of argument (may be the loop-breaker) */
316         curr_cpy = be_new_Copy(raenv->cls, raenv->irg, pred_blk, arg);
317         set_irn_n(curr_phi, pos, curr_cpy);
318         mark_as_done(curr_phi, pos);
319         sched_add_before(last_cpy, curr_cpy);
320         return curr_cpy;
321 }
322
323
324 /**
325  * Perform simple SSA-destruction with copies.
326  * The order of processing _must_ be
327  *  for all positions {
328  *    for all phis {
329  *      doit
330  *    }
331  *  }
332  * else the magic to keep track of processed phi-positions will fail in
333  * function 'insert_copies'
334  */
335 static void ssa_destr_simple_walker(ir_node *blk, void *env) {
336         be_raext_env_t *raenv = env;
337         int pos, max;
338         ir_node *phi;
339
340         /* for all argument positions of the phis */
341         for (pos=0, max=get_irn_arity(blk); pos<max; ++pos) {
342
343                 /* for all phi nodes (which are scheduled first) */
344                 sched_foreach(blk, phi) {
345                         if (!is_Phi(phi))
346                                 break;
347
348                         if (arch_irn_is_ignore(raenv->aenv, phi))
349                                 continue;
350
351                         raenv->cls = arch_get_irn_reg_class(raenv->aenv, phi, -1);
352                         insert_copies(raenv, phi, pos, phi);
353                 }
354         }
355 }
356
357
358 static void ssa_destr_simple(be_raext_env_t *raenv) {
359         be_clear_links(raenv->irg);
360         irg_block_walk_graph(raenv->irg, ssa_destr_simple_walker, NULL, raenv);
361 }
362
363
364 static void ssa_destr_rastello(be_raext_env_t *raenv) {
365         assert(0 && "NYI");
366         exit(0xDeadBeef);
367         /*
368         phi_class_compute(raenv->irg);
369         irg_block_walk_graph(irg, ssa_destr_rastello, NULL, &raenv);
370         */
371 }
372
373 /******************************************************************************
374    __      __   _       ___   __      __
375    \ \    / /  | |     |__ \  \ \    / /
376     \ \  / /_ _| |___     ) |  \ \  / /_ _ _ __ ___
377      \ \/ / _` | / __|   / /    \ \/ / _` | '__/ __|
378       \  / (_| | \__ \  / /_     \  / (_| | |  \__ \
379        \/ \__,_|_|___/ |____|     \/ \__,_|_|  |___/
380  *****************************************************************************/
381
382 /**
383  * This struct maps a variable (nr) to the values belonging to this variable
384  */
385 struct _var_info_t {
386         int var_nr;             /* the key */
387         pset *values;   /* the ssa-values belonging to this variable */
388 };
389
390 #define SET_REMOVED -1
391
392 /**
393  * The link field of an irn points to the var_info struct
394  * representing the corresponding variable.
395  */
396 #define set_var_info(irn, vi)                           set_irn_link(irn, vi)
397 #define get_var_info(irn)                                       ((var_info_t *)get_irn_link(irn))
398
399 #define HASH_VAR_NR(var_nr) var_nr
400
401 static int compare_var_infos(const void *e1, const void *e2, size_t size) {
402         const var_info_t *v1 = e1;
403         const var_info_t *v2 = e2;
404
405         if (v1->var_nr == SET_REMOVED || v2->var_nr == SET_REMOVED)
406                 return 1;
407
408         return v1->var_nr != v2->var_nr;
409 }
410
411 static INLINE var_info_t *var_find(set *vars, int var_nr) {
412         var_info_t vi;
413         vi.var_nr = var_nr;
414
415         return set_find(vars, &vi, sizeof(vi), HASH_VAR_NR(var_nr));
416 }
417
418 static INLINE var_info_t *var_find_or_insert(set *vars, int var_nr) {
419         var_info_t vi, *found;
420         memset(&vi, 0, sizeof(vi));
421         vi.var_nr = var_nr;
422
423         found = set_insert(vars, &vi, sizeof(vi), HASH_VAR_NR(var_nr));
424
425         if (!found->values)
426                 found->values  = pset_new_ptr(1);
427
428         return found;
429 }
430
431 /**
432  * Adds a value to a variable. Sets all pointers accordingly.
433  */
434 static INLINE var_info_t *var_add_value(be_raext_env_t *raenv, int var_nr, ir_node *irn) {
435         var_info_t *vi = var_find_or_insert(raenv->vars, var_nr);
436
437         /* var 2 value mapping */
438         pset_insert_ptr(vi->values, irn);
439
440         /* value 2 var mapping */
441         set_var_info(irn, vi);
442
443         return vi;
444 }
445
446 static INLINE pset *get_var_values(be_raext_env_t *raenv, int var_nr) {
447         var_info_t *vi = var_find(raenv->vars, var_nr);
448         assert(vi && "Variable does not exist");
449         return vi->values;
450 }
451
452 /**
453  * Define variables (numbers) for all SSA-values.
454  * All values in a phi class get assigned the same variable name.
455  * The link field maps values to the var-name
456  */
457 static void values_to_vars(ir_node *irn, void *env) {
458         be_raext_env_t *raenv = env;
459         int nr;
460         pset *vals;
461
462         if(arch_get_irn_reg_class(raenv->aenv, irn, -1) == NULL)
463                 return;
464
465         vals = get_phi_class(irn);
466
467         if (vals) {
468                 nr = get_irn_node_nr(get_first_phi(vals));
469         } else {
470                 /* not a phi class member, value == var */
471                 nr = get_irn_node_nr(irn);
472                 vals = pset_new_ptr(1);
473                 pset_insert_ptr(vals, irn);
474         }
475
476         /* values <--> var mapping */
477         pset_foreach(vals, irn) {
478                 DBG((raenv->dbg, 0, "Var %d contains %+F\n", nr, irn));
479                 var_add_value(raenv, nr, irn);
480         }
481 }
482
483
484 /******************************************************************************
485     _____
486    |  __ \
487    | |  | |_   _ _ __ ___  _ __   ___ _ __
488    | |  | | | | | '_ ` _ \| '_ \ / _ \ '__|
489    | |__| | |_| | | | | | | |_) |  __/ |
490    |_____/ \__,_|_| |_| |_| .__/ \___|_|
491                           | |
492                           |_|
493  *****************************************************************************/
494
495
496 static void extract_vars_of_cls(be_raext_env_t *raenv) {
497         int count = 0;
498         var_info_t *vi;
499
500         raenv->cls_vars = malloc(set_count(raenv->vars) * sizeof(*raenv->cls_vars));
501         assert(raenv->cls_vars);
502
503         set_foreach(raenv->vars, vi)
504                 if (is_res_in_reg_class(get_first_non_phi(vi->values)))
505                         raenv->cls_vars[count++] = vi;
506
507         raenv->cls_vars = realloc(raenv->cls_vars, count * sizeof(*raenv->cls_vars));
508         assert(raenv->cls_vars);
509
510         raenv->n_cls_vars = count;
511 }
512
513
514 /**
515  * Check if node irn has a limited-constraint at position pos.
516  * If yes, dump it to FILE raenv->f
517  */
518 static INLINE void dump_constraint(be_raext_env_t *raenv, ir_node *irn, int pos) {
519         bitset_t *bs = bitset_alloca(raenv->cls->n_regs);
520         arch_register_req_t req;
521
522         arch_get_register_req(raenv->aenv, &req, irn, pos);
523         if (arch_register_req_is(&req, limited)) {
524                 int reg_nr;
525                 req.limited(req.limited_env, bs);
526                 reg_nr = bitset_next_set(bs, 0);
527                 fprintf(raenv->f, "<%d>", reg_nr);
528                 assert(-1 == bitset_next_set(bs, reg_nr+1) && "Constraints with more than 1 possible register are not supported");
529         }
530 }
531
532 #define UNSPILLABLE -1
533
534 static INLINE int get_spill_costs(be_raext_env_t *raenv, var_info_t *vi) {
535         ir_node *irn;
536         int c_spills=0, c_reloads=0;
537
538         pset_foreach(vi->values, irn) {
539                 if (arch_irn_is_ignore(raenv->aenv, irn) || be_is_Reload(irn)) {
540                         pset_break(vi->values);
541                         return UNSPILLABLE;
542                 }
543
544                 if (is_Phi(irn)) {
545                         /* number of reloads is the number of non-phi uses of all values of this var */
546                         const ir_edge_t *edge;
547                         foreach_out_edge(irn, edge)
548                                 if (!is_Phi(edge->src))
549                                         c_reloads += get_reload_weight(edge->src);
550                 } else {
551                         /* number of spills is the number of non-phi values for this var */
552                         c_spills += get_spill_weight(irn);
553                 }
554         }
555
556         return c_spills + c_reloads;
557 }
558
559 static void dump_nodes(be_raext_env_t *raenv) {
560         FILE *f = raenv->f;
561         int i;
562
563         fprintf(f, "\nnodes {\n");
564
565         for (i=0; i<raenv->n_cls_vars; ++i) {
566                 var_info_t *vi = raenv->cls_vars[i];
567
568                 if (vi->var_nr == SET_REMOVED)
569                         continue;
570
571                 fprintf(f, "%d %d", vi->var_nr, get_spill_costs(raenv, vi));
572                 dump_constraint(raenv, get_first_non_phi(vi->values), -1);
573                 fprintf(f, "\n");
574         }
575
576         fprintf(f, "}\n");
577         fflush(f);
578 }
579
580
581 static void dump_interferences(be_raext_env_t *raenv) {
582         int i,o;
583         var_info_t *vi1, *vi2;
584         ir_node *irn1, *irn2;
585         FILE *f = raenv->f;
586
587         fprintf(f, "\ninterferences {\n");
588
589         for (i=0; i<raenv->n_cls_vars; ++i) {
590                 vi1 = raenv->cls_vars[i];
591
592                 if (vi1->var_nr == SET_REMOVED)
593                         continue;
594
595                 for (o=i+1; o<raenv->n_cls_vars; ++o) {
596                         vi2 = raenv->cls_vars[o];
597
598                         if (vi2->var_nr == SET_REMOVED)
599                                 continue;
600
601                         pset_foreach(vi1->values, irn1)
602                                 pset_foreach(vi2->values, irn2)
603                                         if (values_interfere(irn1, irn2)) {
604                                                 pset_break(vi1->values);
605                                                 pset_break(vi2->values);
606                                                 fprintf(f, "(%d, %d)\n", vi1->var_nr, vi2->var_nr);
607                                                 goto NextVar;
608                                         }
609
610 NextVar: ;
611                 }
612         }
613         fprintf(f, "}\n");
614 }
615
616 static void dump_affinities_walker(ir_node *irn, void *env) {
617         be_raext_env_t *raenv = env;
618         arch_register_req_t req;
619         int pos, max;
620         var_info_t *vi1, *vi2;
621
622         if (arch_get_irn_reg_class(raenv->aenv, irn, -1) != raenv->cls || arch_irn_is_ignore(raenv->aenv, irn))
623                 return;
624
625         vi1 = get_var_info(irn);
626
627         /* copies have affinities */
628         if (arch_irn_classify(raenv->aenv, irn) == arch_irn_class_copy) {
629                 ir_node *other = get_irn_n(irn, be_pos_Copy_orig);
630
631                 if (! arch_irn_is_ignore(raenv->aenv, other)) {
632                         vi2 = get_var_info(other);
633
634                         fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_affinity_weight(irn));
635                 }
636         }
637
638
639         /* should_be_equal constraints are affinites */
640         for (pos = 0, max = get_irn_arity(irn); pos<max; ++pos) {
641                 arch_get_register_req(raenv->aenv, &req, irn, pos);
642
643                 if (arch_register_req_is(&req, should_be_same) && arch_irn_is_ignore(raenv->aenv, req.other_same)) {
644                         vi2 = get_var_info(req.other_same);
645
646                         fprintf(raenv->f, "(%d, %d, %d)\n",  vi1->var_nr, vi2->var_nr, get_affinity_weight(irn));
647                 }
648         }
649 }
650
651
652 static void dump_affinities(be_raext_env_t *raenv) {
653         fprintf(raenv->f, "\naffinities {\n");
654         irg_walk_graph(raenv->irg, NULL, dump_affinities_walker, raenv);
655         fprintf(raenv->f, "}\n");
656 }
657
658 /**
659  * Dump all information needed by the external
660  * register allocator to a single file.
661  */
662 static void dump_to_file(be_raext_env_t *raenv, char *filename) {
663         FILE *f;
664
665         if (!(f = fopen(filename, "wt"))) {
666                 fprintf(stderr, "Could not open file %s for writing\n", filename);
667                 assert(0);
668                 exit(0xdeadbeef);
669         }
670         raenv->f = f;
671
672         /* dump register info */
673         fprintf(f, "regs %d\n", arch_register_class_n_regs(raenv->cls));
674
675         /* dump the interference graph */
676         dump_nodes(raenv);
677         dump_interferences(raenv);
678         dump_affinities(raenv);
679
680         fclose(f);
681 }
682
683 /******************************************************************************
684     ______                     _
685    |  ____|                   | |
686    | |__  __  _____  ___ _   _| |_ ___
687    |  __| \ \/ / _ \/ __| | | | __/ _ \
688    | |____ >  <  __/ (__| |_| | ||  __/
689    |______/_/\_\___|\___|\__,_|\__\___|
690  *****************************************************************************/
691
692 /**
693  * Execute the external register allocator specified in the
694  * firm-option firm.be.ra.ext.callee
695  */
696 static void execute(char *prog_to_call, char *out_file, char *result_file) {
697         char cmd_line[1024];
698         int ret_status;
699
700         snprintf(cmd_line, sizeof(cmd_line), "%s -i %s -o %s", prog_to_call, out_file, result_file);
701
702         ret_status = system(cmd_line);
703         assert(ret_status != -1 && "Invokation of external register allocator failed");
704         assert(ret_status == 0 && "External register allocator is unhappy with sth.");
705 }
706
707 /******************************************************************************
708                          _         _____                 _ _
709        /\               | |       |  __ \               | | |
710       /  \   _ __  _ __ | |_   _  | |__) |___  ___ _   _| | |_
711      / /\ \ | '_ \| '_ \| | | | | |  _  // _ \/ __| | | | | __|
712     / ____ \| |_) | |_) | | |_| | | | \ \  __/\__ \ |_| | | |_
713    /_/    \_\ .__/| .__/|_|\__, | |_|  \_\___||___/\__,_|_|\__|
714             | |   | |       __/ |
715             |_|   |_|      |___/
716  *****************************************************************************/
717
718 /**
719  * Spill a variable and add reloads before all uses.
720  */
721 static INLINE void var_add_spills_and_reloads(be_raext_env_t *raenv, int var_nr) {
722         var_info_t *vi = var_find(raenv->vars, var_nr);
723         ir_node *spill=NULL, *ctx, *irn;
724         ir_mode *mode;
725         const ir_edge_t *edge, *ne;
726         pset *spills  = pset_new_ptr(4);        /* the spills of this variable */
727         pset *reloads = pset_new_ptr(4);        /* the reloads of this variable */
728         int new_size, n_spills, n_reloads;
729
730         assert(vi && "Variable nr does not exist!");
731         assert(pset_count(vi->values) && "There are no values associated to this variable");
732
733         /* the spill context is set to an arbitrary node of the phi-class,
734          * or the node itself if it is not member of a phi class
735          */
736         if (pset_count(vi->values) == 1)
737                 ctx = get_first_non_phi(vi->values);
738         else
739                 ctx = get_first_phi(vi->values);
740
741         DBG((raenv->dbg, LEVEL_2, "Spill context: %+F\n", ctx));
742
743         /* for each value of this variable insert the spills */
744         pset_foreach(vi->values, irn) {
745                 if (is_Phi(irn)) {
746                         sched_remove(irn);
747                         continue;
748                 }
749
750                 /* all ordinary nodes must be spilled */
751                 DBG((raenv->dbg, LEVEL_2, "  spilling %+F\n", irn));
752                 spill = be_spill(raenv->aenv, irn, ctx);
753
754                 /* remember the spill */
755                 pset_insert_ptr(spills, spill);
756         }
757
758         assert(spill && "There must be at least one non-phi-node");
759
760         mode = get_irn_mode(get_irn_n(spill, be_pos_Spill_val));
761
762         /* insert reloads and wire them arbitrary*/
763         pset_foreach(vi->values, irn)
764                 foreach_out_edge_safe(irn, edge, ne) {
765                         ir_node *reload, *src = edge->src;
766                         if (is_Phi(src) || be_is_Spill(src))
767                                 continue;
768
769                         /* all real uses must be reloaded */
770                         DBG((raenv->dbg, LEVEL_2, "  reloading before %+F\n", src));
771                         reload = be_reload(raenv->aenv, raenv->cls, edge->src, mode, spill);
772                         set_irn_n(edge->src, edge->pos, reload);
773
774                         /* remember the reload */
775                         pset_insert_ptr(reloads, reload);
776                 }
777
778         /* correct the reload->spill pointers... */
779         be_ssa_constr_set(raenv->dom_info, spills);
780
781
782         /****** correct the variable <--> values mapping: ******
783          *
784          *  - if we had a phi class it gets split into several new variables
785          *  - all reloads are new variables
786          */
787         n_spills = pset_count(spills);
788         n_reloads = pset_count(reloads);
789
790         /* first make room for new pointers in the cls_var array */
791         new_size = raenv->n_cls_vars + n_reloads + ((n_spills>1) ? n_spills : 0);
792         raenv->cls_vars = realloc(raenv->cls_vars, (new_size) * sizeof(*raenv->cls_vars));
793         assert(raenv->cls_vars && "Out of mem!?");
794
795         /* if we had a real phi-class, we must... */
796         if (pset_count(spills) > 1) {
797                 /* ...remove the old variable corresponding to the phi class */
798                 vi->var_nr = SET_REMOVED;
799
800                 /* ...add new vars for each non-phi-member */
801                 pset_foreach(spills, irn) {
802                         ir_node *spilled = get_irn_n(irn, be_pos_Spill_val);
803                         raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(spilled), spilled);
804                 }
805         }
806
807         /* add new variables for all reloads */
808         pset_foreach(reloads, irn) {
809                 assert(get_irn_node_nr(irn) != 1089);
810                 raenv->cls_vars[raenv->n_cls_vars++] = var_add_value(raenv, get_irn_node_nr(irn), irn);
811         }
812
813         del_pset(spills);
814         del_pset(reloads);
815 }
816
817 #define INVALID_FILE_FORMAT assert(0 && "Invalid file format.")
818 #define BUFLEN 32
819 #define BUFCONV " %32s "
820
821 /**
822  * Read in the actions performed by the external allocator.
823  * Apply these transformations to the irg.
824  * @return 1 if an allocation was read in. 0 otherwise.
825  */
826 static int read_and_apply_results(be_raext_env_t *raenv, char *filename) {
827         FILE *f;
828         char buf[BUFLEN];
829         int is_allocation = 0;
830
831         if (!(f = fopen(filename, "rt"))) {
832                 fprintf(stderr, "Could not open file %s for reading\n", filename);
833                 assert(0);
834                 exit(0xdeadbeef);
835         }
836         raenv->f = f;
837
838         /* read the action */
839         if (fscanf(f, BUFCONV, buf) != 1)
840                 INVALID_FILE_FORMAT;
841
842         /* do we spill */
843         if (!strcmp(buf, "spills")) {
844                 int var_nr;
845                 while (fscanf(f, " %d ", &var_nr) == 1)
846                         var_add_spills_and_reloads(raenv, var_nr);
847         } else
848
849         /* or do we allocate */
850         if (!strcmp(buf, "allocs")) {
851                 int var_nr, reg_nr;
852
853                 is_allocation = 1;
854                 while (fscanf(f, " %d %d ", &var_nr, &reg_nr) == 2) {
855                         ir_node *irn;
856                         pset *vals = get_var_values(raenv, var_nr);
857
858                         assert(vals && "Variable nr does not exist!");
859                         pset_foreach(vals, irn)
860                                 arch_set_irn_register(raenv->aenv, irn, arch_register_for_index(raenv->cls, reg_nr));
861                 }
862         } else
863                 INVALID_FILE_FORMAT;
864
865         if (!feof(f))
866                 INVALID_FILE_FORMAT;
867
868         fclose(f);
869
870         return is_allocation;
871 }
872
873 static void check_allocation(be_raext_env_t *raenv) {
874         int i, o;
875
876         for (i=0; i<raenv->n_cls_vars; ++i) {
877                 var_info_t *vi1 = raenv->cls_vars[i];
878
879                 if (vi1->var_nr == SET_REMOVED)
880                         continue;
881
882                 for (o=0; o<i; ++o) {
883                         var_info_t *vi2 = raenv->cls_vars[o];
884                         ir_node *irn1, *irn2;
885
886                         if (vi2->var_nr == SET_REMOVED)
887                                 continue;
888
889                         pset_foreach(vi1->values, irn1)
890                                 pset_foreach(vi2->values, irn2)
891                                         if (values_interfere(irn1, irn2) && arch_get_irn_register(raenv->aenv, irn1) == arch_get_irn_register(raenv->aenv, irn2)) {
892                                                 dump_ir_block_graph_sched(raenv->irg, "ERROR");
893                                                 ir_fprintf(stdout, "SSA values %+F and %+F interfere. They belong to varible %d and %d respectively.\n", irn1, irn2, vi1->var_nr, vi2->var_nr);
894                                                 assert(0 && "ERROR graph dumped");
895                                         }
896                 }
897         }
898 }
899
900 /******************************************************************************
901     __  __       _
902    |  \/  |     (_)
903    | \  / | __ _ _ _ __
904    | |\/| |/ _` | | '_ \
905    | |  | | (_| | | | | |
906    |_|  |_|\__,_|_|_| |_|
907  *****************************************************************************/
908
909 /**
910  * Default values for options
911  */
912 static void (*ssa_destr)(be_raext_env_t*) = ssa_destr_simple;
913 static char callee[128] = "\"E:/user/kimohoff/public/register allocator\"";
914 //static char callee[128] = "/ben/kimohoff/ipd-registerallocator/register_allocator";
915
916
917 /**
918  * Allocate registers with an external program using a text-file interface.
919  *
920  * Do some computations (SSA-destruction and mapping of values--vars)
921  * Write file
922  * Execute external program
923  * Read in results and apply them
924  *
925  */
926 static void be_ra_extern_main(const be_irg_t *bi) {
927         be_main_env_t *env = bi->main_env;
928         ir_graph *irg = bi->irg;
929
930         be_raext_env_t raenv;
931         int clsnr, clss;
932         var_info_t *vi;
933
934         compute_doms(irg);
935         edges_assure(irg);
936
937         raenv.irg      = irg;
938         raenv.aenv     = env->arch_env;
939         raenv.dom_info = be_compute_dominance_frontiers(irg);
940         raenv.vars     = new_set(compare_var_infos, 64);
941         raenv.dbg      = firm_dbg_register("ir.be.raextern");
942         firm_dbg_set_mask(raenv.dbg, DBG_LEVEL);
943
944         /* Insert copies for constraints */
945         handle_constraints(&raenv);
946         be_dump(irg, "-extern-constr", dump_ir_block_graph_sched);
947
948         /* SSA destruction respectively transformation into "Conventional SSA" */
949         ssa_destr(&raenv);
950         be_dump(irg, "-extern-ssadestr", dump_ir_block_graph_sched);
951
952         /* Mapping of SSA-Values <--> Variables */
953         phi_class_compute(irg);
954         be_clear_links(irg);
955         irg_walk_graph(irg, values_to_vars, NULL, &raenv);
956
957
958         /* For all register classes */
959         for(clsnr = 0, clss = arch_isa_get_n_reg_class(raenv.aenv->isa); clsnr < clss; ++clsnr) {
960                 int done, round = 1;
961                 char out[256], in[256];
962
963                 raenv.cls = arch_isa_get_reg_class(raenv.aenv->isa, clsnr);
964
965                 extract_vars_of_cls(&raenv);
966
967                 do {
968                         ir_snprintf(out, sizeof(out), "%F-%s-%d.ra", irg, raenv.cls->name, round);
969                         ir_snprintf(in, sizeof(in), "%F-%s-%d.ra.res", irg, raenv.cls->name, round);
970
971                         be_liveness(irg);
972
973                         dump_to_file(&raenv, out);
974                         execute(callee, out, in);
975                         done = read_and_apply_results(&raenv, in);
976                         be_abi_fix_stack_nodes(bi->abi);
977
978                         ir_snprintf(in, sizeof(in), "-extern-%s-round-%d", raenv.cls->name, round);
979                         be_dump(irg, in, dump_ir_block_graph_sched);
980
981                         round++;
982                 } while (!done);
983
984                 check_allocation(&raenv);
985
986                 free(raenv.cls_vars);
987         }
988
989         be_dump(irg, "-extern-alloc", dump_ir_block_graph_sched);
990
991         /* Clean up */
992         set_foreach(raenv.vars, vi)
993                 del_pset(vi->values);
994         del_set(raenv.vars);
995         be_free_dominance_frontiers(raenv.dom_info);
996 }
997
998 /******************************************************************************
999      ____        _   _
1000     / __ \      | | (_)
1001    | |  | |_ __ | |_ _  ___  _ __  ___
1002    | |  | | '_ \| __| |/ _ \| '_ \/ __|
1003    | |__| | |_) | |_| | (_) | | | \__ \
1004     \____/| .__/ \__|_|\___/|_| |_|___/
1005           | |
1006           |_|
1007  *****************************************************************************/
1008
1009 #ifdef WITH_LIBCORE
1010
1011
1012 static const lc_opt_enum_func_ptr_items_t ssa_destr_items[] = {
1013         { "simple",     (int (*)()) ssa_destr_simple }, /* TODO make (void*) casts nicer */
1014         { "rastello",   (int (*)()) ssa_destr_rastello },
1015         { NULL,      NULL }
1016 };
1017
1018 static lc_opt_enum_func_ptr_var_t ssa_destr_var = {
1019          (int (**)()) &ssa_destr, ssa_destr_items
1020 };
1021
1022 static const lc_opt_table_entry_t be_ra_extern_options[] = {
1023         LC_OPT_ENT_ENUM_FUNC_PTR("ssa_destr", "SSA destruction flavor", &ssa_destr_var),
1024         LC_OPT_ENT_STR("callee", "The external program to call", callee, sizeof(callee)),
1025         { NULL }
1026 };
1027
1028 static void be_ra_extern_register_options(lc_opt_entry_t *root) {
1029         lc_opt_entry_t *grp = lc_opt_get_grp(root, "ext");
1030
1031         lc_opt_add_table(grp, be_ra_extern_options);
1032 }
1033
1034 #endif /* WITH_LIBCORE */
1035
1036 const be_ra_t be_ra_external_allocator = {
1037 #ifdef WITH_LIBCORE
1038         be_ra_extern_register_options,
1039 #endif
1040         be_ra_extern_main
1041 };