Mon Feb 1 14:29:43 CET 2010 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / branch-opts.c
1 /*
2  * branch-opts.c: Branch optimizations support 
3  *
4  * Authors:
5  *   Patrik Torstensson (Patrik.Torstesson at gmail.com)
6  *
7  * (C) 2005 Ximian, Inc.  http://www.ximian.com
8  */
9  #include "mini.h"
10
11 #ifndef DISABLE_JIT
12  
13
14 /*
15  * Returns true if @bb is a basic block which falls through the next block.
16  * TODO verify if it helps to check if the bb last ins is a branch to its successor. 
17  */
18 static gboolean
19 mono_bb_is_fall_through (MonoCompile *cfg, MonoBasicBlock *bb)
20 {
21         return  bb->next_bb && bb->next_bb->region == bb->region && /*fall throught between regions is not really interesting or useful*/
22                         (bb->last_ins == NULL || !MONO_IS_BRANCH_OP (bb->last_ins)); /*and the last op can't be a branch too*/
23 }
24
25 /*
26  * Used by the arch code to replace the exception handling
27  * with a direct branch. This is safe to do if the 
28  * exception object isn't used, no rethrow statement and
29  * no filter statement (verify).
30  *
31  */
32 MonoInst *
33 mono_branch_optimize_exception_target (MonoCompile *cfg, MonoBasicBlock *bb, const char * exname)
34 {
35         MonoMethod *method = cfg->method;
36         MonoMethodHeader *header = mono_method_get_header (method);
37         MonoExceptionClause *clause;
38         MonoClass *exclass;
39         int i;
40
41         if (!(cfg->opt & MONO_OPT_EXCEPTION))
42                 return NULL;
43
44         if (bb->region == -1 || !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
45                 return NULL;
46
47         exclass = mono_class_from_name (mono_get_corlib (), "System", exname);
48         /* search for the handler */
49         for (i = 0; i < header->num_clauses; ++i) {
50                 clause = &header->clauses [i];
51                 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset)) {
52                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE && clause->data.catch_class && mono_class_is_assignable_from (clause->data.catch_class, exclass)) {
53                                 MonoBasicBlock *tbb;
54
55                                 /* get the basic block for the handler and 
56                                  * check if the exception object is used.
57                                  * Flag is set during method_to_ir due to 
58                                  * pop-op is optmized away in codegen (burg).
59                                  */
60                                 tbb = cfg->cil_offset_to_bb [clause->handler_offset];
61                                 if (tbb && tbb->flags & BB_EXCEPTION_DEAD_OBJ && !(tbb->flags & BB_EXCEPTION_UNSAFE)) {
62                                         MonoBasicBlock *targetbb = tbb;
63                                         gboolean unsafe = FALSE;
64
65                                         /* Check if this catch clause is ok to optimize by
66                                          * looking for the BB_EXCEPTION_UNSAFE in every BB that
67                                          * belongs to the same region. 
68                                          *
69                                          * UNSAFE flag is set during method_to_ir (OP_RETHROW)
70                                          */
71                                         while (!unsafe && tbb->next_bb && tbb->region == tbb->next_bb->region) {
72                                                 if (tbb->next_bb->flags & BB_EXCEPTION_UNSAFE)  {
73                                                         unsafe = TRUE;
74                                                         break;
75                                                 }
76                                                 tbb = tbb->next_bb;
77                                         }
78
79                                         if (!unsafe) {
80                                                 MonoInst *jump;
81
82                                                 /* Create dummy inst to allow easier integration in
83                                                  * arch dependent code (opcode ignored)
84                                                  */
85                                                 MONO_INST_NEW (cfg, jump, OP_BR);
86
87                                                 /* Allocate memory for our branch target */
88                                                 jump->inst_i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
89                                                 jump->inst_true_bb = targetbb;
90
91                                                 if (cfg->verbose_level > 2) 
92                                                         g_print ("found exception to optimize - returning branch to BB%d (%s) (instead of throw) for method %s:%s\n", targetbb->block_num, clause->data.catch_class->name, cfg->method->klass->name, cfg->method->name);
93
94                                                 return jump;
95                                         } 
96
97                                         return NULL;
98                                 } else {
99                                         /* Branching to an outer clause could skip inner clauses */
100                                         return NULL;
101                                 }
102                         } else {
103                                 /* Branching to an outer clause could skip inner clauses */
104                                 return NULL;
105                         }
106                 }
107         }
108
109         return NULL;
110 }
111
112 static const int int_cmov_opcodes [] = {
113         OP_CMOV_IEQ,
114         OP_CMOV_INE_UN,
115         OP_CMOV_ILE,
116         OP_CMOV_IGE,
117         OP_CMOV_ILT,
118         OP_CMOV_IGT,
119         OP_CMOV_ILE_UN,
120         OP_CMOV_IGE_UN,
121         OP_CMOV_ILT_UN,
122         OP_CMOV_IGT_UN
123 };
124
125 static const int long_cmov_opcodes [] = {
126         OP_CMOV_LEQ,
127         OP_CMOV_LNE_UN,
128         OP_CMOV_LLE,
129         OP_CMOV_LGE,
130         OP_CMOV_LLT,
131         OP_CMOV_LGT,
132         OP_CMOV_LLE_UN,
133         OP_CMOV_LGE_UN,
134         OP_CMOV_LLT_UN,
135         OP_CMOV_LGT_UN
136 };
137
138 static int
139 br_to_br_un (int opcode)
140 {
141         switch (opcode) {
142         case OP_IBGT:
143                 return OP_IBGT_UN;
144                 break;
145         case OP_IBLE:
146                 return OP_IBLE_UN;
147                 break;
148         case OP_LBGT:
149                 return OP_LBGT_UN;
150                 break;
151         case OP_LBLE:
152                 return OP_LBLE_UN;
153                 break;
154         default:
155                 g_assert_not_reached ();
156                 return -1;
157         }
158 }
159
160 /**
161  * mono_replace_ins:
162  *
163  *   Replace INS with its decomposition which is stored in a series of bblocks starting
164  * at FIRST_BB and ending at LAST_BB. On enter, PREV points to the predecessor of INS. 
165  * On return, it will be set to the last ins of the decomposition.
166  */
167 void
168 mono_replace_ins (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, MonoInst **prev, MonoBasicBlock *first_bb, MonoBasicBlock *last_bb)
169 {
170         MonoInst *next = ins->next;
171
172         if (next && next->opcode == OP_NOP) {
173                 /* Avoid NOPs following branches */
174                 ins->next = next->next;
175                 next = next->next;
176         }
177
178         if (first_bb == last_bb) {
179                 /* 
180                  * Only one replacement bb, merge the code into
181                  * the current bb.
182                  */
183
184                 /* Delete links between the first_bb and its successors */
185                 while (first_bb->out_count)
186                         mono_unlink_bblock (cfg, first_bb, first_bb->out_bb [0]);
187
188                 /* Head */
189                 if (*prev) {
190                         (*prev)->next = first_bb->code;
191                         first_bb->code->prev = (*prev);
192                 } else {
193                         bb->code = first_bb->code;
194                 }
195
196                 /* Tail */
197                 last_bb->last_ins->next = next;
198                 if (next)
199                         next->prev = last_bb->last_ins;
200                 else
201                         bb->last_ins = last_bb->last_ins;
202                 *prev = last_bb->last_ins;
203                 bb->has_array_access |= first_bb->has_array_access;
204         } else {
205                 int i, count;
206                 MonoBasicBlock **tmp_bblocks, *tmp;
207                 MonoInst *last;
208
209                 /* Multiple BBs */
210
211                 /* Set region */
212                 for (tmp = first_bb; tmp; tmp = tmp->next_bb)
213                         tmp->region = bb->region;
214
215                 /* Split the original bb */
216                 if (ins->next)
217                         ins->next->prev = NULL;
218                 ins->next = NULL;
219                 bb->last_ins = ins;
220
221                 /* Merge the second part of the original bb into the last bb */
222                 if (last_bb->last_ins) {
223                         last_bb->last_ins->next = next;
224                         if (next)
225                                 next->prev = last_bb->last_ins;
226                 } else {
227                         last_bb->code = next;
228                 }
229                 last_bb->has_array_access |= bb->has_array_access;
230
231                 if (next) {
232                         for (last = next; last->next != NULL; last = last->next)
233                                 ;
234                         last_bb->last_ins = last;
235                 }
236
237                 for (i = 0; i < bb->out_count; ++i)
238                         mono_link_bblock (cfg, last_bb, bb->out_bb [i]);
239
240                 /* Merge the first (dummy) bb to the original bb */
241                 if (*prev) {
242                         (*prev)->next = first_bb->code;
243                         first_bb->code->prev = (*prev);
244                 } else {
245                         bb->code = first_bb->code;
246                 }
247                 bb->last_ins = first_bb->last_ins;
248                 bb->has_array_access |= first_bb->has_array_access;
249
250                 /* Delete the links between the original bb and its successors */
251                 tmp_bblocks = bb->out_bb;
252                 count = bb->out_count;
253                 for (i = 0; i < count; ++i)
254                         mono_unlink_bblock (cfg, bb, tmp_bblocks [i]);
255
256                 /* Add links between the original bb and the first_bb's successors */
257                 for (i = 0; i < first_bb->out_count; ++i) {
258                         MonoBasicBlock *out_bb = first_bb->out_bb [i];
259
260                         mono_link_bblock (cfg, bb, out_bb);
261                 }
262                 /* Delete links between the first_bb and its successors */
263                 for (i = 0; i < bb->out_count; ++i) {
264                         MonoBasicBlock *out_bb = bb->out_bb [i];
265
266                         mono_unlink_bblock (cfg, first_bb, out_bb);
267                 }
268                 last_bb->next_bb = bb->next_bb;
269                 bb->next_bb = first_bb->next_bb;
270
271                 *prev = NULL;
272         }
273 }
274
275 void
276 mono_if_conversion (MonoCompile *cfg)
277 {
278 #ifdef MONO_ARCH_HAVE_CMOV_OPS
279         MonoBasicBlock *bb;
280         gboolean changed = FALSE;
281
282         if (!(cfg->opt & MONO_OPT_CMOV))
283                 return;
284
285         // FIXME: Make this work with extended bblocks
286
287         /* 
288          * This pass requires somewhat optimized IR code so it should be run after
289          * local cprop/deadce. Also, it should be run before dominator computation, since
290          * it changes control flow.
291          */
292         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
293                 MonoBasicBlock *bb1, *bb2;
294
295         restart:
296                 /* Look for the IR code generated from cond ? a : b
297                  * which is:
298                  * BB:
299                  * b<cond> [BB1BB2]
300                  * BB1:
301                  * <var> <- <a>
302                  * br BB3
303                  * BB2:
304                  * <var> <- <b>
305                  * br BB3
306                  */
307                 if (!(bb->out_count == 2 && !bb->extended))
308                         continue;
309
310                 bb1 = bb->out_bb [0];
311                 bb2 = bb->out_bb [1];
312
313                 if (bb1->in_count == 1 && bb2->in_count == 1 && bb1->out_count == 1 && bb2->out_count == 1 && bb1->out_bb [0] == bb2->out_bb [0]) {
314                         MonoInst *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp;
315                         MonoBasicBlock *true_bb, *false_bb;
316                         gboolean simple, ret;
317                         int dreg, tmp_reg;
318                         CompType comp_type;
319
320                         if (bb->last_ins && (bb->last_ins->opcode == OP_BR_REG || bb->last_ins->opcode == OP_BR))
321                                 continue;
322
323                         /* Find the compare instruction */
324                         if (!bb->last_ins || !bb->last_ins->prev)
325                                 continue;
326                         branch = bb->last_ins;
327                         compare = branch->prev;
328
329                         if (!MONO_IS_COND_BRANCH_OP (branch))
330                                 /* This can happen if a cond branch is optimized away */
331                                 continue;
332
333                         true_bb = branch->inst_true_bb;
334                         false_bb = branch->inst_false_bb;
335
336                         /* 
337                          * Check that bb1 and bb2 are 'simple' and both assign to the same
338                          * variable.
339                          */
340                         /* FIXME: Get rid of the nops earlier */
341                         ins1 = true_bb->code;
342                         while (ins1 && ins1->opcode == OP_NOP)
343                                 ins1 = ins1->next;
344                         ins2 = false_bb->code;
345                         while (ins2 && ins2->opcode == OP_NOP)
346                                 ins2 = ins2->next;
347                         if (!(ins1 && ins2 && ins1->dreg == ins2->dreg && ins1->dreg != -1))
348                                 continue;
349
350                         simple = TRUE;
351                         for (tmp = ins1->next; tmp; tmp = tmp->next)
352                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_BR)))
353                                         simple = FALSE;
354                                         
355                         for (tmp = ins2->next; tmp; tmp = tmp->next)
356                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_BR)))
357                                         simple = FALSE;
358
359                         if (!simple)
360                                 continue;
361
362                         /* We move ins1/ins2 before the compare so they should have no side effect */
363                         if (!(MONO_INS_HAS_NO_SIDE_EFFECT (ins1) && MONO_INS_HAS_NO_SIDE_EFFECT (ins2)))
364                                 continue;
365
366                         /* Moving ins1/ins2 could change the comparison */
367                         /* FIXME: */
368                         if (!((compare->sreg1 != ins1->dreg) && (compare->sreg2 != ins1->dreg)))
369                                 continue;
370
371                         /* FIXME: */
372                         comp_type = mono_opcode_to_type (branch->opcode, compare->opcode);
373                         if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L)))
374                                 continue;
375
376                         /* FIXME: */
377                         /* ins->type might not be set */
378                         if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i')
379                                 continue;
380
381                         if (cfg->verbose_level > 2) {
382                                 printf ("\tBranch -> CMove optimization in BB%d on\n", bb->block_num);
383                                 printf ("\t\t"); mono_print_ins (compare);
384                                 printf ("\t\t"); mono_print_ins (compare->next);
385                                 printf ("\t\t"); mono_print_ins (ins1);
386                                 printf ("\t\t"); mono_print_ins (ins2);
387                         }
388
389                         changed = TRUE;
390
391                         //printf ("HIT!\n");
392
393                         /* Assignments to the return register must remain at the end of bbs */
394                         if (cfg->ret)
395                                 ret = ins1->dreg == cfg->ret->dreg;
396                         else
397                                 ret = FALSE;
398
399                         tmp_reg = mono_alloc_dreg (cfg, STACK_I4);
400                         dreg = ins1->dreg;
401
402                         /* Rewrite ins1 to emit to tmp_reg */
403                         ins1->dreg = tmp_reg;
404
405                         if (ret) {
406                                 dreg = mono_alloc_dreg (cfg, STACK_I4);
407                                 ins2->dreg = dreg;
408                         }
409
410                         /* Remove ins1/ins2 from bb1/bb2 */
411                         MONO_REMOVE_INS (true_bb, ins1);
412                         MONO_REMOVE_INS (false_bb, ins2);
413
414                         /* Move ins1 and ins2 before the comparison */
415                         /* ins1 comes first to avoid ins1 overwriting an argument of ins2 */
416                         mono_bblock_insert_before_ins (bb, compare, ins2);
417                         mono_bblock_insert_before_ins (bb, ins2, ins1);
418
419                         /* Add cmov instruction */
420                         MONO_INST_NEW (cfg, cmov, OP_NOP);
421                         cmov->dreg = dreg;
422                         cmov->sreg1 = dreg;
423                         cmov->sreg2 = tmp_reg;
424                         switch (mono_opcode_to_type (branch->opcode, compare->opcode)) {
425                         case CMP_TYPE_I:
426                                 cmov->opcode = int_cmov_opcodes [mono_opcode_to_cond (branch->opcode)];
427                                 break;
428                         case CMP_TYPE_L:
429                                 cmov->opcode = long_cmov_opcodes [mono_opcode_to_cond (branch->opcode)];
430                                 break;
431                         default:
432                                 g_assert_not_reached ();
433                         }
434                         mono_bblock_insert_after_ins (bb, compare, cmov);
435
436                         if (ret) {
437                                 /* Add an extra move */
438                                 MONO_INST_NEW (cfg, move, OP_MOVE);
439                                 move->dreg = cfg->ret->dreg;
440                                 move->sreg1 = dreg;
441                                 mono_bblock_insert_after_ins (bb, cmov, move);
442                         }
443
444                         /* Rewrite the branch */
445                         branch->opcode = OP_BR;
446                         branch->inst_target_bb = true_bb->out_bb [0];
447                         mono_link_bblock (cfg, bb, branch->inst_target_bb);
448
449                         /* Reorder bblocks */
450                         mono_unlink_bblock (cfg, bb, true_bb);
451                         mono_unlink_bblock (cfg, bb, false_bb);
452                         mono_unlink_bblock (cfg, true_bb, true_bb->out_bb [0]);
453                         mono_unlink_bblock (cfg, false_bb, false_bb->out_bb [0]);
454                         mono_remove_bblock (cfg, true_bb);
455                         mono_remove_bblock (cfg, false_bb);
456
457                         /* Merge bb and its successor if possible */
458                         if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) &&
459                                 (bb->region == bb->out_bb [0]->region)) {
460                                 mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]);
461                                 goto restart;
462                         }
463                 }
464
465                 /* Look for the IR code generated from if (cond) <var> <- <a>
466                  * which is:
467                  * BB:
468                  * b<cond> [BB1BB2]
469                  * BB1:
470                  * <var> <- <a>
471                  * br BB2
472                  */
473
474                 if ((bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) ||
475                         (bb1->in_count == 1 && bb1->out_count == 1 && bb1->out_bb [0] == bb2)) {
476                         MonoInst *compare, *branch, *ins1, *cmov, *tmp;
477                         gboolean simple;
478                         int dreg, tmp_reg;
479                         CompType comp_type;
480                         CompRelation cond;
481                         MonoBasicBlock *next_bb, *code_bb;
482
483                         /* code_bb is the bblock containing code, next_bb is the successor bblock */
484                         if (bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) {
485                                 code_bb = bb2;
486                                 next_bb = bb1;
487                         } else {
488                                 code_bb = bb1;
489                                 next_bb = bb2;
490                         }
491
492                         ins1 = code_bb->code;
493
494                         if (!ins1)
495                                 continue;
496
497                         /* Check that code_bb is simple */
498                         simple = TRUE;
499                         for (tmp = ins1->next; tmp; tmp = tmp->next)
500                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_BR)))
501                                         simple = FALSE;
502
503                         if (!simple)
504                                 continue;
505
506                         /* We move ins1 before the compare so it should have no side effect */
507                         if (!MONO_INS_HAS_NO_SIDE_EFFECT (ins1))
508                                 continue;
509
510                         if (bb->last_ins && bb->last_ins->opcode == OP_BR_REG)
511                                 continue;
512
513                         /* Find the compare instruction */
514
515                         if (!bb->last_ins || !bb->last_ins->prev)
516                                 continue;
517                         branch = bb->last_ins;
518                         compare = branch->prev;
519
520                         if (!MONO_IS_COND_BRANCH_OP (branch))
521                                 /* This can happen if a cond branch is optimized away */
522                                 continue;
523
524                         /* FIXME: */
525                         comp_type = mono_opcode_to_type (branch->opcode, compare->opcode);
526                         if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L)))
527                                 continue;
528
529                         /* FIXME: */
530                         /* ins->type might not be set */
531                         if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i')
532                                 continue;
533
534                         /* FIXME: */
535                         if (cfg->ret && ins1->dreg == cfg->ret->dreg)
536                                 continue;
537
538                         if (cfg->verbose_level > 2) {
539                                 printf ("\tBranch -> CMove optimization (2) in BB%d on\n", bb->block_num);
540                                 printf ("\t\t"); mono_print_ins (compare);
541                                 printf ("\t\t"); mono_print_ins (compare->next);
542                                 printf ("\t\t"); mono_print_ins (ins1);
543                         }
544
545                         changed = TRUE;
546
547                         //printf ("HIT!\n");
548
549                         tmp_reg = mono_alloc_dreg (cfg, STACK_I4);
550                         dreg = ins1->dreg;
551
552                         /* Rewrite ins1 to emit to tmp_reg */
553                         ins1->dreg = tmp_reg;
554
555                         /* Remove ins1 from code_bb */
556                         MONO_REMOVE_INS (code_bb, ins1);
557
558                         /* Move ins1 before the comparison */
559                         mono_bblock_insert_before_ins (bb, compare, ins1);
560
561                         /* Add cmov instruction */
562                         MONO_INST_NEW (cfg, cmov, OP_NOP);
563                         cmov->dreg = dreg;
564                         cmov->sreg1 = dreg;
565                         cmov->sreg2 = tmp_reg;
566                         cond = mono_opcode_to_cond (branch->opcode);
567                         if (branch->inst_false_bb == code_bb)
568                                 cond = mono_negate_cond (cond);
569                         switch (mono_opcode_to_type (branch->opcode, compare->opcode)) {
570                         case CMP_TYPE_I:
571                                 cmov->opcode = int_cmov_opcodes [cond];
572                                 break;
573                         case CMP_TYPE_L:
574                                 cmov->opcode = long_cmov_opcodes [cond];
575                                 break;
576                         default:
577                                 g_assert_not_reached ();
578                         }
579                         mono_bblock_insert_after_ins (bb, compare, cmov);
580
581                         /* Rewrite the branch */
582                         branch->opcode = OP_BR;
583                         branch->inst_target_bb = next_bb;
584                         mono_link_bblock (cfg, bb, branch->inst_target_bb);
585
586                         /* Nullify the branch at the end of code_bb */
587                         if (code_bb->code) {
588                                 branch = code_bb->code;
589                                 MONO_DELETE_INS (code_bb, branch);
590                         }
591
592                         /* Reorder bblocks */
593                         mono_unlink_bblock (cfg, bb, code_bb);
594                         mono_unlink_bblock (cfg, code_bb, next_bb);
595
596                         /* Merge bb and its successor if possible */
597                         if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) &&
598                                 (bb->region == bb->out_bb [0]->region)) {
599                                 mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]);
600
601                                 /* 
602                                  * bbn might have fallen through to the next bb without a branch, 
603                                  * have to add one now (#474718).
604                                  * FIXME: Maybe need to do this more generally in 
605                                  * merge_basic_blocks () ?
606                                  */
607                                 if (!(bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) && bb->out_count) {
608                                         MONO_INST_NEW (cfg, ins1, OP_BR);
609                                         ins1->inst_target_bb = bb->out_bb [0];
610                                         MONO_ADD_INS (bb, ins1);
611                                 }
612                                 goto restart;
613                         }
614                 }
615         }
616
617         /*
618          * Optimize checks like: if (v < 0 || v > limit) by changing then to unsigned
619          * compares. This isn't really if conversion, but it easier to do here than in
620          * optimize_branches () since the IR is already optimized.
621          */
622         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
623                 MonoBasicBlock *bb1, *bb2, *true_bb, *false_bb, *next_bb;
624                 MonoInst *branch1, *branch2, *compare1, *ins;
625
626                 /* Look for the IR code generated from if (<var> < 0 || v > <limit>)
627                  * after branch opts which is:
628                  * BB:
629                  * icompare_imm R [0]
630                  * int_blt [BB1BB2]
631                  * BB2:
632                  * icompare_imm R [<limit>]
633                  * int_ble [BB3BB1]
634                  */
635                 if (!(bb->out_count == 2 && !bb->extended))
636                         continue;
637
638                 bb1 = bb->out_bb [0];
639                 bb2 = bb->out_bb [1];
640
641                 // FIXME: Add more cases
642
643                 /* Check structure */
644                 if (!(bb1->in_count == 2 && bb1->in_bb [0] == bb && bb1->in_bb [1] == bb2 && bb2->in_count == 1 && bb2->out_count == 2))
645                         continue;
646
647                 next_bb = bb2;
648
649                 /* Check first branch */
650                 branch1 = bb->last_ins;
651                 if (!(branch1 && ((branch1->opcode == OP_IBLT) || (branch1->opcode == OP_LBLT)) && (branch1->inst_false_bb == next_bb)))
652                         continue;
653
654                 true_bb = branch1->inst_true_bb;
655
656                 /* Check second branch */
657                 branch2 = next_bb->last_ins;
658                 if (!branch2)
659                         continue;
660
661                 /* mcs sometimes generates inverted branches */
662                 if (((branch2->opcode == OP_IBGT) || (branch2->opcode == OP_LBGT)) && branch2->inst_true_bb == branch1->inst_true_bb)
663                         false_bb = branch2->inst_false_bb;
664                 else if (((branch2->opcode == OP_IBLE) || (branch2->opcode == OP_LBLE)) && branch2->inst_false_bb == branch1->inst_true_bb)
665                         false_bb = branch2->inst_true_bb;
666                 else
667                         continue;
668
669                 /* Check first compare */
670                 compare1 = bb->last_ins->prev;
671                 if (!(compare1 && ((compare1->opcode == OP_ICOMPARE_IMM) || (compare1->opcode == OP_LCOMPARE_IMM)) && compare1->inst_imm == 0))
672                         continue;
673
674                 /* Check second bblock */
675                 ins = next_bb->code;
676                 if (!ins)
677                         continue;
678                 if (((ins->opcode == OP_ICOMPARE_IMM) || (ins->opcode == OP_LCOMPARE_IMM)) && ins->sreg1 == compare1->sreg1 && ins->next == branch2) {
679                         /* The second arg must be positive */
680                         if (ins->inst_imm < 0)
681                                 continue;
682                 } else if (((ins->opcode == OP_LDLEN) || (ins->opcode == OP_STRLEN)) && ins->dreg != compare1->sreg1 && ins->next && ins->next->opcode == OP_ICOMPARE && ins->next->sreg1 == compare1->sreg1 && ins->next->sreg2 == ins->dreg && ins->next->next == branch2) {
683                         /* Another common case: if (index < 0 || index > arr.Length) */
684                 } else {
685                         continue;
686                 }
687
688                 if (cfg->verbose_level > 2) {
689                         printf ("\tSigned->unsigned compare optimization in BB%d on\n", bb->block_num);
690                         printf ("\t\t"); mono_print_ins (compare1);
691                         printf ("\t\t"); mono_print_ins (compare1->next);
692                         printf ("\t\t"); mono_print_ins (ins);
693                 }
694
695                 /* Rewrite the first compare+branch */
696                 MONO_DELETE_INS (bb, compare1);
697                 branch1->opcode = OP_BR;
698                 mono_unlink_bblock (cfg, bb, branch1->inst_true_bb);
699                 mono_unlink_bblock (cfg, bb, branch1->inst_false_bb);
700                 branch1->inst_target_bb = next_bb;
701                 mono_link_bblock (cfg, bb, next_bb);            
702
703                 /* Rewrite the second branch */
704                 branch2->opcode = br_to_br_un (branch2->opcode);
705
706                 mono_merge_basic_blocks (cfg, bb, next_bb);
707         }
708
709 #if 0
710         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
711                 MonoBasicBlock *bb1, *bb2;
712                 MonoInst *prev, *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp;
713                 gboolean simple, ret;
714                 int dreg, tmp_reg;
715                 CompType comp_type;
716
717                 /* Look for the IR code generated from if (cond) <var> <- <a>
718                  * after branch opts which is:
719                  * BB:
720                  * compare
721                  * b<cond> [BB1]
722                  * <var> <- <a>
723                  * BB1:
724                  */
725                 if (!(bb->out_count == 1 && bb->extended && bb->code && bb->code->next && bb->code->next->next))
726                         continue;
727
728                 mono_print_bb (bb, "");
729
730                 /* Find the compare instruction */
731                 prev = NULL;
732                 compare = bb->code;
733                 g_assert (compare);
734                 while (compare->next->next && compare->next->next != bb->last_ins) {
735                         prev = compare;
736                         compare = compare->next;
737                 }
738                 branch = compare->next;
739                 if (!MONO_IS_COND_BRANCH_OP (branch))
740                         continue;
741         }
742 #endif
743
744         if (changed) {
745                 if (cfg->opt & MONO_OPT_BRANCH)
746                         mono_optimize_branches (cfg);
747                 /* Merging bblocks could make some variables local */
748                 mono_handle_global_vregs (cfg);
749                 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
750                         mono_local_cprop (cfg);
751                 if (cfg->opt & MONO_OPT_DEADCE)
752                         mono_local_deadce (cfg);
753         }
754 #endif
755 }
756
757 void
758 mono_nullify_basic_block (MonoBasicBlock *bb) 
759 {
760         bb->in_count = 0;
761         bb->out_count = 0;
762         bb->in_bb = NULL;
763         bb->out_bb = NULL;
764         bb->next_bb = NULL;
765         bb->code = bb->last_ins = NULL;
766         bb->cil_code = NULL;
767 }
768
769 static void 
770 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
771 {
772         int i;
773
774         for (i = 0; i < bb->out_count; i++) {
775                 MonoBasicBlock *ob = bb->out_bb [i];
776                 if (ob == orig) {
777                         if (!repl) {
778                                 if (bb->out_count > 1) {
779                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
780                                 }
781                                 bb->out_count--;
782                         } else {
783                                 bb->out_bb [i] = repl;
784                         }
785                 }
786         }
787 }
788
789 static void 
790 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
791 {
792         int i;
793
794         for (i = 0; i < bb->in_count; i++) {
795                 MonoBasicBlock *ib = bb->in_bb [i];
796                 if (ib == orig) {
797                         if (!repl) {
798                                 if (bb->in_count > 1) {
799                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
800                                 }
801                                 bb->in_count--;
802                         } else {
803                                 bb->in_bb [i] = repl;
804                         }
805                 }
806         }
807 }
808
809 static void
810 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
811         MonoInst *ins;
812         
813         for (ins = bb->code; ins != NULL; ins = ins->next) {
814                 switch (ins->opcode) {
815                 case OP_BR:
816                         if (ins->inst_target_bb == orig)
817                                 ins->inst_target_bb = repl;
818                         break;
819                 case OP_CALL_HANDLER:
820                         if (ins->inst_target_bb == orig)
821                                 ins->inst_target_bb = repl;
822                         break;
823                 case OP_SWITCH: {
824                         int i;
825                         int n = GPOINTER_TO_INT (ins->klass);
826                         for (i = 0; i < n; i++ ) {
827                                 if (ins->inst_many_bb [i] == orig)
828                                         ins->inst_many_bb [i] = repl;
829                         }
830                         break;
831                 }
832                 default:
833                         if (MONO_IS_COND_BRANCH_OP (ins)) {
834                                 if (ins->inst_true_bb == orig)
835                                         ins->inst_true_bb = repl;
836                                 if (ins->inst_false_bb == orig)
837                                         ins->inst_false_bb = repl;
838                         } else if (MONO_IS_JUMP_TABLE (ins)) {
839                                 int i;
840                                 MonoJumpInfoBBTable *table = MONO_JUMP_TABLE_FROM_INS (ins);
841                                 for (i = 0; i < table->table_size; i++ ) {
842                                         if (table->table [i] == orig)
843                                                 table->table [i] = repl;
844                                 }
845                         }
846
847                         break;
848                 }
849         }
850 }
851
852 /**
853   * Check if a bb is useless (is just made of NOPs and ends with an
854   * unconditional branch, or nothing).
855   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
856   * Otherwise, return FALSE;
857   */
858 static gboolean
859 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
860         MonoBasicBlock *target_bb = NULL;
861         MonoInst *inst;
862
863         /* Do not touch handlers */
864         if (bb->region != -1) {
865                 bb->not_useless = TRUE;
866                 return FALSE;
867         }
868         
869         MONO_BB_FOR_EACH_INS (bb, inst) {
870                 switch (inst->opcode) {
871                 case OP_NOP:
872                         break;
873                 case OP_BR:
874                         target_bb = inst->inst_target_bb;
875                         break;
876                 default:
877                         bb->not_useless = TRUE;
878                         return FALSE;
879                 }
880         }
881         
882         if (target_bb == NULL) {
883                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
884                         target_bb = bb->next_bb;
885                 } else {
886                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
887                         return FALSE;
888                 }
889         }
890         
891         /* Do not touch BBs following a switch (they are the "default" branch) */
892         if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == OP_SWITCH)) {
893                 return FALSE;
894         }
895         
896         /* Do not touch BBs following the entry BB and jumping to something that is not */
897         /* thiry "next" bb (the entry BB cannot contain the branch) */
898         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
899                 return FALSE;
900         }
901
902         /* 
903          * Do not touch BBs following a try block as the code in 
904          * mini_method_compile needs them to compute the length of the try block.
905          */
906         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
907                 return FALSE;
908         
909         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
910         if ((target_bb != NULL) && (target_bb != bb)) {
911                 int i;
912
913                 if (cfg->verbose_level > 1) {
914                         printf ("remove_block_if_useless, removed BB%d\n", bb->block_num);
915                 }
916                 
917                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
918                 while (bb->in_count) {
919                         MonoBasicBlock *in_bb = bb->in_bb [0];
920                         mono_unlink_bblock (cfg, in_bb, bb);
921                         mono_link_bblock (cfg, in_bb, target_bb);
922                         replace_out_block_in_code (in_bb, bb, target_bb);
923                 }
924                 
925                 mono_unlink_bblock (cfg, bb, target_bb);
926                 if (previous_bb != cfg->bb_entry && mono_bb_is_fall_through (cfg, previous_bb)) {
927                         for (i = 0; i < previous_bb->out_count; i++) {
928                                 if (previous_bb->out_bb [i] == target_bb) {
929                                         MonoInst *jump;
930                                         MONO_INST_NEW (cfg, jump, OP_BR);
931                                         MONO_ADD_INS (previous_bb, jump);
932                                         jump->cil_code = previous_bb->cil_code;
933                                         jump->inst_target_bb = target_bb;
934                                         break;
935                                 }
936                         }
937                 }
938                 
939                 previous_bb->next_bb = bb->next_bb;
940                 mono_nullify_basic_block (bb);
941                 
942                 return TRUE;
943         } else {
944                 return FALSE;
945         }
946 }
947
948 void
949 mono_merge_basic_blocks (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *bbn) 
950 {
951         MonoInst *inst;
952         MonoBasicBlock *prev_bb;
953         int i;
954
955         bb->has_array_access |= bbn->has_array_access;
956         bb->extended |= bbn->extended;
957
958         mono_unlink_bblock (cfg, bb, bbn);
959         for (i = 0; i < bbn->out_count; ++i)
960                 mono_link_bblock (cfg, bb, bbn->out_bb [i]);
961         while (bbn->out_count)
962                 mono_unlink_bblock (cfg, bbn, bbn->out_bb [0]);
963
964         /* Handle the branch at the end of the bb */
965         if (bb->has_call_handler) {
966                 for (inst = bb->code; inst != NULL; inst = inst->next) {
967                         if (inst->opcode == OP_CALL_HANDLER) {
968                                 g_assert (inst->inst_target_bb == bbn);
969                                 NULLIFY_INS (inst);
970                         }
971                 }
972         }
973         if (bb->has_jump_table) {
974                 for (inst = bb->code; inst != NULL; inst = inst->next) {
975                         if (MONO_IS_JUMP_TABLE (inst)) {
976                                 int i;
977                                 MonoJumpInfoBBTable *table = MONO_JUMP_TABLE_FROM_INS (inst);
978                                 for (i = 0; i < table->table_size; i++ ) {
979                                         /* Might be already NULL from a previous merge */
980                                         if (table->table [i])
981                                                 g_assert (table->table [i] == bbn);
982                                         table->table [i] = NULL;
983                                 }
984                                 /* Can't nullify this as later instructions depend on it */
985                         }
986                 }
987         }
988         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
989                 g_assert (bb->last_ins->inst_false_bb == bbn);
990                 bb->last_ins->inst_false_bb = NULL;
991                 bb->extended = TRUE;
992         } else if (bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) {
993                 NULLIFY_INS (bb->last_ins);
994         }
995
996         bb->has_call_handler |= bbn->has_call_handler;
997         bb->has_jump_table |= bbn->has_jump_table;
998
999         if (bb->last_ins) {
1000                 if (bbn->code) {
1001                         bb->last_ins->next = bbn->code;
1002                         bbn->code->prev = bb->last_ins;
1003                         bb->last_ins = bbn->last_ins;
1004                 }
1005         } else {
1006                 bb->code = bbn->code;
1007                 bb->last_ins = bbn->last_ins;
1008         }
1009
1010         for (prev_bb = cfg->bb_entry; prev_bb && prev_bb->next_bb != bbn; prev_bb = prev_bb->next_bb)
1011                 ;
1012         if (prev_bb) {
1013                 prev_bb->next_bb = bbn->next_bb;
1014         } else {
1015                 /* bbn might not be in the bb list yet */
1016                 if (bb->next_bb == bbn)
1017                         bb->next_bb = bbn->next_bb;
1018         }
1019         mono_nullify_basic_block (bbn);
1020
1021         /* 
1022          * If bbn fell through to its next bblock, have to add a branch, since bb
1023          * will not fall though to the same bblock (#513931).
1024          */
1025         if (bb->last_ins && bb->out_count == 1 && bb->out_bb [0] != bb->next_bb && !MONO_IS_BRANCH_OP (bb->last_ins)) {
1026                 MONO_INST_NEW (cfg, inst, OP_BR);
1027                 inst->inst_target_bb = bb->out_bb [0];
1028                 MONO_ADD_INS (bb, inst);
1029         }
1030 }
1031
1032 static void
1033 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
1034 {
1035         MonoBasicBlock *bbn, *next;
1036
1037         next = bb->next_bb;
1038
1039         /* Find the previous */
1040         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
1041                 ;
1042         if (bbn->next_bb) {
1043                 bbn->next_bb = bb->next_bb;
1044         }
1045
1046         /* Find the last */
1047         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
1048                 ;
1049         bbn->next_bb = bb;
1050         bb->next_bb = NULL;
1051
1052         /* Add a branch */
1053         if (next && (!bb->last_ins || ((bb->last_ins->opcode != OP_NOT_REACHED) && (bb->last_ins->opcode != OP_BR) && (bb->last_ins->opcode != OP_BR_REG) && (!MONO_IS_COND_BRANCH_OP (bb->last_ins))))) {
1054                 MonoInst *ins;
1055
1056                 MONO_INST_NEW (cfg, ins, OP_BR);
1057                 MONO_ADD_INS (bb, ins);
1058                 mono_link_bblock (cfg, bb, next);
1059                 ins->inst_target_bb = next;
1060         }               
1061 }
1062
1063 /*
1064  * mono_remove_block:
1065  *
1066  *   Remove BB from the control flow graph
1067  */
1068 void
1069 mono_remove_bblock (MonoCompile *cfg, MonoBasicBlock *bb) 
1070 {
1071         MonoBasicBlock *tmp_bb;
1072
1073         for (tmp_bb = cfg->bb_entry; tmp_bb && tmp_bb->next_bb != bb; tmp_bb = tmp_bb->next_bb)
1074                 ;
1075
1076         g_assert (tmp_bb);
1077         tmp_bb->next_bb = bb->next_bb;
1078 }
1079
1080 void
1081 mono_remove_critical_edges (MonoCompile *cfg)
1082 {
1083         MonoBasicBlock *bb;
1084         MonoBasicBlock *previous_bb;
1085         
1086         if (cfg->verbose_level > 3) {
1087                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1088                         int i;
1089                         printf ("remove_critical_edges, BEFORE BB%d (in:", bb->block_num);
1090                         for (i = 0; i < bb->in_count; i++) {
1091                                 printf (" %d", bb->in_bb [i]->block_num);
1092                         }
1093                         printf (") (out:");
1094                         for (i = 0; i < bb->out_count; i++) {
1095                                 printf (" %d", bb->out_bb [i]->block_num);
1096                         }
1097                         printf (")");
1098                         if (bb->last_ins != NULL) {
1099                                 printf (" ");
1100                                 mono_print_ins (bb->last_ins);
1101                         }
1102                         printf ("\n");
1103                 }
1104         }
1105         
1106         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
1107                 if (bb->in_count > 1) {
1108                         int in_bb_index;
1109                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
1110                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
1111                                 /* 
1112                                  * Have to remove non-critical edges whose source ends with a BR_REG
1113                                  * ins too, since inserting a computation before the BR_REG could 
1114                                  * overwrite the sreg1 of the ins.
1115                                  */
1116                                 if ((in_bb->out_count > 1) || (in_bb->out_count == 1 && in_bb->last_ins && in_bb->last_ins->opcode == OP_BR_REG)) {
1117                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
1118                                         new_bb->block_num = cfg->num_bblocks++;
1119 //                                      new_bb->real_offset = bb->real_offset;
1120                                         new_bb->region = bb->region;
1121                                         
1122                                         /* Do not alter the CFG while altering the BB list */
1123                                         if (mono_bb_is_fall_through (cfg, previous_bb)) {
1124                                                 if (previous_bb != cfg->bb_entry) {
1125                                                         int i;
1126                                                         /* Make sure previous_bb really falls through bb */
1127                                                         for (i = 0; i < previous_bb->out_count; i++) {
1128                                                                 if (previous_bb->out_bb [i] == bb) {
1129                                                                         MonoInst *jump;
1130                                                                         MONO_INST_NEW (cfg, jump, OP_BR);
1131                                                                         MONO_ADD_INS (previous_bb, jump);
1132                                                                         jump->cil_code = previous_bb->cil_code;
1133                                                                         jump->inst_target_bb = bb;
1134                                                                         break;
1135                                                                 }
1136                                                         }
1137                                                 } else {
1138                                                         /* We cannot add any inst to the entry BB, so we must */
1139                                                         /* put a new BB in the middle to hold the OP_BR */
1140                                                         MonoInst *jump;
1141                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
1142                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
1143 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
1144                                                         new_bb_after_entry->region = bb->region;
1145                                                         
1146                                                         MONO_INST_NEW (cfg, jump, OP_BR);
1147                                                         MONO_ADD_INS (new_bb_after_entry, jump);
1148                                                         jump->cil_code = bb->cil_code;
1149                                                         jump->inst_target_bb = bb;
1150
1151                                                         mono_unlink_bblock (cfg, previous_bb, bb);
1152                                                         mono_link_bblock (cfg, new_bb_after_entry, bb);
1153                                                         mono_link_bblock (cfg, previous_bb, new_bb_after_entry);
1154                                                         
1155                                                         previous_bb->next_bb = new_bb_after_entry;
1156                                                         previous_bb = new_bb_after_entry;
1157
1158                                                         if (cfg->verbose_level > 2) {
1159                                                                 printf ("remove_critical_edges, added helper BB%d jumping to BB%d\n", new_bb_after_entry->block_num, bb->block_num);
1160                                                         }
1161                                                 }
1162                                         }
1163                                         
1164                                         /* Insert new_bb in the BB list */
1165                                         previous_bb->next_bb = new_bb;
1166                                         new_bb->next_bb = bb;
1167                                         previous_bb = new_bb;
1168                                         
1169                                         /* Setup in_bb and out_bb */
1170                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
1171                                         new_bb->in_bb [0] = in_bb;
1172                                         new_bb->in_count = 1;
1173                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
1174                                         new_bb->out_bb [0] = bb;
1175                                         new_bb->out_count = 1;
1176                                         
1177                                         /* Relink in_bb and bb to (from) new_bb */
1178                                         replace_out_block (in_bb, bb, new_bb);
1179                                         replace_out_block_in_code (in_bb, bb, new_bb);
1180                                         replace_in_block (bb, in_bb, new_bb);
1181                                         
1182                                         if (cfg->verbose_level > 2) {
1183                                                 printf ("remove_critical_edges, removed critical edge from BB%d to BB%d (added BB%d)\n", in_bb->block_num, bb->block_num, new_bb->block_num);
1184                                         }
1185                                 }
1186                         }
1187                 }
1188         }
1189         
1190         if (cfg->verbose_level > 3) {
1191                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1192                         int i;
1193                         printf ("remove_critical_edges, AFTER BB%d (in:", bb->block_num);
1194                         for (i = 0; i < bb->in_count; i++) {
1195                                 printf (" %d", bb->in_bb [i]->block_num);
1196                         }
1197                         printf (") (out:");
1198                         for (i = 0; i < bb->out_count; i++) {
1199                                 printf (" %d", bb->out_bb [i]->block_num);
1200                         }
1201                         printf (")");
1202                         if (bb->last_ins != NULL) {
1203                                 printf (" ");
1204                                 mono_print_ins (bb->last_ins);
1205                         }
1206                         printf ("\n");
1207                 }
1208         }
1209 }
1210
1211 /*
1212  * Optimizes the branches on the Control Flow Graph
1213  *
1214  */
1215 void
1216 mono_optimize_branches (MonoCompile *cfg)
1217 {
1218         int i, changed = FALSE;
1219         MonoBasicBlock *bb, *bbn;
1220         guint32 niterations;
1221
1222         /*
1223          * Some crazy loops could cause the code below to go into an infinite
1224          * loop, see bug #53003 for an example. To prevent this, we put an upper
1225          * bound on the number of iterations.
1226          */
1227         if (cfg->num_bblocks > 1000)
1228                 niterations = cfg->num_bblocks * 2;
1229         else
1230                 niterations = 1000;
1231         
1232         do {
1233                 MonoBasicBlock *previous_bb;
1234                 changed = FALSE;
1235                 niterations --;
1236
1237                 /* we skip the entry block (exit is handled specially instead ) */
1238                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
1239                         /* dont touch code inside exception clauses */
1240                         if (bb->region != -1)
1241                                 continue;
1242
1243                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
1244                                 changed = TRUE;
1245                                 continue;
1246                         }
1247
1248                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) {
1249                                 if (cfg->verbose_level > 2)
1250                                         g_print ("nullify block triggered %d\n", bbn->block_num);
1251
1252                                 bb->next_bb = bbn->next_bb;
1253
1254                                 for (i = 0; i < bbn->out_count; i++)
1255                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
1256
1257                                 mono_nullify_basic_block (bbn);                 
1258                                 changed = TRUE;
1259                         }
1260
1261                         if (bb->out_count == 1) {
1262                                 bbn = bb->out_bb [0];
1263
1264                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
1265                                 if (bb->last_ins && (bb->last_ins->opcode != OP_BR) && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1266                                         bb->last_ins->opcode = OP_BR;
1267                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
1268                                         changed = TRUE;
1269                                         if (cfg->verbose_level > 2)
1270                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
1271                                 }
1272
1273                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
1274                                         /* the block are in sequence anyway ... */
1275
1276                                         /* branches to the following block can be removed */
1277                                         if (bb->last_ins && bb->last_ins->opcode == OP_BR) {
1278                                                 bb->last_ins->opcode = OP_NOP;
1279                                                 changed = TRUE;
1280                                                 if (cfg->verbose_level > 2)
1281                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
1282                                         }
1283
1284                                         if (bbn->in_count == 1 && !bb->extended) {
1285                                                 if (bbn != cfg->bb_exit) {
1286                                                         if (cfg->verbose_level > 2)
1287                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
1288                                                         mono_merge_basic_blocks (cfg, bb, bbn);
1289                                                         changed = TRUE;
1290                                                         continue;
1291                                                 }
1292
1293                                                 //mono_print_bb_code (bb);
1294                                         }
1295                                 }
1296                         }
1297
1298                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) {
1299                                 if (cfg->verbose_level > 2) {
1300                                         g_print ("nullify block triggered %d\n", bbn->block_num);
1301                                 }
1302                                 bb->next_bb = bbn->next_bb;
1303
1304                                 for (i = 0; i < bbn->out_count; i++)
1305                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
1306
1307                                 mono_nullify_basic_block (bbn);                 
1308                                 changed = TRUE;
1309                                 continue;
1310                         }
1311
1312                         if (bb->out_count == 1) {
1313                                 bbn = bb->out_bb [0];
1314
1315                                 if (bb->last_ins && bb->last_ins->opcode == OP_BR) {
1316                                         bbn = bb->last_ins->inst_target_bb;
1317                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
1318                                                 bbn->code->inst_target_bb != bbn &&
1319                                             bbn->code->inst_target_bb->region == bb->region) {
1320                                                 
1321                                                 if (cfg->verbose_level > 2)
1322                                                         g_print ("branch to branch triggered %d -> %d -> %d\n", bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
1323
1324                                                 replace_in_block (bbn, bb, NULL);
1325                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
1326                                                 mono_link_bblock (cfg, bb, bbn->code->inst_target_bb);
1327                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
1328                                                 changed = TRUE;
1329                                                 continue;
1330                                         }
1331                                 }
1332                         } else if (bb->out_count == 2) {
1333                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
1334                                         int branch_result;
1335                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
1336
1337                                         if (bb->last_ins->flags & MONO_INST_CFOLD_TAKEN)
1338                                                 branch_result = BRANCH_TAKEN;
1339                                         else if (bb->last_ins->flags & MONO_INST_CFOLD_NOT_TAKEN)
1340                                                 branch_result = BRANCH_NOT_TAKEN;
1341                                         else
1342                                                 branch_result = BRANCH_UNDEF;
1343
1344                                         if (branch_result == BRANCH_TAKEN) {
1345                                                 taken_branch_target = bb->last_ins->inst_true_bb;
1346                                                 untaken_branch_target = bb->last_ins->inst_false_bb;
1347                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
1348                                                 taken_branch_target = bb->last_ins->inst_false_bb;
1349                                                 untaken_branch_target = bb->last_ins->inst_true_bb;
1350                                         }
1351                                         if (taken_branch_target) {
1352                                                 /* if mono_eval_cond_branch () is ever taken to handle 
1353                                                  * non-constant values to compare, issue a pop here.
1354                                                  */
1355                                                 bb->last_ins->opcode = OP_BR;
1356                                                 bb->last_ins->inst_target_bb = taken_branch_target;
1357                                                 if (!bb->extended)
1358                                                         mono_unlink_bblock (cfg, bb, untaken_branch_target);
1359                                                 changed = TRUE;
1360                                                 continue;
1361                                         }
1362                                         bbn = bb->last_ins->inst_true_bb;
1363                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
1364                                             bbn->code->inst_target_bb->region == bb->region) {
1365                                                 if (cfg->verbose_level > 2)             
1366                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
1367                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
1368                                                                  bbn->code->opcode);
1369
1370                                                 /* 
1371                                                  * Unlink, then relink bblocks to avoid various
1372                                                  * tricky situations when the two targets of the branch
1373                                                  * are equal, or will become equal after the change.
1374                                                  */
1375                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1376                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1377
1378                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
1379
1380                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1381                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1382
1383                                                 changed = TRUE;
1384                                                 continue;
1385                                         }
1386
1387                                         bbn = bb->last_ins->inst_false_bb;
1388                                         if (bbn && bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
1389                                             bbn->code->inst_target_bb->region == bb->region) {
1390                                                 if (cfg->verbose_level > 2)
1391                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
1392                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
1393                                                                  bbn->code->opcode);
1394
1395                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1396                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1397
1398                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
1399
1400                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1401                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1402
1403                                                 changed = TRUE;
1404                                                 continue;
1405                                         }
1406
1407                                         bbn = bb->last_ins->inst_false_bb;
1408                                         /*
1409                                          * If bb is an extended bb, it could contain an inside branch to bbn.
1410                                          * FIXME: Enable the optimization if that is not true.
1411                                          * If bblocks_linked () is true, then merging bb and bbn
1412                                          * would require addition of an extra branch at the end of bbn 
1413                                          * slowing down loops.
1414                                          */
1415                                         if (bbn && bb->region == bbn->region && bbn->in_count == 1 && cfg->enable_extended_bblocks && bbn != cfg->bb_exit && !bb->extended && !bbn->out_of_line && !mono_bblocks_linked (bbn, bb)) {
1416                                                 g_assert (bbn->in_bb [0] == bb);
1417                                                 if (cfg->verbose_level > 2)
1418                                                         g_print ("merge false branch target triggered BB%d -> BB%d\n", bb->block_num, bbn->block_num);
1419                                                 mono_merge_basic_blocks (cfg, bb, bbn);
1420                                                 changed = TRUE;
1421                                                 continue;
1422                                         }
1423                                 }
1424
1425                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
1426                                         if (bb->last_ins->inst_false_bb && bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region) && !cfg->disable_out_of_line_bblocks) {
1427                                                 /* Reverse the branch */
1428                                                 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
1429                                                 bbn = bb->last_ins->inst_false_bb;
1430                                                 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
1431                                                 bb->last_ins->inst_true_bb = bbn;
1432
1433                                                 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
1434                                                 if (cfg->verbose_level > 2)
1435                                                         g_print ("cbranch to throw block triggered %d.\n", 
1436                                                                          bb->block_num);
1437                                         }
1438                                 }
1439                         }
1440                 }
1441         } while (changed && (niterations > 0));
1442 }
1443
1444 #endif /* DISABLE_JIT */