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