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