fab9262bcb21dd122d866aca641baee6c08517e1
[libfirm] / ir / be / beilpsched.c
1 /**
2  * Scheduling algorithms.
3  * An ILP scheduler based on
4  * "ILP-based Instruction Scheduling for IA-64"
5  * by Daniel Kaestner and Sebastian Winkel
6  *
7  * @date   22.10.2005
8  * @author Christian Wuerdig
9  * @cvs-id $Id$
10  */
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #ifdef WITH_ILP
16
17 #include <math.h>
18
19 #ifndef _WIN32
20 #include <strings.h>
21 #endif /* _WIN32 */
22
23 #include "irnode_t.h"
24 #include "irgwalk.h"
25 #include "irbitset.h"
26 #include "irphase_t.h"
27 #include "height.h"
28 #include "iredges.h"
29 #include "pdeq.h"
30 #include "debug.h"
31 #include "irtools.h"
32 #include "irdump.h"
33 #include "plist.h"
34
35 #include <lpp/lpp.h>
36 #include <lpp/lpp_net.h>
37
38 #include <libcore/lc_opts.h>
39 #include <libcore/lc_opts_enum.h>
40 #include <libcore/lc_timing.h>
41
42 #include "be.h"
43 #include "benode_t.h"
44 #include "besched_t.h"
45 #include "beilpsched.h"
46 #include "beutil.h"
47
48 typedef struct _ilpsched_options_t {
49         unsigned regpress;
50         unsigned time_limit;
51         char     log_file[1024];
52 } ilpsched_options_t;
53
54 typedef struct _unit_type_info_t {
55         int                            n_units;
56         const be_execution_unit_type_t *tp;
57 } unit_type_info_t;
58
59 /**
60  * holding the ILP variables of the different types
61  */
62 typedef struct _ilp_var_types_t {
63         int *x;   /* x_{nt}^k variables */
64         int *a;   /* a_{nt}^k variables */
65         int *y;   /* y_{nt}^k variables */
66 } ilp_var_types_t;
67
68 /**
69  * Holds alive variables for a node live-in to a block.
70  */
71 typedef struct _ilp_livein_node_t {
72         ir_node  *irn;
73         unsigned max_alive_steps;
74         int      *a;
75 } ilp_livein_node_t;
76
77 /* attributes for a node */
78 typedef struct _ilpsched_node_attr_t {
79         unsigned asap;                     /**< The ASAP scheduling control step */
80         unsigned alap;                     /**< The ALAP scheduling control step */
81         unsigned latency;                  /**< Latency of this node (needed for sorting) */
82         unsigned sched_point;              /**< the step in which the node is finally scheduled */
83         unsigned visit_idx;                /**< Index of the node having visited this node last */
84         unsigned consumer_idx;             /**< Index of the node having counted this node as consumer last */
85         unsigned n_consumer;               /**< Number of consumers */
86         ir_node  **block_consumer;         /**< List of consumer being in the same block */
87         waitq    *projkeeps;               /**< A List of Projs and Keeps belonging to this node */
88         unsigned block_idx     : 30;       /**< A unique per block index */
89         unsigned alap_changed  : 1;        /**< the current ALAP has changed, revisit preds */
90         unsigned is_dummy_node : 1;        /**< this node is assigned to DUMMY unit */
91         bitset_t *transitive_block_nodes;  /**< Set of transitive block nodes (predecessors
92                                                                                         for ASAP, successors for ALAP */
93         unsigned         n_unit_types;     /**< number of allowed execution unit types */
94         unit_type_info_t *type_info;       /**< list of allowed execution unit types */
95         ilp_var_types_t  ilp_vars;         /**< the different ILP variables */
96 } ilpsched_node_attr_t;
97
98 /* attributes for a block */
99 typedef struct _ilpsched_block_attr_t {
100         unsigned block_last_idx;        /**< The highest node index in block so far */
101         unsigned n_interesting_nodes;   /**< The number of nodes interesting for scheduling */
102         unsigned max_steps;             /**< Upper bound for block execution */
103         plist_t  *root_nodes;           /**< A list of nodes having no user in current block */
104         ir_node  *head_ilp_nodes;       /**< A linked list of nodes which will contribute to ILP */
105         pset     *livein_nodes;         /**< A set of nodes which are live-in to this block */
106 } ilpsched_block_attr_t;
107
108 typedef union _ilpsched_attr_ {
109         ilpsched_node_attr_t  node_attr;
110         ilpsched_block_attr_t block_attr;
111 } ilpsched_attr_t;
112
113 /* A irn for the phase and it's attributes (either node or block) */
114 typedef struct {
115         ir_node         *irn;
116         ilpsched_attr_t attr;
117 } be_ilpsched_irn_t;
118
119 /* The ILP scheduling environment */
120 typedef struct {
121         phase_t              ph;            /**< The phase */
122         ir_graph             *irg;          /**< The current irg */
123         heights_t            *height;       /**< The heights object of the irg */
124         void                 *irg_env;      /**< An environment for the irg scheduling, provided by the backend */
125         void                 *block_env;    /**< An environment for scheduling a block, provided by the backend */
126         const arch_env_t     *arch_env;
127         const arch_isa_t     *isa;          /**< The ISA */
128         const be_main_env_t  *main_env;
129         const be_machine_t   *cpu;          /**< the current abstract machine */
130         ilpsched_options_t   *opts;         /**< the ilp options for current irg */
131         const be_irg_t       *birg;         /**< The birg object */
132         be_options_t         *be_opts;      /**< backend options */
133         const ilp_sched_selector_t *sel;    /**< The ILP sched selector provided by the backend */
134         DEBUG_ONLY(firm_dbg_module_t *dbg);
135 } be_ilpsched_env_t;
136
137 /* convenience macros to handle phase irn data */
138 #define get_ilpsched_irn(ilpsched_env, irn) (phase_get_or_set_irn_data(&(ilpsched_env)->ph, (irn)))
139 #define is_ilpsched_block(node)             (is_Block((node)->irn))
140 #define get_ilpsched_block_attr(block)      (&(block)->attr.block_attr)
141 #define get_ilpsched_node_attr(node)        (&(node)->attr.node_attr)
142
143 /* check if node is considered for ILP scheduling */
144 #define consider_for_sched(isa, irn) \
145         (! (is_Block(irn)            ||  \
146                 is_normal_Proj(isa, irn) ||  \
147                 is_Phi(irn)              ||  \
148                 is_NoMem(irn)            ||  \
149                 is_Unknown(irn)          ||  \
150                 is_End(irn)                  \
151                 ))
152
153 /* gives the valid scheduling time step interval for a node */
154 #define VALID_SCHED_INTERVAL(na) ((na)->alap - (na)->asap + 1)
155
156 /* gives the valid interval where a node can die */
157 #define VALID_KILL_INTERVAL(ba, na) ((ba)->max_steps - (na)->asap + 1)
158
159 /* gives the corresponding ILP variable for given node, unit and time step */
160 #define ILPVAR_IDX(na, unit, control_step) \
161         ((unit) * VALID_SCHED_INTERVAL((na)) + (control_step) - (na)->asap + 1)
162
163 /* gives the corresponding dead nodes ILP variable for given node, unit and time step */
164 #define ILPVAR_IDX_DEAD(ba, na, unit, control_step) \
165         ((unit) * VALID_KILL_INTERVAL((ba), (na)) + (control_step) - (na)->asap + 1)
166
167 /* check if a double value is within an epsilon environment of 0 */
168 #define LPP_VALUE_IS_0(dbl) (fabs((dbl)) <= 1e-10)
169
170 #define ilp_timer_push(t)         lc_timer_push((t))
171 #define ilp_timer_pop()           lc_timer_pop()
172 #define ilp_timer_elapsed_usec(t) lc_timer_elapsed_usec((t))
173
174 /* option variable */
175 static ilpsched_options_t ilp_opts = {
176         1,     /* default is with register pressure constraints */
177         300,   /* 300 sec per block time limit */
178         ""     /* no log file */
179 };
180
181 /* ILP options */
182 static const lc_opt_table_entry_t ilpsched_option_table[] = {
183         LC_OPT_ENT_BOOL("regpress",  "Use register pressure constraints", &ilp_opts.regpress),
184         LC_OPT_ENT_INT("time_limit", "ILP time limit per block", &ilp_opts.time_limit),
185         LC_OPT_ENT_STR("lpp_log",    "LPP logfile (stderr and stdout are supported)", ilp_opts.log_file, sizeof(ilp_opts.log_file)),
186         { NULL }
187 };
188
189 /*
190         We need this global variable as we compare nodes dependent on heights,
191         but we cannot pass any information to the qsort compare function.
192 */
193 static heights_t *glob_heights;
194
195 /**
196  * Check if irn is a Proj, which has no execution units assigned.
197  * @return 1 if irn is a Proj having no execution units assigned, 0 otherwise
198  */
199 static INLINE int is_normal_Proj(const arch_isa_t *isa, const ir_node *irn) {
200         return is_Proj(irn) && (arch_isa_get_allowed_execution_units(isa, irn) == NULL);
201 }
202
203 /**
204  * Skips normal Projs.
205  * @return predecessor if irn is a normal Proj, otherwise irn.
206  */
207 static INLINE ir_node *skip_normal_Proj(const arch_isa_t *isa, ir_node *irn) {
208         if (is_normal_Proj(isa, irn))
209                 return get_Proj_pred(irn);
210         return irn;
211 }
212
213 static INLINE int fixed_latency(const ilp_sched_selector_t *sel, ir_node *irn, void *env) {
214         unsigned lat = be_ilp_sched_latency(sel, irn, env);
215         if (lat == 0 && ! is_Proj(irn) && ! be_is_Keep(irn))
216                 lat = 1;
217         return lat;
218 }
219
220 static int cmp_live_in_nodes(const void *a, const void *b) {
221         const ilp_livein_node_t *n1 = a;
222         const ilp_livein_node_t *n2 = b;
223
224         return n1->irn != n2->irn;
225 }
226
227 /**
228  * Compare scheduling time steps of two be_ilpsched_irn's.
229  */
230 static int cmp_ilpsched_irn(const void *a, const void *b) {
231         be_ilpsched_irn_t    *n1   = *(be_ilpsched_irn_t **)a;
232         be_ilpsched_irn_t    *n2   = *(be_ilpsched_irn_t **)b;
233         ilpsched_node_attr_t *n1_a = get_ilpsched_node_attr(n1);
234         ilpsched_node_attr_t *n2_a = get_ilpsched_node_attr(n2);
235
236         if (n1_a->sched_point == n2_a->sched_point) {
237                 ir_node *irn_a = n1->irn;
238                 ir_node *irn_b = n2->irn;
239
240                 if (heights_reachable_in_block(glob_heights, irn_a, irn_b))
241                         return 1;
242                 if (heights_reachable_in_block(glob_heights, irn_b, irn_a))
243                         return -1;
244
245                 /*
246                         Ok, timestep is equal and the nodes are parallel,
247                         so check latency and schedule high latency first.
248                 */
249                 return QSORT_CMP(n2_a->latency, n1_a->latency);
250         }
251         else
252                 return QSORT_CMP(n1_a->sched_point, n2_a->sched_point);
253 }
254
255 /**
256  * In case there is no phase information for irn, initialize it.
257  */
258 static void *init_ilpsched_irn(phase_t *ph, ir_node *irn, void *old) {
259         be_ilpsched_irn_t *res = old ? old : phase_alloc(ph, sizeof(res[0]));
260
261         if (res == old) {
262                 /* if we have already some data: check for reinitialization */
263
264                 if (! is_Block(irn)) {
265                         ilpsched_node_attr_t *na = get_ilpsched_node_attr(res);
266
267                         if (! na->transitive_block_nodes) {
268                                 ir_node               *block      = get_nodes_block(irn);
269                                 be_ilpsched_irn_t     *block_node = phase_get_or_set_irn_data(ph, block);
270                                 ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
271
272                                 /* we are called after the block indices have been build: create bitset */
273                                 na->transitive_block_nodes = bitset_obstack_alloc(phase_obst(ph), ba->block_last_idx);
274                         }
275                         else {
276                                 /* we are called from reinit block data: clear the bitset */
277                                 bitset_clear_all(na->transitive_block_nodes);
278                                 na->visit_idx    = 0;
279                                 na->alap_changed = 1;
280                         }
281                 }
282                 return old;
283         }
284
285         res->irn = irn;
286
287         /* set ilpsched irn attributes (either block or irn) */
288         if (is_Block(irn)) {
289                 ilpsched_block_attr_t *ba = get_ilpsched_block_attr(res);
290
291                 ba->n_interesting_nodes = 0;
292                 ba->block_last_idx      = 0;
293                 ba->root_nodes          = plist_new();
294                 ba->head_ilp_nodes      = NULL;
295                 ba->livein_nodes        = new_pset(cmp_live_in_nodes, 16);
296                 ba->max_steps           = 0;
297         }
298         else {
299                 ilpsched_node_attr_t *na = get_ilpsched_node_attr(res);
300                 memset(na, 0, sizeof(*na));
301         }
302
303         return res;
304 }
305
306 /**
307  * Assign a per block unique number to each node.
308  */
309 static void build_block_idx(ir_node *irn, void *walk_env) {
310         be_ilpsched_env_t     *env = walk_env;
311         be_ilpsched_irn_t     *node, *block_node;
312         ilpsched_node_attr_t  *na;
313         ilpsched_block_attr_t *ba;
314
315         set_irn_link(irn, NULL);
316         if (! consider_for_sched(env->arch_env->isa, irn))
317                 return;
318
319         node       = get_ilpsched_irn(env, irn);
320         na         = get_ilpsched_node_attr(node);
321         block_node = get_ilpsched_irn(env, get_nodes_block(irn));
322         ba         = get_ilpsched_block_attr(block_node);
323
324         na->block_idx = ba->block_last_idx++;
325 }
326
327 /********************************************************
328  *                              __        _
329  *                             / /       | |
330  *   __ _ ___  __ _ _ __      / /    __ _| | __ _ _ __
331  *  / _` / __|/ _` | '_ \    / /    / _` | |/ _` | '_ \
332  * | (_| \__ \ (_| | |_) |  / /    | (_| | | (_| | |_) |
333  *  \__,_|___/\__,_| .__/  /_/      \__,_|_|\__,_| .__/
334  *                 | |                           | |
335  *                 |_|                           |_|
336  ********************************************************/
337
338 /**
339  * Add all nodes having no user in current block to last_nodes list.
340  */
341 static void collect_alap_root_nodes(ir_node *irn, void *walk_env) {
342         ir_node               *block;
343         const ir_edge_t       *edge;
344         be_ilpsched_irn_t     *block_node, *node;
345         ilpsched_block_attr_t *ba;
346         ilpsched_node_attr_t  *na;
347         int                   i, j;
348         be_ilpsched_env_t     *env           = walk_env;
349         int                   has_block_user = 0;
350         unsigned              n_consumer     = 0;
351         ir_edge_kind_t        ekind[2]       = { EDGE_KIND_NORMAL, EDGE_KIND_DEP };
352         ir_node               **consumer;
353         int                   idx;
354
355         if (! consider_for_sched(env->arch_env->isa, irn))
356                 return;
357
358         block    = get_nodes_block(irn);
359     idx      = get_irn_idx(irn);
360         consumer = NEW_ARR_F(ir_node *, 0);
361
362         DBG((env->dbg, LEVEL_3, "%+F (%+F) is interesting, examining ... ", irn, block));
363
364         /* check data and dependency out edges */
365         for (i = 0; i < 2 && ! has_block_user; ++i) {
366                 foreach_out_edge_kind(irn, edge, ekind[i]) {
367                         ir_node *user = get_edge_src_irn(edge);
368
369                         if (is_normal_Proj(env->arch_env->isa, user)) {
370                                 const ir_edge_t *user_edge;
371
372                                 if (get_irn_mode(user) == mode_X)
373                                         continue;
374
375                                 /* The ABI ensures, that there will be no ProjT nodes in the graph. */
376                                 for (j = 0; j < 2; ++j) {
377                                         foreach_out_edge_kind(user, user_edge, ekind[j]) {
378                                                 ir_node *real_user = get_edge_src_irn(user_edge);
379
380                                                 if (! is_Phi(real_user) && ! is_Block(real_user)) {
381                                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, real_user);
382                                                         ilpsched_node_attr_t *ua   = get_ilpsched_node_attr(node);
383
384                                                         /* skip already visited nodes */
385                                                         if (ua->consumer_idx == idx)
386                                                                 continue;
387
388                                                         /* check if node has user in this block and collect the user if it's a data user */
389                                                         if (get_nodes_block(real_user) == block) {
390                                                                 if (i == 0 && j == 0)
391                                                                         ARR_APP1(ir_node *, consumer, real_user);
392                                                                 has_block_user = 1;
393                                                         }
394
395                                                         /* only count data consumer */
396                                                         if (i == 0)
397                                                                 n_consumer++;
398
399                                                         /* mark user as visited by this node */
400                                                         ua->consumer_idx = idx;
401                                                 }
402                                         }
403                                 }
404                         }
405                         else if (is_Block(user)) {
406                                 continue;
407                         }
408                         else if (! is_Phi(user)) {
409                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, user);
410                                 ilpsched_node_attr_t *ua   = get_ilpsched_node_attr(node);
411
412                                 /* skip already visited nodes */
413                                 if (ua->consumer_idx == idx)
414                                         continue;
415
416                                 /* check if node has user in this block and collect the user if it's a data user */
417                                 if (get_nodes_block(user) == block) {
418                                         if (i == 0)
419                                                 ARR_APP1(ir_node *, consumer, user);
420                                         has_block_user = 1;
421                                 }
422
423                                 /* only count data consumer */
424                                 if (i == 0)
425                                         n_consumer++;
426
427                                 /* mark user visited by this node */
428                                 ua->consumer_idx = idx;
429                         }
430                         else if (get_nodes_block(user) != block) {
431                                 n_consumer++;
432                         }
433                 }
434         }
435
436         block_node = get_ilpsched_irn(env, block);
437         ba         = get_ilpsched_block_attr(block_node);
438
439         ba->n_interesting_nodes++;
440
441         /* current irn has no user inside this block, add to queue */
442         if (! has_block_user) {
443                 DB((env->dbg, LEVEL_3, "root node\n"));
444                 plist_insert_back(ba->root_nodes, irn);
445         }
446         else {
447                 DB((env->dbg, LEVEL_3, "normal node\n"));
448         }
449
450         /* record number of all consumer and the consumer within the same block */
451         node = get_ilpsched_irn(env, irn);
452         na   = get_ilpsched_node_attr(node);
453         na->n_consumer     = n_consumer;
454         na->block_consumer = NEW_ARR_D(ir_node *, phase_obst(&env->ph), ARR_LEN(consumer));
455         memcpy(na->block_consumer, consumer, ARR_LEN(consumer) * sizeof(na->block_consumer[0]));
456         DEL_ARR_F(consumer);
457 }
458
459 /**
460  * Calculate the ASAP scheduling step for current irn.
461  */
462 static void calculate_irn_asap(ir_node *irn, void *walk_env) {
463         be_ilpsched_env_t     *env = walk_env;
464         int                   i;
465         ir_node               *block;
466         be_ilpsched_irn_t     *node, *block_node;
467         ilpsched_node_attr_t  *na;
468         ilpsched_block_attr_t *ba;
469
470         /* These nodes are handled separate */
471         if (! consider_for_sched(env->arch_env->isa, irn))
472                 return;
473
474         DBG((env->dbg, LEVEL_2, "Calculating ASAP of node %+F ... ", irn));
475
476         block    = get_nodes_block(irn);
477         node     = get_ilpsched_irn(env, irn);
478         na       = get_ilpsched_node_attr(node);
479         na->asap = 1;
480
481         for (i = get_irn_ins_or_deps(irn) - 1; i >= 0; --i) {
482                 ir_node *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(irn, i));
483
484                 /* check for greatest distance to top */
485                 if (! is_Phi(pred) && ! is_NoMem(pred) && get_nodes_block(pred) == block) {
486                         be_ilpsched_irn_t    *pred_node = get_ilpsched_irn(env, pred);
487                         ilpsched_node_attr_t *pna       = get_ilpsched_node_attr(pred_node);
488                         unsigned             lat;
489
490                         lat         = fixed_latency(env->sel, pred, env->block_env);
491                         na->latency = lat;
492                         na->asap    = MAX(na->asap, pna->asap + lat);
493                 }
494         }
495
496         /* add node to ILP node list and update max_steps */
497         block_node = get_ilpsched_irn(env, block);
498         ba         = get_ilpsched_block_attr(block_node);
499
500         set_irn_link(irn, ba->head_ilp_nodes);
501         ba->head_ilp_nodes = irn;
502         ba->max_steps     += fixed_latency(env->sel, irn, env->block_env);
503
504         DB((env->dbg, LEVEL_2, "%u\n", na->asap));
505 }
506
507 /**
508  * Calculate the ALAP scheduling step of all irns in current block.
509  * Depends on max_steps being calculated.
510  */
511 static void calculate_block_alap(ir_node *block, void *walk_env) {
512         be_ilpsched_env_t     *env        = walk_env;
513         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
514         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
515         waitq                 *cur_queue  = new_waitq();
516         plist_element_t       *el;
517
518         assert(is_Block(block));
519
520         DBG((env->dbg, LEVEL_2, "Calculating ALAP for nodes in %+F (%u nodes, %u max steps)\n",
521                 block, ba->n_interesting_nodes, ba->max_steps));
522
523         /* TODO: Might be faster to use out edges and call phase_reinit_single_irn_data */
524         //phase_reinit_block_irn_data(&env->ph, block);
525
526         /* init start queue */
527         foreach_plist(ba->root_nodes, el) {
528                 waitq_put(cur_queue, plist_element_get_value(el));
529         }
530
531         /* repeat until all nodes are processed */
532         while (! waitq_empty(cur_queue)) {
533                 waitq *next_queue = new_waitq();
534
535                 /* process all nodes in current step */
536                 while (! waitq_empty(cur_queue)) {
537                         ir_node              *cur_irn = waitq_get(cur_queue);
538                         be_ilpsched_irn_t    *node    = get_ilpsched_irn(env, cur_irn);
539                         ilpsched_node_attr_t *na      = get_ilpsched_node_attr(node);
540                         int                  i;
541
542                         /* cur_node has no alap set -> it's a root node, set to max alap */
543                         if (na->alap == 0) {
544                                 na->alap = ba->max_steps;
545                                 DBG((env->dbg, LEVEL_2, "setting ALAP of node %+F to %u, handling preds:\n",
546                                         cur_irn, na->alap));
547                         }
548                         else {
549                                 DBG((env->dbg, LEVEL_2, "ALAP of node %+F is %u, handling preds:\n",
550                                         cur_irn, na->alap));
551                         }
552
553                         /* set the alap's of all predecessors */
554                         for (i = get_irn_ins_or_deps(cur_irn) - 1; i >= 0; --i) {
555                                 ir_node *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(cur_irn, i));
556
557                                 /* check for greatest distance to bottom */
558                                 if (! is_Phi(pred) && ! is_NoMem(pred) && get_nodes_block(pred) == block) {
559                                         be_ilpsched_irn_t    *pred_node = get_ilpsched_irn(env, pred);
560                                         ilpsched_node_attr_t *pna       = get_ilpsched_node_attr(pred_node);
561                                         unsigned             lat;
562
563                                         /* mark the predecessor as visited by current irn */
564                                         if (pna->visit_idx == get_irn_idx(cur_irn) && ! na->alap_changed)
565                                                 continue;
566                                         pna->visit_idx = get_irn_idx(cur_irn);
567
568                                         lat = fixed_latency(env->sel, pred, env->block_env);
569
570                                         /* set ALAP of current pred */
571                                         if (pna->alap == 0) {
572                                                 /* current ALAP is 0: node has not yet been visited */
573                                                 pna->alap_changed = 1;
574                                                 pna->alap         = na->alap - lat;
575                                         }
576                                         else if (pna->alap > na->alap - lat) {
577                                                 /* we found a longer path to root node: change ALAP */
578                                                 pna->alap         = na->alap - lat;
579                                                 pna->alap_changed = 1;
580                                         }
581                                         else {
582                                                 /* current ALAP is best found so far: keep it */
583                                                 pna->alap_changed = 0;
584                                         }
585
586                                         DBG((env->dbg, LEVEL_2, "\tsetting ALAP of node %+F to %u\n", pred, pna->alap));
587
588                                         /* enqueue node for next iteration */
589                                         if (get_irn_ins_or_deps(pred) > 0)
590                                                 waitq_put(next_queue, pred);
591                                 }
592                         }
593                 }
594
595                 /* prepare for next iteration */
596                 del_waitq(cur_queue);
597                 cur_queue = next_queue;
598         }
599 }
600
601 /**
602  * Free list of root nodes and the set of live-in nodes.
603  */
604 static void clear_unwanted_data(ir_node *block, void *walk_env) {
605         be_ilpsched_env_t     *env        = walk_env;
606         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
607         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
608
609         plist_free(ba->root_nodes);
610         ba->root_nodes = NULL;
611         del_pset(ba->livein_nodes);
612         ba->livein_nodes = NULL;
613 }
614
615 /**
616  * Refine the {ASAP(n), ALAP(n)} interval for the nodes.
617  * Set the ASAP/ALAP times of Projs and Keeps to their ancestor ones.
618  */
619 static void refine_asap_alap_times(ir_node *irn, void *walk_env) {
620         be_ilpsched_env_t    *env  = walk_env;
621         ir_node              *pred = irn;
622         be_ilpsched_irn_t    *node, *pred_node;
623         ilpsched_node_attr_t *na, *pna;
624
625         if (! consider_for_sched(env->arch_env->isa, irn))
626                 return;
627
628         if (! is_Proj(irn) && ! be_is_Keep(irn))
629                 return;
630
631         /* go to the ancestor */
632         if (be_is_Keep(irn))
633                 pred = get_irn_n(irn, 0);
634         pred = skip_Proj(pred);
635
636         node      = get_ilpsched_irn(env, irn);
637         pred_node = get_ilpsched_irn(env, pred);
638         na        = get_ilpsched_node_attr(node);
639         pna       = get_ilpsched_node_attr(pred_node);
640
641         na->asap = pna->asap;
642         na->alap = pna->alap;
643
644         /* record all Projs and Keeps for this node */
645         if (! pna->projkeeps)
646                 pna->projkeeps = new_waitq();
647         waitq_put(pna->projkeeps, irn);
648
649         DBG((env->dbg, LEVEL_2, "fixing ASAP/ALAP of %+F to %u/%u\n", irn, na->asap, na->alap));
650 }
651
652 /*******************************************
653  *           _              _       _
654  *          | |            | |     | |
655  *  ___  ___| |__   ___  __| |_   _| | ___
656  * / __|/ __| '_ \ / _ \/ _` | | | | |/ _ \
657  * \__ \ (__| | | |  __/ (_| | |_| | |  __/
658  * |___/\___|_| |_|\___|\__,_|\__,_|_|\___|
659  *
660  *******************************************/
661
662 static INLINE void check_for_keeps(waitq *keeps, ir_node *block, ir_node *irn) {
663         const ir_edge_t *edge;
664
665         foreach_out_edge(irn, edge) {
666                 ir_node *user = get_edge_src_irn(edge);
667
668                 if (be_is_Keep(user)) {
669                         assert(get_nodes_block(user) == block && "Keep must not be in different block.");
670                         waitq_put(keeps, user);
671                 }
672         }
673 }
674
675 /**
676  * Inserts @p irn before @p before into schedule and notifies backend.
677  */
678 static INLINE void notified_sched_add_before(be_ilpsched_env_t *env,
679         ir_node *before, ir_node *irn, unsigned cycle)
680 {
681         be_ilp_sched_node_scheduled(env->sel, irn, cycle, env->block_env);
682         sched_add_before(before, irn);
683 }
684
685 /**
686  * Adds a node, it's Projs (in case of mode_T nodes) and
687  * it's Keeps to schedule.
688  */
689 static void add_to_sched(be_ilpsched_env_t *env, ir_node *block, ir_node *irn, unsigned cycle) {
690         const ir_edge_t *edge;
691         waitq           *keeps = new_waitq();
692
693         /* mode_M nodes are not scheduled */
694         if (get_irn_mode(irn) == mode_M)
695                 return;
696
697         if (! sched_is_scheduled(irn))
698                 notified_sched_add_before(env, block, irn, cycle);
699
700         /* add Projs */
701         if (get_irn_mode(irn) == mode_T) {
702                 foreach_out_edge(irn, edge) {
703                         ir_node *user = get_edge_src_irn(edge);
704
705                         if ((to_appear_in_schedule(user) || get_irn_mode(user) == mode_b) &&
706                                 get_irn_n_edges(user) > 0)
707                         {
708                                 notified_sched_add_before(env, block, user, cycle);
709                         }
710
711                         check_for_keeps(keeps, block, user);
712                 }
713         }
714         else {
715                 check_for_keeps(keeps, block, irn);
716         }
717
718         /* add Keeps */
719         while (! waitq_empty(keeps)) {
720                 ir_node *keep = waitq_get(keeps);
721                 if (! sched_is_scheduled(keep))
722                         notified_sched_add_before(env, block, keep, cycle);
723         }
724
725         del_waitq(keeps);
726 }
727
728 /**
729  * Schedule all nodes in the given block, according to the ILP solution.
730  */
731 static void apply_solution(be_ilpsched_env_t *env, lpp_t *lpp, ir_node *block) {
732         be_ilpsched_irn_t     *block_node = get_ilpsched_irn(env, block);
733         ilpsched_block_attr_t *ba         = get_ilpsched_block_attr(block_node);
734         sched_info_t          *info       = get_irn_sched_info(block);
735         be_ilpsched_irn_t     **sched_nodes;
736         unsigned              i, l;
737         ir_node               *cfop, *irn;
738         const ir_edge_t       *edge;
739
740         /* init block schedule list */
741         INIT_LIST_HEAD(&info->list);
742         info->scheduled = 1;
743
744         /* collect nodes and their scheduling time step */
745         sched_nodes = NEW_ARR_F(be_ilpsched_irn_t *, 0);
746         if (ba->n_interesting_nodes == 0) {
747                 /* ignore */
748         }
749         else if (ba->n_interesting_nodes == 1) {
750                 be_ilpsched_irn_t *node = get_ilpsched_irn(env, ba->head_ilp_nodes);
751
752                 /* add the single node */
753                 ARR_APP1(be_ilpsched_irn_t *, sched_nodes, node);
754         }
755         else {
756                 /* check all nodes for their positive solution */
757                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
758                         be_ilpsched_irn_t    *node;
759                         ilpsched_node_attr_t *na;
760                         int                  tp_idx, found;
761                         unsigned             cur_var, t;
762
763                         node    = get_ilpsched_irn(env, irn);
764                         na      = get_ilpsched_node_attr(node);
765                         cur_var = 0;
766                         found   = 0;
767
768                         if (! na->is_dummy_node) {
769                                 for (tp_idx = na->n_unit_types - 1; ! found && tp_idx >= 0; --tp_idx) {
770                                         for (t = na->asap - 1; ! found && t <= na->alap - 1; ++t) {
771                                                 double cost = lpp_get_var_sol(lpp, na->ilp_vars.y[cur_var]);
772
773                                                 if (! LPP_VALUE_IS_0(cost)) {
774                                                         DBG((env->dbg, LEVEL_3, "%+F has additional regpressure costs of %f\n", irn, cost));
775                                                         found = 1;
776                                                 }
777                                         }
778                                 }
779                         }
780
781                         found = 0;
782                         /* go over all variables of a node until the non-zero one is found */
783                         for (tp_idx = na->n_unit_types - 1; ! found && tp_idx >= 0; --tp_idx) {
784                                 for (t = na->asap - 1; ! found && t <= na->alap - 1; ++t) {
785                                         double val = lpp_get_var_sol(lpp, na->ilp_vars.x[cur_var++]);
786
787                                         /* check, if variable is set to one (it's not zero then :) */
788                                         if (! LPP_VALUE_IS_0(val)) {
789                                                 na->sched_point = t;
790                                                 ARR_APP1(be_ilpsched_irn_t *, sched_nodes, node);
791                                                 DBG((env->dbg, LEVEL_2, "Schedpoint of %+F is %u at unit type %s\n",
792                                                         irn, t, na->type_info[tp_idx].tp->name));
793                                                 found = 1;
794                                         }
795                                 }
796                         }
797                 }
798
799                 glob_heights = env->height;
800                 /* sort nodes ascending by scheduling time step */
801                 qsort(sched_nodes, ARR_LEN(sched_nodes), sizeof(sched_nodes[0]), cmp_ilpsched_irn);
802         }
803
804         /* make all Phis ready and remember the single cf op */
805         cfop = NULL;
806         foreach_out_edge(block, edge) {
807                 irn = get_edge_src_irn(edge);
808
809                 switch (get_irn_opcode(irn)) {
810                         case iro_Phi:
811                                 add_to_sched(env, block, irn, 0);
812                                 break;
813                         case iro_Start:
814                         case iro_End:
815                         case iro_Proj:
816                         case iro_Bad:
817                         case iro_Unknown:
818                                 break;
819                         default:
820                                 if (is_cfop(irn)) {
821                                         assert(cfop == NULL && "Highlander - there can be only one");
822                                         cfop = irn;
823                                 }
824                         break;
825                 }
826         }
827
828         /* add all nodes from list */
829         for (i = 0, l = ARR_LEN(sched_nodes); i < l; ++i) {
830                 ilpsched_node_attr_t *na = get_ilpsched_node_attr(sched_nodes[i]);
831                 if (sched_nodes[i]->irn != cfop)
832                         add_to_sched(env, block, sched_nodes[i]->irn, na->sched_point);
833         }
834
835         /* schedule control flow node if not already done */
836         if (cfop && ! sched_is_scheduled(cfop))
837                 add_to_sched(env, block, cfop, 0);
838
839         DEL_ARR_F(sched_nodes);
840 }
841
842 /***************************************************************
843  *   _____ _      _____     _____           _   _
844  *  |_   _| |    |  __ \   / ____|         | | (_)
845  *    | | | |    | |__) | | (___   ___  ___| |_ _  ___  _ __
846  *    | | | |    |  ___/   \___ \ / _ \/ __| __| |/ _ \| '_ \
847  *   _| |_| |____| |       ____) |  __/ (__| |_| | (_) | | | |
848  *  |_____|______|_|      |_____/ \___|\___|\__|_|\___/|_| |_|
849  *
850  ***************************************************************/
851
852 /**
853  * Check if node can be executed on given unit type.
854  */
855 static INLINE int is_valid_unit_type_for_node(const be_execution_unit_type_t *tp, be_ilpsched_irn_t *node) {
856         int                  i;
857         ilpsched_node_attr_t *na = get_ilpsched_node_attr(node);
858
859         for (i = na->n_unit_types - 1; i >= 0; --i) {
860                 if (na->type_info[i].tp == tp)
861                         return i;
862         }
863
864         return -1;
865 }
866
867 /************************************************
868  *                   _       _     _
869  *                  (_)     | |   | |
870  *  __   ____ _ _ __ _  __ _| |__ | | ___  ___
871  *  \ \ / / _` | '__| |/ _` | '_ \| |/ _ \/ __|
872  *   \ V / (_| | |  | | (_| | |_) | |  __/\__ \
873  *    \_/ \__,_|_|  |_|\__,_|_.__/|_|\___||___/
874  *
875  ************************************************/
876
877 static int be_ilpsched_set_type_info(be_ilpsched_env_t *env, ir_node *irn, struct obstack *obst) {
878         const be_execution_unit_t ***execunits = arch_isa_get_allowed_execution_units(env->arch_env->isa, irn);
879         unsigned                  n_unit_types = 0;
880         be_ilpsched_irn_t         *node;
881         ilpsched_node_attr_t      *na;
882         unsigned                  unit_idx, tp_idx;
883
884         /* count number of available unit types for this node */
885         for (n_unit_types = 0; execunits[n_unit_types]; ++n_unit_types)
886                 /* just count */ ;
887
888         node = get_ilpsched_irn(env, irn);
889         na   = get_ilpsched_node_attr(node);
890
891         if (! na->type_info) {
892                 na->n_unit_types = n_unit_types;
893                 na->type_info    = NEW_ARR_D(unit_type_info_t, obst, n_unit_types);
894
895                 /* fill the type info array */
896                 for (tp_idx = 0; tp_idx < n_unit_types; ++tp_idx) {
897                         for (unit_idx = 0; execunits[tp_idx][unit_idx]; ++unit_idx) {
898                                 /* beware: we also count number of available units here */
899                                 if (be_machine_is_dummy_unit(execunits[tp_idx][unit_idx]))
900                                         na->is_dummy_node = 1;
901                         }
902
903                         na->type_info[tp_idx].tp      = execunits[tp_idx][0]->tp;
904                         na->type_info[tp_idx].n_units = unit_idx;
905                 }
906         }
907
908         return n_unit_types;
909 }
910
911 /**
912  * Returns the largest alap time of a user of @p irn.
913  * The user must be in block @p block.
914  */
915 static unsigned be_ilpsched_get_max_alap_user(be_ilpsched_env_t *env, ir_node *irn, ir_node *block) {
916         const ir_edge_t *edge;
917         unsigned        max_alap = 0;
918
919         foreach_out_edge(irn, edge) {
920                 ir_node *user = get_edge_src_irn(edge);
921
922                 if (get_nodes_block(user) == block) {
923                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, user);
924                         ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
925
926                         max_alap = MAX(max_alap, na->alap);
927                 }
928         }
929
930         assert(max_alap > 0);
931         return max_alap;
932 }
933
934 /**
935  * Create the following variables:
936  * - x_{nt}^k    binary     weigthed with: t
937  *      node n is scheduled at time step t to unit type k
938  * ==>> These variables represent the schedule
939  *
940  * - a_{nt}^k    binary     weighted with num_nodes
941  *      node n is alive at time step t on unit type k
942  *
943  * - y_{nt}^k    continuous  weighted with: num_nodes^2
944  *      register pressure over limit for unit type k
945  * ==>> These variables represent the register pressure
946  *
947  */
948 static void create_variables(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node, struct obstack *var_obst) {
949         char                  buf[1024];
950         ir_node               *irn;
951         unsigned              num_block_var, num_nodes;
952         ilp_livein_node_t     *livein;
953         ilpsched_block_attr_t *ba      = get_ilpsched_block_attr(block_node);
954         unsigned              weigth_y = ba->n_interesting_nodes * ba->n_interesting_nodes;
955         lc_timer_t            *t_var   = lc_timer_register("beilpsched_var", "create ilp variables");
956
957         ilp_timer_push(t_var);
958         num_block_var = num_nodes = 0;
959         foreach_linked_irns(ba->head_ilp_nodes, irn) {
960                 be_ilpsched_irn_t    *node;
961                 ilpsched_node_attr_t *na;
962                 unsigned             n_unit_types, tp_idx, n_var, cur_unit;
963                 unsigned             cur_var_ad, cur_var_x, cur_var_y, num_ad;
964                 int                  i;
965
966                 node         = get_ilpsched_irn(env, irn);
967                 na           = get_ilpsched_node_attr(node);
968                 n_unit_types = be_ilpsched_set_type_info(env, irn, var_obst);
969
970                 /* allocate space for ilp variables */
971                 na->ilp_vars.x = NEW_ARR_D(int, var_obst, n_unit_types * VALID_SCHED_INTERVAL(na));
972                 memset(na->ilp_vars.x, -1, ARR_LEN(na->ilp_vars.x) * sizeof(na->ilp_vars.x[0]));
973
974                 /* we need these variables only for "real" nodes */
975                 if (! na->is_dummy_node) {
976                         na->ilp_vars.y = NEW_ARR_D(int, var_obst, n_unit_types * VALID_SCHED_INTERVAL(na));
977                         memset(na->ilp_vars.y, -1, ARR_LEN(na->ilp_vars.y) * sizeof(na->ilp_vars.y[0]));
978
979                         num_ad         = ba->max_steps - na->asap + 1;
980                         na->ilp_vars.a = NEW_ARR_D(int, var_obst, n_unit_types * num_ad);
981                         memset(na->ilp_vars.a, -1, ARR_LEN(na->ilp_vars.a) * sizeof(na->ilp_vars.a[0]));
982                 }
983
984                 DBG((env->dbg, LEVEL_3, "\thandling %+F (asap %u, alap %u, unit types %u):\n",
985                         irn, na->asap, na->alap, na->n_unit_types));
986
987                 cur_var_x = cur_var_ad = cur_var_y = cur_unit = n_var = 0;
988                 /* create variables */
989                 for (tp_idx = 0; tp_idx < n_unit_types; ++tp_idx) {
990                         unsigned t;
991
992                         for (t = na->asap - 1; t <= na->alap - 1; ++t) {
993                                 /* x_{nt}^k variables */
994                                 snprintf(buf, sizeof(buf), "x_n%u_%s_%u",
995                                         get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
996                                 na->ilp_vars.x[cur_var_x++] = lpp_add_var(lpp, buf, lpp_binary, (double)(t + 1));
997                                 DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
998                                 /* variable counter */
999                                 n_var++;
1000                                 num_block_var++;
1001
1002                                 if (! na->is_dummy_node) {
1003                                         /* y_{nt}^k variables */
1004                                         snprintf(buf, sizeof(buf), "y_n%u_%s_%u",
1005                                                 get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1006                                         na->ilp_vars.y[cur_var_y++] = lpp_add_var(lpp, buf, lpp_continous, (double)(weigth_y));
1007                                         DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1008
1009                                         /* variable counter */
1010                                         n_var++;
1011                                         num_block_var++;
1012                                 }
1013                         }
1014
1015                         /* a node can die at any step t: asap(n) <= t <= U */
1016                         if (! na->is_dummy_node) {
1017                                 for (t = na->asap - 1; t <= ba->max_steps; ++t) {
1018
1019                                         /* a_{nt}^k variables */
1020                                         snprintf(buf, sizeof(buf), "a_n%u_%s_%u",
1021                                                 get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1022                                         na->ilp_vars.a[cur_var_ad++] = lpp_add_var(lpp, buf, lpp_binary, (double)(ba->n_interesting_nodes));
1023                                         DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1024
1025                                         /* variable counter */
1026                                         n_var++;
1027                                         num_block_var++;
1028                                 }
1029                         }
1030
1031                         /* collect live-in nodes */
1032                         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1033                                 ir_node *pred = get_irn_n(irn, i);
1034
1035                                 if (get_nodes_block(pred) != block_node->irn && consider_for_sched(env->arch_env->isa, pred)) {
1036                                         be_ilpsched_set_type_info(env, pred, var_obst);
1037                                         if (! na->is_dummy_node) {
1038                                                 ilp_livein_node_t *entry = obstack_alloc(var_obst, sizeof(*entry));
1039                                                 entry->irn = pred;
1040                                                 entry->a   = NULL;
1041                                                 pset_insert(ba->livein_nodes, entry, (unsigned)get_irn_idx(pred));
1042                                         }
1043                                 }
1044                         }
1045                 }
1046
1047                 DB((env->dbg, LEVEL_3, "%u variables created\n", n_var));
1048                 num_nodes++;
1049         }
1050
1051         /* create alive variables a_{nt}^k for live-ins */
1052         foreach_pset(ba->livein_nodes, livein) {
1053                 be_ilpsched_irn_t    *node;
1054                 ilpsched_node_attr_t *na;
1055                 unsigned             tp_idx, var_idx;
1056                 ir_node              *irn;
1057
1058                 irn  = livein->irn;
1059                 node = get_ilpsched_irn(env, irn);
1060                 na   = get_ilpsched_node_attr(node);
1061
1062                 livein->max_alive_steps = be_ilpsched_get_max_alap_user(env, irn, block_node->irn);
1063
1064                 livein->a = NEW_ARR_D(int, var_obst, na->n_unit_types * livein->max_alive_steps);
1065                 var_idx   = 0;
1066
1067                 /* create variables */
1068                 for (tp_idx = 0; tp_idx < na->n_unit_types; ++tp_idx) {
1069                         unsigned t;
1070
1071                         for (t = 0; t < livein->max_alive_steps; ++t) {
1072                                 /* a_{nt}^k variables */
1073                                 snprintf(buf, sizeof(buf), "al_n%u_%s_%u",
1074                                         get_irn_idx(irn), na->type_info[tp_idx].tp->name, t);
1075                                 livein->a[var_idx++] = lpp_add_var(lpp, buf, lpp_binary, (double)(ba->n_interesting_nodes));
1076                                 DBG((env->dbg, LEVEL_4, "\t\tcreated ILP variable %s\n", buf));
1077                                 num_block_var++;
1078                         }
1079                 }
1080         }
1081
1082         ilp_timer_pop();
1083         DBG((env->dbg, LEVEL_1, "... %u variables for %u nodes created (%g sec)\n",
1084                 num_block_var, num_nodes, ilp_timer_elapsed_usec(t_var) / 1000000.0));
1085 }
1086
1087 /*******************************************************
1088  *                      _             _       _
1089  *                     | |           (_)     | |
1090  *   ___ ___  _ __  ___| |_ _ __ __ _ _ _ __ | |_ ___
1091  *  / __/ _ \| '_ \/ __| __| '__/ _` | | '_ \| __/ __|
1092  * | (_| (_) | | | \__ \ |_| | | (_| | | | | | |_\__ \
1093  *  \___\___/|_| |_|___/\__|_|  \__,_|_|_| |_|\__|___/
1094  *
1095  *******************************************************/
1096
1097 /**
1098  * Create following ILP constraints:
1099  * - the assignment constraints:
1100  *     assure each node is executed once by exactly one (allowed) execution unit
1101  * - the dead node assignment constraints:
1102  *     assure a node can only die at most once
1103  * - the precedence constraints:
1104  *     assure that no data dependencies are violated
1105  */
1106 static void create_assignment_and_precedence_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1107         unsigned              num_cst_assign, num_cst_prec, num_cst_dead;
1108         char                  buf[1024];
1109         ir_node               *irn;
1110         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1111         bitset_t              *bs_block_irns = bitset_alloca(ba->block_last_idx);
1112         lc_timer_t            *t_cst_assign  = lc_timer_register("beilpsched_cst_assign", "create assignment constraints");
1113         lc_timer_t            *t_cst_prec    = lc_timer_register("beilpsched_cst_prec",   "create precedence constraints");
1114
1115         num_cst_assign = num_cst_prec = num_cst_dead = 0;
1116         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1117                 int                  cst, tp_idx, i;
1118                 unsigned             cur_var;
1119                 be_ilpsched_irn_t    *node;
1120                 ilpsched_node_attr_t *na;
1121
1122                 node    = get_ilpsched_irn(env, irn);
1123                 na      = get_ilpsched_node_attr(node);
1124                 cur_var = 0;
1125
1126                 /* the assignment constraint */
1127                 ilp_timer_push(t_cst_assign);
1128                 snprintf(buf, sizeof(buf), "assignment_cst_n%u", get_irn_idx(irn));
1129                 cst = lpp_add_cst_uniq(lpp, buf, lpp_equal, 1.0);
1130                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1131                 num_cst_assign++;
1132
1133                 lpp_set_factor_fast_bulk(lpp, cst, na->ilp_vars.x, ARR_LEN(na->ilp_vars.x), 1.0);
1134                 ilp_timer_pop();
1135
1136                 /* We have separate constraints for Projs and Keeps */
1137                 // ILP becomes infeasible ?!?
1138 //              if (is_Proj(irn) || be_is_Keep(irn))
1139 //                      continue;
1140
1141                 /* the precedence constraints */
1142                 ilp_timer_push(t_cst_prec);
1143                 bs_block_irns = bitset_clear_all(bs_block_irns);
1144                 for (i = get_irn_ins_or_deps(irn) - 1; i >= 0; --i) {
1145                         ir_node              *pred = skip_normal_Proj(env->arch_env->isa, get_irn_in_or_dep(irn, i));
1146                         unsigned             t_low, t_high, t;
1147                         be_ilpsched_irn_t    *pred_node;
1148                         ilpsched_node_attr_t *pna;
1149                         unsigned             delay;
1150
1151                         if (is_Phi(pred) || block_node->irn != get_nodes_block(pred) || is_NoMem(pred))
1152                                 continue;
1153
1154                         pred_node = get_ilpsched_irn(env, pred);
1155                         pna       = get_ilpsched_node_attr(pred_node);
1156
1157                         assert(pna->asap > 0 && pna->alap >= pna->asap && "Invalid scheduling interval.");
1158
1159                         if (! bitset_is_set(bs_block_irns, pna->block_idx))
1160                                 bitset_set(bs_block_irns, pna->block_idx);
1161                         else
1162                                 continue;
1163
1164                         /* irn = n, pred = m */
1165                         delay  = fixed_latency(env->sel, pred, env->block_env);
1166                         t_low  = MAX(na->asap, pna->asap + delay - 1);
1167                         t_high = MIN(na->alap, pna->alap + delay - 1);
1168                         for (t = t_low - 1; t <= t_high - 1; ++t) {
1169                                 unsigned tn, tm;
1170                                 int      *tmp_var_idx = NEW_ARR_F(int, 0);
1171
1172                                 snprintf(buf, sizeof(buf), "precedence_n%u_n%u_%u", get_irn_idx(pred), get_irn_idx(irn), t);
1173                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, 1.0);
1174                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1175                                 num_cst_prec++;
1176
1177                                 /* lpp_set_factor_fast_bulk needs variables sorted ascending by index */
1178                                 if (na->ilp_vars.x[0] < pna->ilp_vars.x[0]) {
1179                                         /* node variables have smaller index than pred variables */
1180                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1181                                                 for (tn = na->asap - 1; tn <= t; ++tn) {
1182                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1183                                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1184                                                 }
1185                                         }
1186
1187                                         for (tp_idx = pna->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1188                                                 for (tm = t - delay + 1; tm < pna->alap; ++tm) {
1189                                                         unsigned idx = ILPVAR_IDX(pna, tp_idx, tm);
1190                                                         ARR_APP1(int, tmp_var_idx, pna->ilp_vars.x[idx]);
1191                                                 }
1192                                         }
1193                                 }
1194                                 else {
1195                                         /* pred variables have smaller index than node variables */
1196                                         for (tp_idx = pna->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1197                                                 for (tm = t - delay + 1; tm < pna->alap; ++tm) {
1198                                                         unsigned idx = ILPVAR_IDX(pna, tp_idx, tm);
1199                                                         ARR_APP1(int, tmp_var_idx, pna->ilp_vars.x[idx]);
1200                                                 }
1201                                         }
1202
1203                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1204                                                 for (tn = na->asap - 1; tn <= t; ++tn) {
1205                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1206                                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1207                                                 }
1208                                         }
1209                                 }
1210
1211                                 if (ARR_LEN(tmp_var_idx) > 0)
1212                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1213
1214                                 DEL_ARR_F(tmp_var_idx);
1215                         }
1216                 }
1217                 ilp_timer_pop();
1218         }
1219         DBG((env->dbg, LEVEL_1, "\t%u assignement constraints (%g sec)\n",
1220                 num_cst_assign, ilp_timer_elapsed_usec(t_cst_assign) / 1000000.0));
1221         DBG((env->dbg, LEVEL_1, "\t%u precedence constraints (%g sec)\n",
1222                 num_cst_prec, ilp_timer_elapsed_usec(t_cst_prec) / 1000000.0));
1223 }
1224
1225 /**
1226  * Create ILP resource constraints:
1227  * - assure that for each time step not more instructions are scheduled
1228  *   to the same unit types as units of this type are available
1229  */
1230 static void create_ressource_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1231         int                   glob_type_idx;
1232         char                  buf[1024];
1233         unsigned              num_cst_resrc = 0;
1234         ilpsched_block_attr_t *ba           = get_ilpsched_block_attr(block_node);
1235         lc_timer_t            *t_cst_rsrc   = lc_timer_register("beilpsched_cst_rsrc",   "create resource constraints");
1236
1237         ilp_timer_push(t_cst_rsrc);
1238         for (glob_type_idx = env->cpu->n_unit_types - 1; glob_type_idx >= 0; --glob_type_idx) {
1239                 unsigned                 t;
1240                 be_execution_unit_type_t *cur_tp = &env->cpu->unit_types[glob_type_idx];
1241
1242                 /* BEWARE: the DUMMY unit type is not in CPU, so it's skipped automatically */
1243
1244                 /* check each time step */
1245                 for (t = 0; t < ba->max_steps; ++t) {
1246                         ir_node *irn;
1247                         int     cst;
1248                         int     *tmp_var_idx = NEW_ARR_F(int, 0);
1249
1250                         snprintf(buf, sizeof(buf), "resource_cst_%s_%u", cur_tp->name, t);
1251                         cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)cur_tp->n_units);
1252                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1253                         num_cst_resrc++;
1254
1255                         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1256                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1257                                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1258                                 int                  tp_idx;
1259
1260                                 tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1261
1262                                 if (tp_idx >= 0 && t >= na->asap - 1 && t <= na->alap - 1) {
1263                                         int cur_var = ILPVAR_IDX(na, tp_idx, t);
1264                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[cur_var]);
1265                                 }
1266                         }
1267
1268                         /* set constraints if we have some */
1269                         if (ARR_LEN(tmp_var_idx) > 0)
1270                                 lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1271
1272                         DEL_ARR_F(tmp_var_idx);
1273                 }
1274         }
1275         ilp_timer_pop();
1276         DBG((env->dbg, LEVEL_1, "\t%u resource constraints (%g sec)\n",
1277                 num_cst_resrc, ilp_timer_elapsed_usec(t_cst_rsrc) / 1000000.0));
1278 }
1279
1280 /**
1281  * Create ILP bundle constraints:
1282  * - assure, at most bundle_size * bundles_per_cycle instructions
1283  *   can be started at a certain point.
1284  */
1285 static void create_bundle_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1286         char                  buf[1024];
1287         unsigned              t;
1288         unsigned              num_cst_bundle = 0;
1289         unsigned              n_instr_max    = env->cpu->bundle_size * env->cpu->bundels_per_cycle;
1290         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1291         lc_timer_t            *t_cst_bundle  = lc_timer_register("beilpsched_cst_bundle", "create bundle constraints");
1292
1293         ilp_timer_push(t_cst_bundle);
1294         for (t = 0; t < ba->max_steps; ++t) {
1295                 ir_node *irn;
1296                 int     cst;
1297                 int     *tmp_var_idx = NEW_ARR_F(int, 0);
1298
1299                 snprintf(buf, sizeof(buf), "bundle_cst_%u", t);
1300                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)n_instr_max);
1301                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1302                 num_cst_bundle++;
1303
1304                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
1305                         be_ilpsched_irn_t    *node;
1306                         ilpsched_node_attr_t *na;
1307                         int                  tp_idx;
1308
1309                         /* Projs and Keeps do not contribute to bundle size */
1310                         if (is_Proj(irn) || be_is_Keep(irn))
1311                                 continue;
1312
1313                         node = get_ilpsched_irn(env, irn);
1314                         na   = get_ilpsched_node_attr(node);
1315
1316                         /* nodes assigned to DUMMY unit do not contribute to bundle size */
1317                         if (na->is_dummy_node)
1318                                 continue;
1319
1320                         if (t >= na->asap - 1 && t <= na->alap - 1) {
1321                                 for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1322                                         int idx = ILPVAR_IDX(na, tp_idx, t);
1323                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.x[idx]);
1324                                 }
1325                         }
1326                 }
1327
1328                 if (ARR_LEN(tmp_var_idx) > 0)
1329                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1330
1331                 DEL_ARR_F(tmp_var_idx);
1332         }
1333         ilp_timer_pop();
1334         DBG((env->dbg, LEVEL_1, "\t%u bundle constraints (%g sec)\n",
1335                 num_cst_bundle, ilp_timer_elapsed_usec(t_cst_bundle) / 1000000.0));
1336 }
1337
1338 /**
1339  * Create ILP alive nodes constraints:
1340  * - set variable a_{nt}^k to 1 if nodes n is alive at step t on unit k
1341  */
1342 static void create_alive_nodes_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1343         char                  buf[1024];
1344         ir_node               *irn;
1345         unsigned              num_cst = 0;
1346         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1347         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_alive_nodes", "create alive nodes constraints");
1348
1349         ilp_timer_push(t_cst);
1350         /* for each node */
1351         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1352                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1353                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1354                 unsigned             t;
1355
1356                 /* we ignore nodes assigned to dummy unit here */
1357                 if (na->is_dummy_node)
1358                         continue;
1359
1360                 /* check check all time steps: asap(n) <= t <= U */
1361                 for (t = na->asap - 1; t < ba->max_steps; ++t) {
1362                         int node_tp_idx;
1363
1364                         /* for all unit types available for this node */
1365                         for (node_tp_idx = na->n_unit_types - 1; node_tp_idx >= 0; --node_tp_idx) {
1366                                 unsigned tn, tn_max, idx;
1367                                 int      cst, i;
1368                                 int      *tmp_var_idx_n = NEW_ARR_F(int, 0);
1369                                 int      *tmp_var_idx_m = NEW_ARR_F(int, 0);
1370
1371                                 snprintf(buf, sizeof(buf), "alive_node_cst_%u_n%u_%s",
1372                                         t, get_irn_idx(irn), na->type_info[node_tp_idx].tp->name);
1373                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, 0.0);
1374                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1375                                 num_cst++;
1376
1377                                 tn_max = MIN(na->alap - 1, t);
1378                                 /* check if the node has been scheduled so far */
1379                                 for (tn = na->asap - 1; tn <= tn_max; ++tn) {
1380                                         int idx = ILPVAR_IDX(na, node_tp_idx, tn);
1381                                         ARR_APP1(int, tmp_var_idx_n, na->ilp_vars.x[idx]);
1382                                 }
1383
1384                                 if (ARR_LEN(tmp_var_idx_n) > 0)
1385                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_n, ARR_LEN(tmp_var_idx_n), (double)(na->n_consumer));
1386                                 DEL_ARR_F(tmp_var_idx_n);
1387
1388                                 /* subtract the number of consumer scheduled so far */
1389                                 for (i = ARR_LEN(na->block_consumer) - 1; i >= 0; --i) {
1390                                         be_ilpsched_irn_t    *cons = get_ilpsched_irn(env, na->block_consumer[i]);
1391                                         ilpsched_node_attr_t *ca   = get_ilpsched_node_attr(cons);
1392                                         int                  tp_idx;
1393                                         unsigned             tm, tm_max;
1394
1395                                         tm_max = MIN(ca->alap - 1, t);
1396                                         for (tp_idx = ca->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1397                                                 for (tm = ca->asap - 1; tm <= tm_max; ++tm) {
1398                                                         int idx = ILPVAR_IDX(ca, tp_idx, tm);
1399                                                         ARR_APP1(int, tmp_var_idx_m, ca->ilp_vars.x[idx]);
1400                                                 }
1401                                         }
1402                                 }
1403
1404                                 if (ARR_LEN(tmp_var_idx_m) > 0)
1405                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_m, ARR_LEN(tmp_var_idx_m), -1.0);
1406                                 DEL_ARR_F(tmp_var_idx_m);
1407
1408                                 /* -c * a_{nt}^k */
1409                                 idx = ILPVAR_IDX_DEAD(ba, na, node_tp_idx, t);
1410                                 lpp_set_factor_fast(lpp, cst, na->ilp_vars.a[idx], 0.0 - (double)(na->n_consumer));
1411
1412                         }
1413                 }
1414         }
1415         ilp_timer_pop();
1416         DBG((env->dbg, LEVEL_1, "\t%u alive nodes constraints (%g sec)\n",
1417                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1418 }
1419
1420 /**
1421  * Create ILP alive nodes constraints for live-in nodes:
1422  * - set variable a_{nt}^k to 1 if nodes n is alive at step t on unit k
1423  */
1424 static void create_alive_livein_nodes_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1425         char                  buf[1024];
1426         ilp_livein_node_t     *livein;
1427         unsigned              num_cst = 0;
1428         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1429         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_alive_livein_nodes", "create alive livein nodes constraints");
1430
1431         ilp_timer_push(t_cst);
1432         /* for each node */
1433         foreach_pset(ba->livein_nodes, livein) {
1434                 ir_node              *irn  = livein->irn;
1435                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1436                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1437                 unsigned             t;
1438
1439                 /* check check all time steps: 0 <= t < max_alive_steps */
1440                 for (t = 0; t < livein->max_alive_steps; ++t) {
1441                         int node_tp_idx;
1442
1443                         /* for all unit types available for this node */
1444                         for (node_tp_idx = na->n_unit_types - 1; node_tp_idx >= 0; --node_tp_idx) {
1445                                 const ir_edge_t *edge;
1446                                 unsigned idx;
1447                                 int      cst, num_block_user;
1448                                 int      *tmp_var_idx_m = NEW_ARR_F(int, 0);
1449
1450                                 /* check the number of consumer scheduled so far */
1451                                 num_block_user = 0;
1452                                 foreach_out_edge(irn, edge) {
1453                                         ir_node              *user = get_edge_src_irn(edge);
1454                                         be_ilpsched_irn_t    *cons;
1455                                         ilpsched_node_attr_t *ca;
1456                                         int                  tp_idx;
1457                                         unsigned             tm, tm_max;
1458
1459                                         /* check only users within current block */
1460                                         if (get_nodes_block(user) != block_node->irn)
1461                                                 continue;
1462
1463                                         num_block_user++;
1464                                         cons = get_ilpsched_irn(env, user);
1465                                         ca   = get_ilpsched_node_attr(cons);
1466
1467                                         tm_max = MIN(ca->alap - 1, t);
1468                                         for (tp_idx = ca->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1469                                                 for (tm = ca->asap - 1; tm <= tm_max; ++tm) {
1470                                                         int idx = ILPVAR_IDX(ca, tp_idx, tm);
1471                                                         ARR_APP1(int, tmp_var_idx_m, ca->ilp_vars.x[idx]);
1472                                                 }
1473                                         }
1474                                 }
1475
1476                                 snprintf(buf, sizeof(buf), "alive_livein_node_cst_%u_n%u_%s",
1477                                         t, get_irn_idx(irn), na->type_info[node_tp_idx].tp->name);
1478                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_greater, (double)num_block_user);
1479                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1480                                 num_cst++;
1481
1482                                 /* sum(scheduled users) */
1483                                 if (ARR_LEN(tmp_var_idx_m) > 0)
1484                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_m, ARR_LEN(tmp_var_idx_m), 1.0);
1485                                 DEL_ARR_F(tmp_var_idx_m);
1486
1487                                 /* + c * a_{nt}^k */
1488                                 idx = node_tp_idx * livein->max_alive_steps + t;
1489                                 lpp_set_factor_fast(lpp, cst, livein->a[idx], (double)(num_block_user));
1490                         }
1491                 }
1492         }
1493         ilp_timer_pop();
1494         DBG((env->dbg, LEVEL_1, "\t%u alive livein nodes constraints (%g sec)\n",
1495                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1496 }
1497
1498 /**
1499  * Create ILP pressure constraints, based on alive nodes:
1500  * - add additional costs to objective function if a node is scheduled
1501  *   on a unit although all units of this type are currently occupied
1502  */
1503 static void create_pressure_alive_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1504         char                  buf[1024];
1505         ir_node               *cur_irn;
1506         unsigned              num_cst = 0;
1507         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1508         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_pressure", "create pressure constraints");
1509
1510         ilp_timer_push(t_cst);
1511         /* y_{nt}^k is set for each node and timestep and unit type */
1512         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1513                 unsigned             cur_idx   = get_irn_idx(cur_irn);
1514                 be_ilpsched_irn_t    *cur_node = get_ilpsched_irn(env, cur_irn);
1515                 ilpsched_node_attr_t *cur_na   = get_ilpsched_node_attr(cur_node);
1516                 int                  glob_type_idx;
1517
1518                 /* we ignore nodes assigned to DUMMY unit here */
1519                 if (cur_na->is_dummy_node)
1520                         continue;
1521
1522                 /* for all types */
1523                 for (glob_type_idx = env->cpu->n_unit_types - 1; glob_type_idx >= 0; --glob_type_idx) {
1524                         be_execution_unit_type_t *cur_tp   = &env->cpu->unit_types[glob_type_idx];
1525                         int                      cur_tp_idx;
1526                         unsigned                 t;
1527
1528                         /* BEWARE: the DUMMY unit types is not in CPU, so it's skipped automatically */
1529
1530                         /* check if node can be executed on this unit type */
1531                         cur_tp_idx = is_valid_unit_type_for_node(cur_tp, cur_node);
1532                         if (cur_tp_idx < 0)
1533                                 continue;
1534
1535                         /* check all time_steps at which the current node can be scheduled */
1536                         for (t = cur_na->asap - 1; t <= cur_na->alap - 1; ++t) {
1537                                 int     cst, y_idx;
1538                                 ir_node *irn;
1539                                 int     *tmp_var_idx = NEW_ARR_F(int, 0);
1540                                 ilp_livein_node_t *livein;
1541
1542                                 snprintf(buf, sizeof(buf), "pressure_cst_n%u_%u_%s", cur_idx, t, cur_tp->name);
1543                                 cst = lpp_add_cst_uniq(lpp, buf, lpp_less, (double)(cur_tp->n_units - 1));
1544                                 DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1545                                 num_cst++;
1546
1547                                 /* - accumulate all nodes alive at point t on unit type k */
1548                                 foreach_linked_irns(ba->head_ilp_nodes, irn) {
1549                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1550                                         ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1551                                         int                  a_idx, tp_idx;
1552
1553                                         /* check if node can be alive here */
1554                                         if (t < na->asap - 1)
1555                                                 continue;
1556
1557                                         tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1558
1559                                         /* current type is not suitable */
1560                                         if (tp_idx < 0)
1561                                                 continue;
1562
1563                                         a_idx = ILPVAR_IDX_DEAD(ba, na, tp_idx, t);
1564                                         ARR_APP1(int, tmp_var_idx, na->ilp_vars.a[a_idx]);
1565                                 }
1566                                 /* do the same for livein nodes */
1567                                 foreach_pset(ba->livein_nodes, livein) {
1568                                         ir_node              *irn  = livein->irn;
1569                                         be_ilpsched_irn_t    *node = get_ilpsched_irn(env, irn);
1570                                         int                  a_idx, tp_idx;
1571
1572                                         /* check if node can be alive here */
1573                                         if (t >= livein->max_alive_steps)
1574                                                 continue;
1575
1576                                         tp_idx = is_valid_unit_type_for_node(cur_tp, node);
1577
1578                                         /* current type is not suitable */
1579                                         if (tp_idx < 0)
1580                                                 continue;
1581
1582                                         a_idx = tp_idx * livein->max_alive_steps + t;
1583                                         ARR_APP1(int, tmp_var_idx, livein->a[a_idx]);
1584                                 }
1585
1586                                 if (ARR_LEN(tmp_var_idx) > 0)
1587                                         lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx, ARR_LEN(tmp_var_idx), 1.0);
1588                                 DEL_ARR_F(tmp_var_idx);
1589
1590                                 /* - num_nodes * y_{nt}^k */
1591                                 y_idx = ILPVAR_IDX(cur_na, cur_tp_idx, t);
1592                                 lpp_set_factor_fast(lpp, cst, cur_na->ilp_vars.y[y_idx], -1.0);
1593                         }
1594                 }
1595         }
1596         ilp_timer_pop();
1597         DBG((env->dbg, LEVEL_1, "\t%u pressure constraints (%g sec)\n",
1598                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1599 }
1600
1601 /**
1602  * Create ILP branch constraints:
1603  * Assure, alle nodes are scheduled prior to cfg op.
1604  */
1605 static void create_branch_constraint(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1606         char                  buf[1024];
1607         ir_node               *cur_irn, *cfop;
1608         unsigned              num_cst          = 0;
1609         unsigned              num_non_branches = 0;
1610         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1611         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_branch", "create branch constraints");
1612
1613         ilp_timer_push(t_cst);
1614         cfop = NULL;
1615         /* determine number of non-branch nodes and the one and only branch node */
1616         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1617                 switch (get_irn_opcode(cur_irn)) {
1618                         case iro_Phi:
1619                         case iro_Start:
1620                         case iro_End:
1621                         case iro_Proj:
1622                         case iro_Bad:
1623                         case iro_Unknown:
1624                                 num_non_branches++;
1625                                 break;
1626                         default:
1627                                 if (is_cfop(cur_irn)) {
1628                                         assert(cfop == NULL && "Highlander - there can be only one to be constrained");
1629                                         cfop = cur_irn;
1630                                 }
1631                                 else {
1632                                         num_non_branches++;
1633                                 }
1634                                 break;
1635                 }
1636         }
1637
1638         if (cfop) {
1639                 be_ilpsched_irn_t    *cf_node = get_ilpsched_irn(env, cfop);
1640                 ilpsched_node_attr_t *cf_na   = get_ilpsched_node_attr(cf_node);
1641                 unsigned t;
1642
1643                 /* for each time step */
1644                 for (t = cf_na->asap - 1; t <= cf_na->alap - 1; ++t) {
1645                         int *non_branch_vars, *branch_vars;
1646                         int cst;
1647
1648                         snprintf(buf, sizeof(buf), "branch_cst_%u_n%u", t, get_irn_idx(cfop));
1649                         cst = lpp_add_cst_uniq(lpp, buf, lpp_greater, 0.0);
1650                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1651                         num_cst++;
1652
1653                         /* sum(overall non branches: n)x_{nt}^k - sum(overall branches: b)(num_non_branches * x_{bt}^k >= 0) */
1654                         non_branch_vars = NEW_ARR_F(int, 0);
1655                         branch_vars     = NEW_ARR_F(int, 0);
1656                         foreach_linked_irns(ba->head_ilp_nodes, cur_irn) {
1657                                 be_ilpsched_irn_t    *node = get_ilpsched_irn(env, cur_irn);
1658                                 ilpsched_node_attr_t *na   = get_ilpsched_node_attr(node);
1659                                 int                  tp_idx;
1660
1661                                 if (cur_irn == cfop) {
1662                                         /* for all unit types available for this node */
1663                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1664                                                 unsigned idx = ILPVAR_IDX(na, tp_idx, t);
1665                                                 ARR_APP1(int, branch_vars, na->ilp_vars.x[idx]);
1666                                         }
1667                                 }
1668                                 else {
1669                                         /* sum up all possible schedule points for this node upto current timestep */
1670                                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1671                                                 unsigned tn;
1672                                                 unsigned tmax = MIN(t, na->alap - 1);
1673
1674                                                 for (tn = na->asap - 1; tn <= tmax; ++tn) {
1675                                                         unsigned idx = ILPVAR_IDX(na, tp_idx, tn);
1676                                                         ARR_APP1(int, non_branch_vars, na->ilp_vars.x[idx]);
1677                                                 }
1678                                         }
1679                                 }
1680
1681                         }
1682
1683                         if (ARR_LEN(non_branch_vars) > 0)
1684                                 lpp_set_factor_fast_bulk(lpp, cst, non_branch_vars, ARR_LEN(non_branch_vars), 1.0);
1685                         if (ARR_LEN(branch_vars) > 0)
1686                                 lpp_set_factor_fast_bulk(lpp, cst, branch_vars, ARR_LEN(branch_vars), 0.0 - (double)num_non_branches);
1687
1688                         DEL_ARR_F(branch_vars);
1689                         DEL_ARR_F(non_branch_vars);
1690                 }
1691         }
1692         ilp_timer_pop();
1693         DBG((env->dbg, LEVEL_1, "\t%u branch constraints (%g sec)\n",
1694                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1695 }
1696
1697 #if 0
1698 static void create_proj_keep_constraints(be_ilpsched_env_t *env, lpp_t *lpp, be_ilpsched_irn_t *block_node) {
1699         char                  buf[1024];
1700         ir_node               *irn;
1701         unsigned              num_cst = 0;
1702         ilpsched_block_attr_t *ba     = get_ilpsched_block_attr(block_node);
1703         lc_timer_t            *t_cst  = lc_timer_register("beilpsched_cst_projkeep", "create proj and keep constraints");
1704
1705         ilp_timer_push(t_cst);
1706         /* check all nodes */
1707         foreach_linked_irns(ba->head_ilp_nodes, irn) {
1708                 be_ilpsched_irn_t    *node;
1709                 ilpsched_node_attr_t *na;
1710                 unsigned             t;
1711                 ir_node              **pk;
1712
1713                 /* only mode_T nodes can have Projs and Keeps assigned */
1714                 if (get_irn_mode(irn) != mode_T)
1715                         continue;
1716
1717                 node = get_ilpsched_irn(env, irn);
1718                 na   = get_ilpsched_node_attr(node);
1719
1720                 /* check if has some Projs and Keeps assigned */
1721                 if (! na->projkeeps)
1722                         continue;
1723
1724                 /* we can run only once over the queue, so preserve the nodes */
1725                 pk = NEW_ARR_F(ir_node *, 0);
1726                 while (! waitq_empty(na->projkeeps))
1727                         ARR_APP1(ir_node *, pk, waitq_get(na->projkeeps));
1728                 del_waitq(na->projkeeps);
1729                 na->projkeeps = NULL;
1730
1731                 /* for all time steps at which this node can be scheduled */
1732                 for (t = na->asap - 1; t <= na->alap - 1; ++t) {
1733                         int cst, tp_idx, i;
1734                         int *tmp_var_idx_n = NEW_ARR_F(int, 0);
1735
1736                         /* add the constraint, assure, that a node is always scheduled along with it's Projs and Keeps */
1737                         snprintf(buf, sizeof(buf), "projkeep_cst_n%u_%u", get_irn_idx(irn), t);
1738                         cst = lpp_add_cst_uniq(lpp, buf, lpp_equal, 0.0);
1739                         DBG((env->dbg, LEVEL_2, "added constraint %s\n", buf));
1740                         num_cst++;
1741
1742                         /* sum up scheduling variables for this time step */
1743                         for (tp_idx = na->n_unit_types - 1; tp_idx >= 0; --tp_idx) {
1744                                 int idx = ILPVAR_IDX(na, tp_idx, t);
1745                                 ARR_APP1(int, tmp_var_idx_n, na->ilp_vars.x[idx]);
1746                         }
1747
1748                         if (ARR_LEN(tmp_var_idx_n) > 0)
1749                                 lpp_set_factor_fast_bulk(lpp, cst, tmp_var_idx_n, ARR_LEN(tmp_var_idx_n), (double)(ARR_LEN(pk)));
1750                         DEL_ARR_F(tmp_var_idx_n);
1751
1752                         /* subtract all Proj and Keep variables for this step */
1753                         for (i = ARR_LEN(pk) - 1; i >= 0; --i) {
1754                                 be_ilpsched_irn_t    *pk_node = get_ilpsched_irn(env, pk[i]);
1755                                 ilpsched_node_attr_t *pk_na   = get_ilpsched_node_attr(pk_node);
1756                                 int                  pk_tp_idx;
1757
1758                                 for (pk_tp_idx = pk_na->n_unit_types - 1; pk_tp_idx >= 0; --pk_tp_idx) {
1759                                         int idx = ILPVAR_IDX(pk_na, pk_tp_idx, t);
1760                                         lpp_set_factor_fast(lpp, cst, pk_na->ilp_vars.x[idx], -1.0);
1761                                 }
1762                         }
1763                 }
1764         }
1765         ilp_timer_pop();
1766         DBG((env->dbg, LEVEL_1, "\t%u Proj and Keep constraints (%g sec)\n",
1767                 num_cst, ilp_timer_elapsed_usec(t_cst) / 1000000.0));
1768 }
1769 #endif /* if 0 */
1770
1771 /***************************************************
1772  *  _____ _      _____                    _
1773  * |_   _| |    |  __ \                  (_)
1774  *   | | | |    | |__) |  _ __ ___   __ _ _ _ __
1775  *   | | | |    |  ___/  | '_ ` _ \ / _` | | '_ \
1776  *  _| |_| |____| |      | | | | | | (_| | | | | |
1777  * |_____|______|_|      |_| |_| |_|\__,_|_|_| |_|
1778  *
1779  ***************************************************/
1780
1781 /**
1782  * Create the ilp (add variables, build constraints, solve, build schedule from solution).
1783  */
1784 static void create_ilp(ir_node *block, void *walk_env) {
1785         be_ilpsched_env_t     *env           = walk_env;
1786         be_ilpsched_irn_t     *block_node    = get_ilpsched_irn(env, block);
1787         ilpsched_block_attr_t *ba            = get_ilpsched_block_attr(block_node);
1788         FILE                  *logfile       = NULL;
1789         lpp_t                 *lpp           = NULL;
1790         int                   need_heur      = 0;
1791         struct obstack        var_obst;
1792         char                  name[1024];
1793
1794         DBG((env->dbg, 255, "\n\n\n=========================================\n"));
1795         DBG((env->dbg, 255, "  ILP Scheduling for %+F\n", block));
1796         DBG((env->dbg, 255, "=========================================\n\n"));
1797
1798         DBG((env->dbg, LEVEL_1, "Creating ILP Variables for nodes in %+F (%u interesting nodes, %u max steps)\n",
1799                 block, ba->n_interesting_nodes, ba->max_steps));
1800
1801         /* notify backend and get block environment */
1802         env->block_env = be_ilp_sched_init_block_ilp_schedule(env->sel, block);
1803
1804         /* if we have less than two interesting nodes, there is no need to create the ILP */
1805         if (ba->n_interesting_nodes > 1) {
1806                 double fact_var        = ba->n_interesting_nodes > 25 ? 2.3 : 3;
1807                 double fact_cst        = ba->n_interesting_nodes > 25 ? 3   : 4.5;
1808                 int    base_num        = ba->n_interesting_nodes * ba->n_interesting_nodes;
1809                 int    estimated_n_var = (int)((double)base_num * fact_var);
1810                 int    estimated_n_cst = (int)((double)base_num * fact_cst);
1811
1812                 DBG((env->dbg, LEVEL_1, "Creating LPP with estimated numbers: %d vars, %d cst\n",
1813                         estimated_n_var, estimated_n_cst));
1814
1815                 /* set up the LPP object */
1816                 snprintf(name, sizeof(name), "ilp scheduling IRG %s", get_entity_ld_name(get_irg_entity(env->irg)));
1817
1818                 lpp = new_lpp_userdef(
1819                         (const char *)name,
1820                         lpp_minimize,
1821                         estimated_n_cst,     /* num vars */
1822                         estimated_n_cst + 1, /* num cst */
1823                         1.3);                /* grow factor */
1824                 obstack_init(&var_obst);
1825
1826                 /* create ILP variables */
1827                 create_variables(env, lpp, block_node, &var_obst);
1828
1829                 /* create ILP constraints */
1830                 DBG((env->dbg, LEVEL_1, "Creating constraints for nodes in %+F:\n", block));
1831                 create_assignment_and_precedence_constraints(env, lpp, block_node);
1832                 create_ressource_constraints(env, lpp, block_node);
1833                 create_bundle_constraints(env, lpp, block_node);
1834                 create_branch_constraint(env, lpp, block_node);
1835                 //create_proj_keep_constraints(env, lpp, block_node);
1836
1837                 if (env->opts->regpress) {
1838                         create_alive_nodes_constraint(env, lpp, block_node);
1839                         create_alive_livein_nodes_constraint(env, lpp, block_node);
1840                         create_pressure_alive_constraint(env, lpp, block_node);
1841                 }
1842
1843                 DBG((env->dbg, LEVEL_1, "ILP to solve: %u variables, %u constraints\n", lpp->var_next, lpp->cst_next));
1844
1845                 /* debug stuff, dump lpp when debugging is on  */
1846                 DEBUG_ONLY(
1847                         if (firm_dbg_get_mask(env->dbg) > 1) {
1848                                 char buf[1024];
1849                                 FILE *f;
1850
1851                                 snprintf(buf, sizeof(buf), "lpp_block_%lu.txt", get_irn_node_nr(block));
1852                                 f = fopen(buf, "w");
1853                                 lpp_dump_plain(lpp, f);
1854                                 fclose(f);
1855                                 snprintf(buf, sizeof(buf), "lpp_block_%lu.mps", get_irn_node_nr(block));
1856                                 lpp_dump(lpp, buf);
1857                         }
1858                 );
1859
1860                 /* set solve time limit */
1861                 lpp_set_time_limit(lpp, env->opts->time_limit);
1862
1863                 /* set logfile if requested */
1864                 if (strlen(env->opts->log_file) > 0) {
1865                         if (strcasecmp(env->opts->log_file, "stdout") == 0)
1866                                 lpp_set_log(lpp, stdout);
1867                         else if (strcasecmp(env->opts->log_file, "stderr") == 0)
1868                                 lpp_set_log(lpp, stderr);
1869                         else {
1870                                 logfile = fopen(env->opts->log_file, "w");
1871                                 if (! logfile)
1872                                         fprintf(stderr, "Could not open logfile '%s'! Logging disabled.\n", env->opts->log_file);
1873                                 else
1874                                         lpp_set_log(lpp, logfile);
1875                         }
1876                 }
1877
1878                 /* solve the ILP */
1879                 lpp_solve_net(lpp, env->main_env->options->ilp_server, env->main_env->options->ilp_solver);
1880
1881                 if (logfile)
1882                         fclose(logfile);
1883
1884                 /* check for valid solution */
1885                 if (! lpp_is_sol_valid(lpp)) {
1886                         char buf[1024];
1887                         FILE *f;
1888
1889                         DEBUG_ONLY(
1890                                 if (firm_dbg_get_mask(env->dbg) >= 2) {
1891                                         snprintf(buf, sizeof(buf), "lpp_block_%lu.infeasible.txt", get_irn_node_nr(block));
1892                                         f = fopen(buf, "w");
1893                                         lpp_dump_plain(lpp, f);
1894                                         fclose(f);
1895                                         snprintf(buf, sizeof(buf), "lpp_block_%lu.infeasible.mps", get_irn_node_nr(block));
1896                                         lpp_dump(lpp, buf);
1897                                         dump_ir_block_graph(env->irg, "-infeasible");
1898                                 }
1899                         )
1900
1901                         ir_fprintf(stderr, "ILP found no solution within time (%+F, %+F), falling back to heuristics.\n", block, env->irg);
1902                         need_heur = 1;
1903                 }
1904
1905                 DBG((env->dbg, LEVEL_1, "\nSolution:\n"));
1906                 DBG((env->dbg, LEVEL_1, "\tsend time: %g sec\n", lpp->send_time / 1000000.0));
1907                 DBG((env->dbg, LEVEL_1, "\treceive time: %g sec\n", lpp->recv_time / 1000000.0));
1908                 DBG((env->dbg, LEVEL_1, "\tmatrix: %u elements, density %.2f%%, size %.2fMB\n", lpp->n_elems, lpp->density, (double)lpp->matrix_mem / 1024.0 / 1024.0));
1909                 DBG((env->dbg, LEVEL_1, "\titerations: %d\n", lpp->iterations));
1910                 DBG((env->dbg, LEVEL_1, "\tsolution time: %g\n", lpp->sol_time));
1911                 DBG((env->dbg, LEVEL_1, "\tobjective function: %g\n", LPP_VALUE_IS_0(lpp->objval) ? 0.0 : lpp->objval));
1912                 DBG((env->dbg, LEVEL_1, "\tbest bound: %g\n", LPP_VALUE_IS_0(lpp->best_bound) ? 0.0 : lpp->best_bound));
1913
1914                 DBG((env->dbg, LEVEL_1, "variables used %u bytes\n", obstack_memory_used(&var_obst)));
1915         }
1916
1917         /* apply solution */
1918         if (need_heur)
1919                 list_sched_single_block(env->birg, block, env->be_opts);
1920         else
1921                 apply_solution(env, lpp, block);
1922
1923         if (lpp)
1924                 free_lpp(lpp);
1925
1926         /* notify backend */
1927         be_ilp_sched_finish_block_ilp_schedule(env->sel, block, env->block_env);
1928 }
1929
1930 /**
1931  * Perform ILP scheduling on the given irg.
1932  */
1933 void be_ilp_sched(const be_irg_t *birg, be_options_t *be_opts) {
1934         be_ilpsched_env_t          env;
1935         const char                 *name = "be ilp scheduling";
1936         arch_isa_t                 *isa  = birg->main_env->arch_env->isa;
1937         const ilp_sched_selector_t *sel  = isa->impl->get_ilp_sched_selector(isa);
1938
1939         FIRM_DBG_REGISTER(env.dbg, "firm.be.sched.ilp");
1940
1941 //      firm_dbg_set_mask(env.dbg, 1);
1942
1943         env.irg_env    = be_ilp_sched_init_irg_ilp_schedule(sel, birg->irg);
1944         env.sel        = sel;
1945         env.irg        = birg->irg;
1946         env.height     = heights_new(birg->irg);
1947         env.main_env   = birg->main_env;
1948         env.arch_env   = birg->main_env->arch_env;
1949         env.cpu        = arch_isa_get_machine(birg->main_env->arch_env->isa);
1950         env.opts       = &ilp_opts;
1951         env.birg       = birg;
1952         env.be_opts    = be_opts;
1953         phase_init(&env.ph, name, env.irg, PHASE_DEFAULT_GROWTH, init_ilpsched_irn);
1954
1955         /* assign a unique per block number to all interesting nodes */
1956         irg_walk_in_or_dep_graph(env.irg, NULL, build_block_idx, &env);
1957
1958         /*
1959                 The block indices are completely build after the walk,
1960                 now we can allocate the bitsets (size depends on block indices)
1961                 for all nodes.
1962         */
1963         phase_reinit_irn_data(&env.ph);
1964
1965         /* Collect all root nodes (having no user in their block) and calculate ASAP. */
1966         irg_walk_in_or_dep_blkwise_graph(env.irg, collect_alap_root_nodes, calculate_irn_asap, &env);
1967
1968         /* Calculate ALAP of all irns */
1969         irg_block_walk_graph(env.irg, NULL, calculate_block_alap, &env);
1970
1971         /* We refine the {ASAP(n), ALAP(n)} interval and fix the time steps for Projs and Keeps */
1972         irg_walk_in_or_dep_blkwise_graph(env.irg, NULL, refine_asap_alap_times, &env);
1973
1974         /* perform ILP scheduling */
1975         irg_block_walk_graph(env.irg, NULL, create_ilp, &env);
1976
1977         DEBUG_ONLY(
1978                 if (firm_dbg_get_mask(env.dbg)) {
1979                         phase_stat_t stat;
1980                         phase_stat_t *stat_ptr = phase_stat(&env.ph, &stat);
1981
1982                         fprintf(stderr, "Phase used: %u bytes\n", stat_ptr->overall_bytes);
1983                 }
1984         );
1985
1986         /* free data allocated dynamically */
1987         irg_block_walk_graph(env.irg, NULL, clear_unwanted_data, &env);
1988
1989         /* free all allocated object */
1990         phase_free(&env.ph);
1991         heights_free(env.height);
1992
1993         /* notify backend */
1994         be_ilp_sched_finish_irg_ilp_schedule(sel, birg->irg, env.irg_env);
1995 }
1996
1997 /**
1998  * Register ILP scheduler options.
1999  */
2000 void be_init_ilpsched(void)
2001 {
2002         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
2003         lc_opt_entry_t *sched_grp = lc_opt_get_grp(be_grp, "ilpsched");
2004
2005         lc_opt_add_table(sched_grp, ilpsched_option_table);
2006 }
2007
2008 #else /* WITH_ILP */
2009
2010 static INLINE void some_picky_compiler_do_not_allow_empty_files(void)
2011 {}
2012
2013 #endif /* WITH_ILP */