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