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