1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)c1_IR.cpp    1.161 08/11/07 15:47:10 JVM"
   3 #endif
   4 /*
   5  * Copyright 1999-2008 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 # include "incls/_precompiled.incl"
  29 # include "incls/_c1_IR.cpp.incl"
  30 
  31 
  32 // Implementation of XHandlers
  33 //
  34 // Note: This code could eventually go away if we are
  35 //       just using the ciExceptionHandlerStream.
  36 
  37 XHandlers::XHandlers(ciMethod* method) : _list(method->exception_table_length()) {
  38   ciExceptionHandlerStream s(method);
  39   while (!s.is_done()) {
  40     _list.append(new XHandler(s.handler()));
  41     s.next();
  42   }
  43   assert(s.count() == method->exception_table_length(), "exception table lengths inconsistent");
  44 }
  45 
  46 // deep copy of all XHandler contained in list
  47 XHandlers::XHandlers(XHandlers* other) :
  48   _list(other->length())
  49 { 
  50   for (int i = 0; i < other->length(); i++) {
  51     _list.append(new XHandler(other->handler_at(i)));
  52   }
  53 }
  54 
  55 // Returns whether a particular exception type can be caught.  Also
  56 // returns true if klass is unloaded or any exception handler
  57 // classes are unloaded.  type_is_exact indicates whether the throw
  58 // is known to be exactly that class or it might throw a subtype.
  59 bool XHandlers::could_catch(ciInstanceKlass* klass, bool type_is_exact) const {
  60   // the type is unknown so be conservative
  61   if (!klass->is_loaded()) {
  62     return true;
  63   }
  64 
  65   for (int i = 0; i < length(); i++) {
  66     XHandler* handler = handler_at(i);
  67     if (handler->is_catch_all()) {
  68       // catch of ANY
  69       return true;
  70     }
  71     ciInstanceKlass* handler_klass = handler->catch_klass();
  72     // if it's unknown it might be catchable
  73     if (!handler_klass->is_loaded()) {
  74       return true;
  75     }
  76     // if the throw type is definitely a subtype of the catch type
  77     // then it can be caught.
  78     if (klass->is_subtype_of(handler_klass)) {
  79       return true;
  80     }
  81     if (!type_is_exact) {
  82       // If the type isn't exactly known then it can also be caught by
  83       // catch statements where the inexact type is a subtype of the
  84       // catch type.
  85       // given: foo extends bar extends Exception
  86       // throw bar can be caught by catch foo, catch bar, and catch
  87       // Exception, however it can't be caught by any handlers without
  88       // bar in its type hierarchy.
  89       if (handler_klass->is_subtype_of(klass)) {
  90         return true;
  91       }
  92     }
  93   }
  94 
  95   return false;
  96 }
  97 
  98 
  99 bool XHandlers::equals(XHandlers* others) const {
 100   if (others == NULL) return false;
 101   if (length() != others->length()) return false;
 102 
 103   for (int i = 0; i < length(); i++) {
 104     if (!handler_at(i)->equals(others->handler_at(i))) return false;
 105   }
 106   return true;
 107 }
 108 
 109 bool XHandler::equals(XHandler* other) const {
 110   assert(entry_pco() != -1 && other->entry_pco() != -1, "must have entry_pco");
 111 
 112   if (entry_pco() != other->entry_pco()) return false;
 113   if (scope_count() != other->scope_count()) return false;
 114   if (_desc != other->_desc) return false;
 115 
 116   assert(entry_block() == other->entry_block(), "entry_block must be equal when entry_pco is equal");
 117   return true;
 118 }
 119 
 120 
 121 // Implementation of IRScope
 122 
 123 BlockBegin* IRScope::header_block(BlockBegin* entry, BlockBegin::Flag f, ValueStack* state) {
 124   if (entry == NULL) return NULL;
 125   assert(entry->is_set(f), "entry/flag mismatch");
 126   // create header block
 127   BlockBegin* h = new BlockBegin(entry->bci());
 128   BlockEnd* g = new Goto(entry, false);
 129   h->set_next(g, entry->bci());
 130   h->set_end(g);
 131   h->set(f);
 132   // setup header block end state
 133   ValueStack* s = state->copy(); // can use copy since stack is empty (=> no phis)
 134   assert(s->stack_is_empty(), "must have empty stack at entry point");
 135   g->set_state(s);
 136   return h;
 137 }
 138 
 139 
 140 BlockBegin* IRScope::build_graph(Compilation* compilation, int osr_bci) {
 141   GraphBuilder gm(compilation, this);
 142   NOT_PRODUCT(if (PrintValueNumbering && Verbose) gm.print_stats());
 143   if (compilation->bailed_out()) return NULL;
 144   return gm.start();
 145 }
 146 
 147 
 148 IRScope::IRScope(Compilation* compilation, IRScope* caller, int caller_bci, ciMethod* method, int osr_bci, bool create_graph)
 149 : _callees(2)
 150 , _compilation(compilation)
 151 , _lock_stack_size(-1)
 152 , _requires_phi_function(method->max_locals())
 153 {
 154   _caller             = caller;
 155   _caller_bci         = caller == NULL ? -1 : caller_bci;
 156   _caller_state       = NULL; // Must be set later if needed
 157   _level              = caller == NULL ?  0 : caller->level() + 1;
 158   _method             = method;
 159   _xhandlers          = new XHandlers(method);
 160   _number_of_locks    = 0;
 161   _monitor_pairing_ok = method->has_balanced_monitors();
 162   _start              = NULL;
 163 
 164   if (osr_bci == -1) {
 165     _requires_phi_function.clear();
 166   } else {
 167         // selective creation of phi functions is not possibel in osr-methods
 168     _requires_phi_function.set_range(0, method->max_locals());
 169   }
 170 
 171   assert(method->holder()->is_loaded() , "method holder must be loaded");
 172 
 173   // build graph if monitor pairing is ok
 174   if (create_graph && monitor_pairing_ok()) _start = build_graph(compilation, osr_bci);
 175 }
 176 
 177 
 178 int IRScope::max_stack() const {
 179   int my_max = method()->max_stack();
 180   int callee_max = 0;
 181   for (int i = 0; i < number_of_callees(); i++) {
 182     callee_max = MAX2(callee_max, callee_no(i)->max_stack());
 183   }
 184   return my_max + callee_max;
 185 }
 186 
 187 
 188 void IRScope::compute_lock_stack_size() {
 189   if (!InlineMethodsWithExceptionHandlers) {
 190     _lock_stack_size = 0;
 191     return;
 192   }
 193 
 194   // Figure out whether we have to preserve expression stack elements
 195   // for parent scopes, and if so, how many
 196   IRScope* cur_scope = this;
 197   while (cur_scope != NULL && !cur_scope->xhandlers()->has_handlers()) {
 198     cur_scope = cur_scope->caller();
 199   }
 200   _lock_stack_size = (cur_scope == NULL ? 0 :
 201                       (cur_scope->caller_state() == NULL ? 0 :
 202                        cur_scope->caller_state()->stack_size()));
 203 }
 204 
 205 int IRScope::top_scope_bci() const {
 206   assert(!is_top_scope(), "no correct answer for top scope possible");
 207   const IRScope* scope = this;
 208   while (!scope->caller()->is_top_scope()) {
 209     scope = scope->caller();
 210   }
 211   return scope->caller_bci();
 212 }
 213 
 214 
 215 
 216 // Implementation of CodeEmitInfo
 217 
 218 // Stack must be NON-null
 219 CodeEmitInfo::CodeEmitInfo(int bci, ValueStack* stack, XHandlers* exception_handlers)
 220   : _scope(stack->scope())
 221   , _bci(bci)
 222   , _scope_debug_info(NULL)
 223   , _oop_map(NULL)
 224   , _stack(stack)
 225   , _exception_handlers(exception_handlers)
 226   , _next(NULL)
 227   , _id(-1) {
 228   assert(_stack != NULL, "must be non null");
 229   assert(_bci == SynchronizationEntryBCI || Bytecodes::is_defined(scope()->method()->java_code_at_bci(_bci)), "make sure bci points at a real bytecode");
 230 }
 231 
 232 
 233 CodeEmitInfo::CodeEmitInfo(CodeEmitInfo* info, bool lock_stack_only)
 234   : _scope(info->_scope)
 235   , _exception_handlers(NULL)
 236   , _bci(info->_bci)
 237   , _scope_debug_info(NULL)
 238   , _oop_map(NULL) {
 239   if (lock_stack_only) {
 240     if (info->_stack != NULL) {
 241       _stack = info->_stack->copy_locks();
 242     } else {
 243       _stack = NULL;
 244     }
 245   } else {
 246     _stack = info->_stack;
 247   }
 248 
 249   // deep copy of exception handlers
 250   if (info->_exception_handlers != NULL) {
 251     _exception_handlers = new XHandlers(info->_exception_handlers);
 252   }
 253 }
 254 
 255 
 256 void CodeEmitInfo::record_debug_info(DebugInformationRecorder* recorder, int pc_offset) {
 257   // record the safepoint before recording the debug info for enclosing scopes
 258   recorder->add_safepoint(pc_offset, _oop_map->deep_copy());
 259   _scope_debug_info->record_debug_info(recorder, pc_offset);
 260   recorder->end_safepoint(pc_offset);
 261 }
 262 
 263 
 264 void CodeEmitInfo::add_register_oop(LIR_Opr opr) {
 265   assert(_oop_map != NULL, "oop map must already exist");
 266   assert(opr->is_single_cpu(), "should not call otherwise");
 267 
 268   int frame_size = frame_map()->framesize();
 269   int arg_count = frame_map()->oop_map_arg_count();
 270   VMReg name = frame_map()->regname(opr);
 271   _oop_map->set_oop(name);
 272 }
 273 
 274 
 275 
 276 
 277 // Implementation of IR
 278 
 279 IR::IR(Compilation* compilation, ciMethod* method, int osr_bci) :
 280     _locals_size(in_WordSize(-1))
 281   , _num_loops(0) {
 282   // initialize data structures
 283   ValueType::initialize();
 284   Instruction::initialize();
 285   BlockBegin::initialize();
 286   GraphBuilder::initialize();
 287   // setup IR fields
 288   _compilation = compilation;
 289   _top_scope   = new IRScope(compilation, NULL, -1, method, osr_bci, true);
 290   _code        = NULL;
 291 }
 292 
 293 
 294 void IR::optimize() {
 295   Optimizer opt(this);
 296   if (DoCEE) {
 297     opt.eliminate_conditional_expressions();
 298 #ifndef PRODUCT
 299     if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after CEE"); print(true); }
 300     if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after CEE"); print(false); }
 301 #endif
 302   }
 303   if (EliminateBlocks) {
 304     opt.eliminate_blocks();
 305 #ifndef PRODUCT
 306     if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after block elimination"); print(true); }
 307     if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after block elimination"); print(false); }
 308 #endif
 309   }
 310   if (EliminateNullChecks) {
 311     opt.eliminate_null_checks();
 312 #ifndef PRODUCT
 313     if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after null check elimination"); print(true); }
 314     if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after null check elimination"); print(false); }
 315 #endif
 316   }
 317 }
 318 
 319 
 320 static int sort_pairs(BlockPair** a, BlockPair** b) {
 321   if ((*a)->from() == (*b)->from()) {
 322     return (*a)->to()->block_id() - (*b)->to()->block_id();
 323   } else {
 324     return (*a)->from()->block_id() - (*b)->from()->block_id();
 325   }
 326 }
 327 
 328 
 329 class CriticalEdgeFinder: public BlockClosure {
 330   BlockPairList blocks;
 331   IR*       _ir;
 332   
 333  public:
 334   CriticalEdgeFinder(IR* ir): _ir(ir) {}
 335   void block_do(BlockBegin* bb) {
 336     BlockEnd* be = bb->end();
 337     int nos = be->number_of_sux();
 338     if (nos >= 2) {
 339       for (int i = 0; i < nos; i++) {
 340         BlockBegin* sux = be->sux_at(i);
 341         if (sux->number_of_preds() >= 2) {
 342           blocks.append(new BlockPair(bb, sux));
 343         }
 344       }
 345     }
 346   }
 347 
 348   void split_edges() {
 349     BlockPair* last_pair = NULL;
 350     blocks.sort(sort_pairs);
 351     for (int i = 0; i < blocks.length(); i++) {
 352       BlockPair* pair = blocks.at(i);
 353       if (last_pair != NULL && pair->is_same(last_pair)) continue;
 354       BlockBegin* from = pair->from();
 355       BlockBegin* to = pair->to();
 356       BlockBegin* split = from->insert_block_between(to);
 357 #ifndef PRODUCT
 358       if ((PrintIR || PrintIR1) && Verbose) {
 359         tty->print_cr("Split critical edge B%d -> B%d (new block B%d)",
 360                       from->block_id(), to->block_id(), split->block_id());
 361       }
 362 #endif
 363       last_pair = pair;
 364     }
 365   }
 366 };
 367 
 368 void IR::split_critical_edges() {
 369   CriticalEdgeFinder cef(this);
 370 
 371   iterate_preorder(&cef);
 372   cef.split_edges();
 373 }
 374 
 375 
 376 class UseCountComputer: public AllStatic {
 377  private:
 378   static void update_use_count(Value* n) {
 379     // Local instructions and Phis for expression stack values at the
 380     // start of basic blocks are not added to the instruction list
 381     if ((*n)->bci() == -99 && (*n)->as_Local() == NULL &&
 382         (*n)->as_Phi() == NULL) {
 383       assert(false, "a node was not appended to the graph");
 384       Compilation::current_compilation()->bailout("a node was not appended to the graph");
 385     }
 386     // use n's input if not visited before
 387     if (!(*n)->is_pinned() && !(*n)->has_uses()) {
 388       // note: a) if the instruction is pinned, it will be handled by compute_use_count
 389       //       b) if the instruction has uses, it was touched before
 390       //       => in both cases we don't need to update n's values
 391       uses_do(n);
 392     }
 393     // use n
 394     (*n)->_use_count++;
 395   }
 396 
 397   static Values* worklist;
 398   static int depth;
 399   enum {
 400     max_recurse_depth = 20
 401   };
 402 
 403   static void uses_do(Value* n) {
 404     depth++;
 405     if (depth > max_recurse_depth) {
 406       // don't allow the traversal to recurse too deeply
 407       worklist->push(*n);
 408     } else {
 409       (*n)->input_values_do(update_use_count);
 410       // special handling for some instructions
 411       if ((*n)->as_BlockEnd() != NULL) {
 412         // note on BlockEnd:
 413         //   must 'use' the stack only if the method doesn't
 414         //   terminate, however, in those cases stack is empty
 415         (*n)->state_values_do(update_use_count);
 416       }
 417     }
 418     depth--;
 419   }
 420 
 421   static void basic_compute_use_count(BlockBegin* b) {
 422     depth = 0;
 423     // process all pinned nodes as the roots of expression trees
 424     for (Instruction* n = b; n != NULL; n = n->next()) {
 425       if (n->is_pinned()) uses_do(&n);
 426     }
 427     assert(depth == 0, "should have counted back down");
 428 
 429     // now process any unpinned nodes which recursed too deeply
 430     while (worklist->length() > 0) {
 431       Value t = worklist->pop();
 432       if (!t->is_pinned()) {
 433         // compute the use count
 434         uses_do(&t);
 435 
 436         // pin the instruction so that LIRGenerator doesn't recurse
 437         // too deeply during it's evaluation.
 438         t->pin();
 439       }
 440     }
 441     assert(depth == 0, "should have counted back down");
 442   }
 443 
 444  public:
 445   static void compute(BlockList* blocks) {
 446     worklist = new Values();
 447     blocks->blocks_do(basic_compute_use_count);
 448     worklist = NULL;
 449   }
 450 };
 451 
 452 
 453 Values* UseCountComputer::worklist = NULL;
 454 int UseCountComputer::depth = 0;
 455 
 456 // helper macro for short definition of trace-output inside code
 457 #ifndef PRODUCT
 458   #define TRACE_LINEAR_SCAN(level, code)       \
 459     if (TraceLinearScanLevel >= level) {       \
 460       code;                                    \
 461     }
 462 #else 
 463   #define TRACE_LINEAR_SCAN(level, code)
 464 #endif
 465 
 466 class ComputeLinearScanOrder : public StackObj {
 467  private:
 468   int        _max_block_id;        // the highest block_id of a block
 469   int        _num_blocks;          // total number of blocks (smaller than _max_block_id)
 470   int        _num_loops;           // total number of loops
 471   bool       _iterative_dominators;// method requires iterative computation of dominatiors
 472 
 473   BlockList* _linear_scan_order;   // the resulting list of blocks in correct order
 474 
 475   BitMap     _visited_blocks;      // used for recursive processing of blocks
 476   BitMap     _active_blocks;       // used for recursive processing of blocks
 477   BitMap     _dominator_blocks;    // temproary BitMap used for computation of dominator
 478   intArray   _forward_branches;    // number of incoming forward branches for each block
 479   BlockList  _loop_end_blocks;     // list of all loop end blocks collected during count_edges
 480   BitMap2D   _loop_map;            // two-dimensional bit set: a bit is set if a block is contained in a loop
 481   BlockList  _work_list;           // temporary list (used in mark_loops and compute_order)
 482 
 483   // accessors for _visited_blocks and _active_blocks
 484   void init_visited()                     { _active_blocks.clear(); _visited_blocks.clear(); }
 485   bool is_visited(BlockBegin* b) const    { return _visited_blocks.at(b->block_id()); }
 486   bool is_active(BlockBegin* b) const     { return _active_blocks.at(b->block_id()); }
 487   void set_visited(BlockBegin* b)         { assert(!is_visited(b), "already set"); _visited_blocks.set_bit(b->block_id()); }
 488   void set_active(BlockBegin* b)          { assert(!is_active(b), "already set");  _active_blocks.set_bit(b->block_id()); }
 489   void clear_active(BlockBegin* b)        { assert(is_active(b), "not already");   _active_blocks.clear_bit(b->block_id()); }
 490 
 491   // accessors for _forward_branches
 492   void inc_forward_branches(BlockBegin* b) { _forward_branches.at_put(b->block_id(), _forward_branches.at(b->block_id()) + 1); }
 493   int  dec_forward_branches(BlockBegin* b) { _forward_branches.at_put(b->block_id(), _forward_branches.at(b->block_id()) - 1); return _forward_branches.at(b->block_id()); }
 494 
 495   // accessors for _loop_map
 496   bool is_block_in_loop   (int loop_idx, BlockBegin* b) const { return _loop_map.at(loop_idx, b->block_id()); }
 497   void set_block_in_loop  (int loop_idx, BlockBegin* b)       { _loop_map.set_bit(loop_idx, b->block_id()); }
 498   void clear_block_in_loop(int loop_idx, int block_id)        { _loop_map.clear_bit(loop_idx, block_id); }
 499 
 500   // count edges between blocks
 501   void count_edges(BlockBegin* cur, BlockBegin* parent);
 502 
 503   // loop detection
 504   void mark_loops();
 505   void clear_non_natural_loops(BlockBegin* start_block);
 506   void assign_loop_depth(BlockBegin* start_block);
 507 
 508   // computation of final block order
 509   BlockBegin* common_dominator(BlockBegin* a, BlockBegin* b);
 510   void compute_dominator(BlockBegin* cur, BlockBegin* parent);
 511   int  compute_weight(BlockBegin* cur);
 512   bool ready_for_processing(BlockBegin* cur);
 513   void sort_into_work_list(BlockBegin* b);
 514   void append_block(BlockBegin* cur);
 515   void compute_order(BlockBegin* start_block);
 516 
 517   // fixup of dominators for non-natural loops
 518   bool compute_dominators_iter();
 519   void compute_dominators();
 520 
 521   // debug functions
 522   NOT_PRODUCT(void print_blocks();)
 523   DEBUG_ONLY(void verify();)
 524 
 525  public:
 526   ComputeLinearScanOrder(BlockBegin* start_block);
 527 
 528   // accessors for final result
 529   BlockList* linear_scan_order() const    { return _linear_scan_order; }
 530   int        num_loops() const            { return _num_loops; }
 531 };
 532 
 533 
 534 ComputeLinearScanOrder::ComputeLinearScanOrder(BlockBegin* start_block) : 
 535   _max_block_id(BlockBegin::number_of_blocks()),
 536   _num_blocks(0),
 537   _num_loops(0),
 538   _iterative_dominators(false),
 539   _visited_blocks(_max_block_id),
 540   _active_blocks(_max_block_id),
 541   _dominator_blocks(_max_block_id),
 542   _forward_branches(_max_block_id, 0),
 543   _loop_end_blocks(8),
 544   _work_list(8),
 545   _linear_scan_order(NULL), // initialized later with correct size
 546   _loop_map(0, 0)           // initialized later with correct size
 547 {
 548   TRACE_LINEAR_SCAN(2, "***** computing linear-scan block order");
 549 
 550   init_visited();
 551   count_edges(start_block, NULL);
 552 
 553   if (_num_loops > 0) {
 554     mark_loops();
 555     clear_non_natural_loops(start_block);
 556     assign_loop_depth(start_block);
 557   }
 558 
 559   compute_order(start_block);
 560   compute_dominators();
 561 
 562   NOT_PRODUCT(print_blocks());
 563   DEBUG_ONLY(verify());
 564 }
 565 
 566 
 567 // Traverse the CFG:
 568 // * count total number of blocks
 569 // * count all incoming edges and backward incoming edges
 570 // * number loop header blocks
 571 // * create a list with all loop end blocks
 572 void ComputeLinearScanOrder::count_edges(BlockBegin* cur, BlockBegin* parent) {
 573   TRACE_LINEAR_SCAN(3, tty->print_cr("Enter count_edges for block B%d coming from B%d", cur->block_id(), parent != NULL ? parent->block_id() : -1));
 574   assert(cur->dominator() == NULL, "dominator already initialized");
 575 
 576   if (is_active(cur)) {
 577     TRACE_LINEAR_SCAN(3, tty->print_cr("backward branch"));
 578     assert(is_visited(cur), "block must be visisted when block is active");
 579     assert(parent != NULL, "must have parent");
 580 
 581     cur->set(BlockBegin::linear_scan_loop_header_flag);
 582     cur->set(BlockBegin::backward_branch_target_flag);
 583 
 584     parent->set(BlockBegin::linear_scan_loop_end_flag);
 585 
 586     // When a loop header is also the start of an exception handler, then the backward branch is
 587     // an exception edge. Because such edges are usually critical edges which cannot be split, the
 588     // loop must be excluded here from processing.
 589     if (cur->is_set(BlockBegin::exception_entry_flag)) {
 590       // Make sure that dominators are correct in this weird situation
 591       _iterative_dominators = true;
 592       return;
 593     }
 594     assert(parent->number_of_sux() == 1 && parent->sux_at(0) == cur,
 595            "loop end blocks must have one successor (critical edges are split)");
 596 
 597     _loop_end_blocks.append(parent);
 598     return;
 599   }
 600 
 601   // increment number of incoming forward branches
 602   inc_forward_branches(cur);
 603 
 604   if (is_visited(cur)) {
 605     TRACE_LINEAR_SCAN(3, tty->print_cr("block already visited"));
 606     return;
 607   }
 608 
 609   _num_blocks++;
 610   set_visited(cur);
 611   set_active(cur);
 612 
 613   // recursive call for all successors
 614   int i;
 615   for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 616     count_edges(cur->sux_at(i), cur);
 617   }
 618   for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 619     count_edges(cur->exception_handler_at(i), cur);
 620   }
 621 
 622   clear_active(cur);
 623 
 624   // Each loop has a unique number.
 625   // When multiple loops are nested, assign_loop_depth assumes that the 
 626   // innermost loop has the lowest number. This is guaranteed by setting
 627   // the loop number after the recursive calls for the successors above
 628   // have returned.
 629   if (cur->is_set(BlockBegin::linear_scan_loop_header_flag)) {
 630     assert(cur->loop_index() == -1, "cannot set loop-index twice");
 631     TRACE_LINEAR_SCAN(3, tty->print_cr("Block B%d is loop header of loop %d", cur->block_id(), _num_loops));
 632 
 633     cur->set_loop_index(_num_loops);
 634     _num_loops++;
 635   }
 636 
 637   TRACE_LINEAR_SCAN(3, tty->print_cr("Finished count_edges for block B%d", cur->block_id()));
 638 }
 639 
 640 
 641 void ComputeLinearScanOrder::mark_loops() {
 642   TRACE_LINEAR_SCAN(3, tty->print_cr("----- marking loops"));
 643 
 644   _loop_map = BitMap2D(_num_loops, _max_block_id); 
 645   _loop_map.clear();
 646 
 647   for (int i = _loop_end_blocks.length() - 1; i >= 0; i--) {
 648     BlockBegin* loop_end   = _loop_end_blocks.at(i);
 649     BlockBegin* loop_start = loop_end->sux_at(0);
 650     int         loop_idx   = loop_start->loop_index();
 651 
 652     TRACE_LINEAR_SCAN(3, tty->print_cr("Processing loop from B%d to B%d (loop %d):", loop_start->block_id(), loop_end->block_id(), loop_idx));
 653     assert(loop_end->is_set(BlockBegin::linear_scan_loop_end_flag), "loop end flag must be set");
 654     assert(loop_end->number_of_sux() == 1, "incorrect number of successors");
 655     assert(loop_start->is_set(BlockBegin::linear_scan_loop_header_flag), "loop header flag must be set");
 656     assert(loop_idx >= 0 && loop_idx < _num_loops, "loop index not set");
 657     assert(_work_list.is_empty(), "work list must be empty before processing");
 658 
 659     // add the end-block of the loop to the working list
 660     _work_list.push(loop_end);
 661     set_block_in_loop(loop_idx, loop_end);
 662     do {
 663       BlockBegin* cur = _work_list.pop();
 664 
 665       TRACE_LINEAR_SCAN(3, tty->print_cr("    processing B%d", cur->block_id()));
 666       assert(is_block_in_loop(loop_idx, cur), "bit in loop map must be set when block is in work list");
 667 
 668       // recursive processing of all predecessors ends when start block of loop is reached
 669       if (cur != loop_start && !cur->is_set(BlockBegin::osr_entry_flag)) {
 670         for (int j = cur->number_of_preds() - 1; j >= 0; j--) {
 671           BlockBegin* pred = cur->pred_at(j);
 672 
 673           if (!is_block_in_loop(loop_idx, pred) /*&& !pred->is_set(BlockBeginosr_entry_flag)*/) {
 674             // this predecessor has not been processed yet, so add it to work list
 675             TRACE_LINEAR_SCAN(3, tty->print_cr("    pushing B%d", pred->block_id()));
 676             _work_list.push(pred);
 677             set_block_in_loop(loop_idx, pred);
 678           }
 679         }
 680       }
 681     } while (!_work_list.is_empty());
 682   }
 683 }
 684 
 685 
 686 // check for non-natural loops (loops where the loop header does not dominate
 687 // all other loop blocks = loops with mulitple entries).
 688 // such loops are ignored
 689 void ComputeLinearScanOrder::clear_non_natural_loops(BlockBegin* start_block) {
 690   for (int i = _num_loops - 1; i >= 0; i--) {
 691     if (is_block_in_loop(i, start_block)) {
 692       // loop i contains the entry block of the method
 693       // -> this is not a natural loop, so ignore it
 694       TRACE_LINEAR_SCAN(2, tty->print_cr("Loop %d is non-natural, so it is ignored", i));
 695 
 696       for (int block_id = _max_block_id - 1; block_id >= 0; block_id--) {
 697         clear_block_in_loop(i, block_id);
 698       }
 699       _iterative_dominators = true;
 700     }
 701   }
 702 }
 703 
 704 void ComputeLinearScanOrder::assign_loop_depth(BlockBegin* start_block) {
 705   TRACE_LINEAR_SCAN(3, "----- computing loop-depth and weight");
 706   init_visited();
 707 
 708   assert(_work_list.is_empty(), "work list must be empty before processing");
 709   _work_list.append(start_block);
 710 
 711   do {
 712     BlockBegin* cur = _work_list.pop();
 713 
 714     if (!is_visited(cur)) {
 715       set_visited(cur);
 716       TRACE_LINEAR_SCAN(4, tty->print_cr("Computing loop depth for block B%d", cur->block_id()));
 717 
 718       // compute loop-depth and loop-index for the block
 719       assert(cur->loop_depth() == 0, "cannot set loop-depth twice");
 720       int i;
 721       int loop_depth = 0;
 722       int min_loop_idx = -1;
 723       for (i = _num_loops - 1; i >= 0; i--) {
 724         if (is_block_in_loop(i, cur)) {
 725           loop_depth++;
 726           min_loop_idx = i;
 727         }
 728       } 
 729       cur->set_loop_depth(loop_depth);
 730       cur->set_loop_index(min_loop_idx);
 731   
 732       // append all unvisited successors to work list
 733       for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 734         _work_list.append(cur->sux_at(i));
 735       }
 736       for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 737         _work_list.append(cur->exception_handler_at(i));
 738       }
 739     } 
 740   } while (!_work_list.is_empty());
 741 }
 742 
 743 
 744 BlockBegin* ComputeLinearScanOrder::common_dominator(BlockBegin* a, BlockBegin* b) {
 745   assert(a != NULL && b != NULL, "must have input blocks");
 746 
 747   _dominator_blocks.clear();
 748   while (a != NULL) { 
 749     _dominator_blocks.set_bit(a->block_id()); 
 750     assert(a->dominator() != NULL || a == _linear_scan_order->at(0), "dominator must be initialized");
 751     a = a->dominator(); 
 752   }
 753   while (b != NULL && !_dominator_blocks.at(b->block_id())) {
 754     assert(b->dominator() != NULL || b == _linear_scan_order->at(0), "dominator must be initialized");
 755     b = b->dominator();
 756   }
 757 
 758   assert(b != NULL, "could not find dominator");
 759   return b;
 760 }
 761 
 762 void ComputeLinearScanOrder::compute_dominator(BlockBegin* cur, BlockBegin* parent) {
 763   if (cur->dominator() == NULL) {
 764     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: initializing dominator of B%d to B%d", cur->block_id(), parent->block_id()));
 765     cur->set_dominator(parent);
 766 
 767   } else if (!(cur->is_set(BlockBegin::linear_scan_loop_header_flag) && parent->is_set(BlockBegin::linear_scan_loop_end_flag))) {
 768     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: computing dominator of B%d: common dominator of B%d and B%d is B%d", cur->block_id(), parent->block_id(), cur->dominator()->block_id(), common_dominator(cur->dominator(), parent)->block_id()));
 769     assert(cur->number_of_preds() > 1, "");
 770     cur->set_dominator(common_dominator(cur->dominator(), parent));
 771   }
 772 }
 773 
 774 
 775 int ComputeLinearScanOrder::compute_weight(BlockBegin* cur) {
 776   BlockBegin* single_sux = NULL;
 777   if (cur->number_of_sux() == 1) {
 778     single_sux = cur->sux_at(0);
 779   }
 780 
 781   // limit loop-depth to 15 bit (only for security reason, it will never be so big)
 782   int weight = (cur->loop_depth() & 0x7FFF) << 16;
 783 
 784   // general macro for short definition of weight flags
 785   // the first instance of INC_WEIGHT_IF has the highest priority
 786   int cur_bit = 15;
 787   #define INC_WEIGHT_IF(condition) if ((condition)) { weight |= (1 << cur_bit); } cur_bit--;
 788 
 789   // this is necessery for the (very rare) case that two successing blocks have
 790   // the same loop depth, but a different loop index (can happen for endless loops
 791   // with exception handlers)
 792   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_header_flag));
 793 
 794   // loop end blocks (blocks that end with a backward branch) are added
 795   // after all other blocks of the loop.
 796   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_end_flag));
 797 
 798   // critical edge split blocks are prefered because than they have a bigger
 799   // proability to be completely empty
 800   INC_WEIGHT_IF(cur->is_set(BlockBegin::critical_edge_split_flag));
 801 
 802   // exceptions should not be thrown in normal control flow, so these blocks
 803   // are added as late as possible
 804   INC_WEIGHT_IF(cur->end()->as_Throw() == NULL  && (single_sux == NULL || single_sux->end()->as_Throw()  == NULL));
 805   INC_WEIGHT_IF(cur->end()->as_Return() == NULL && (single_sux == NULL || single_sux->end()->as_Return() == NULL));
 806 
 807   // exceptions handlers are added as late as possible
 808   INC_WEIGHT_IF(!cur->is_set(BlockBegin::exception_entry_flag));
 809   
 810   // guarantee that weight is > 0
 811   weight |= 1;
 812 
 813   #undef INC_WEIGHT_IF
 814   assert(cur_bit >= 0, "too many flags");
 815   assert(weight > 0, "weight cannot become negative");
 816 
 817   return weight;
 818 }
 819 
 820 bool ComputeLinearScanOrder::ready_for_processing(BlockBegin* cur) {
 821   // Discount the edge just traveled.
 822   // When the number drops to zero, all forward branches were processed 
 823   if (dec_forward_branches(cur) != 0) {
 824     return false;
 825   }
 826 
 827   assert(_linear_scan_order->index_of(cur) == -1, "block already processed (block can be ready only once)");
 828   assert(_work_list.index_of(cur) == -1, "block already in work-list (block can be ready only once)");
 829   return true;
 830 }
 831 
 832 void ComputeLinearScanOrder::sort_into_work_list(BlockBegin* cur) {
 833   assert(_work_list.index_of(cur) == -1, "block already in work list");
 834 
 835   int cur_weight = compute_weight(cur);
 836 
 837   // the linear_scan_number is used to cache the weight of a block
 838   cur->set_linear_scan_number(cur_weight);
 839 
 840 #ifndef PRODUCT
 841   if (StressLinearScan) {
 842     _work_list.insert_before(0, cur);
 843     return;
 844   }
 845 #endif
 846 
 847   _work_list.append(NULL); // provide space for new element
 848 
 849   int insert_idx = _work_list.length() - 1;
 850   while (insert_idx > 0 && _work_list.at(insert_idx - 1)->linear_scan_number() > cur_weight) {
 851     _work_list.at_put(insert_idx, _work_list.at(insert_idx - 1));
 852     insert_idx--;
 853   }
 854   _work_list.at_put(insert_idx, cur);
 855 
 856   TRACE_LINEAR_SCAN(3, tty->print_cr("Sorted B%d into worklist. new worklist:", cur->block_id()));
 857   TRACE_LINEAR_SCAN(3, for (int i = 0; i < _work_list.length(); i++) tty->print_cr("%8d B%2d  weight:%6x", i, _work_list.at(i)->block_id(), _work_list.at(i)->linear_scan_number()));
 858 
 859 #ifdef ASSERT
 860   for (int i = 0; i < _work_list.length(); i++) {
 861     assert(_work_list.at(i)->linear_scan_number() > 0, "weight not set");
 862     assert(i == 0 || _work_list.at(i - 1)->linear_scan_number() <= _work_list.at(i)->linear_scan_number(), "incorrect order in worklist");
 863   }
 864 #endif
 865 }
 866 
 867 void ComputeLinearScanOrder::append_block(BlockBegin* cur) {
 868   TRACE_LINEAR_SCAN(3, tty->print_cr("appending block B%d (weight 0x%6x) to linear-scan order", cur->block_id(), cur->linear_scan_number()));
 869   assert(_linear_scan_order->index_of(cur) == -1, "cannot add the same block twice");
 870 
 871   // currently, the linear scan order and code emit order are equal.
 872   // therefore the linear_scan_number and the weight of a block must also
 873   // be equal.
 874   cur->set_linear_scan_number(_linear_scan_order->length());
 875   _linear_scan_order->append(cur);
 876 }
 877 
 878 void ComputeLinearScanOrder::compute_order(BlockBegin* start_block) {
 879   TRACE_LINEAR_SCAN(3, "----- computing final block order");
 880 
 881   // the start block is always the first block in the linear scan order
 882   _linear_scan_order = new BlockList(_num_blocks);
 883   append_block(start_block);
 884 
 885   assert(start_block->end()->as_Base() != NULL, "start block must end with Base-instruction");
 886   BlockBegin* std_entry = ((Base*)start_block->end())->std_entry();
 887   BlockBegin* osr_entry = ((Base*)start_block->end())->osr_entry();
 888 
 889   BlockBegin* sux_of_osr_entry = NULL;
 890   if (osr_entry != NULL) {
 891     // special handling for osr entry:
 892     // ignore the edge between the osr entry and its successor for processing
 893     // the osr entry block is added manually below
 894     assert(osr_entry->number_of_sux() == 1, "osr entry must have exactly one successor");
 895     assert(osr_entry->sux_at(0)->number_of_preds() >= 2, "sucessor of osr entry must have two predecessors (otherwise it is not present in normal control flow");
 896 
 897     sux_of_osr_entry = osr_entry->sux_at(0);
 898     dec_forward_branches(sux_of_osr_entry);
 899 
 900     compute_dominator(osr_entry, start_block);
 901     _iterative_dominators = true;
 902   }
 903   compute_dominator(std_entry, start_block);
 904 
 905   // start processing with standard entry block
 906   assert(_work_list.is_empty(), "list must be empty before processing");
 907 
 908   if (ready_for_processing(std_entry)) {
 909     sort_into_work_list(std_entry);
 910   } else {
 911     assert(false, "the std_entry must be ready for processing (otherwise, the method has no start block)");
 912   }
 913 
 914   do {
 915     BlockBegin* cur = _work_list.pop();
 916 
 917     if (cur == sux_of_osr_entry) {
 918       // the osr entry block is ignored in normal processing, it is never added to the 
 919       // work list. Instead, it is added as late as possible manually here.
 920       append_block(osr_entry);
 921       compute_dominator(cur, osr_entry);
 922     }
 923     append_block(cur);
 924 
 925     int i;
 926     int num_sux = cur->number_of_sux();
 927     // changed loop order to get "intuitive" order of if- and else-blocks
 928     for (i = 0; i < num_sux; i++) {
 929       BlockBegin* sux = cur->sux_at(i);
 930       compute_dominator(sux, cur);
 931       if (ready_for_processing(sux)) {
 932         sort_into_work_list(sux);
 933       }
 934     }
 935     num_sux = cur->number_of_exception_handlers();
 936     for (i = 0; i < num_sux; i++) {
 937       BlockBegin* sux = cur->exception_handler_at(i);
 938       compute_dominator(sux, cur);
 939       if (ready_for_processing(sux)) {
 940         sort_into_work_list(sux);
 941       }
 942     }
 943   } while (_work_list.length() > 0);
 944 }
 945 
 946 
 947 bool ComputeLinearScanOrder::compute_dominators_iter() {
 948   bool changed = false;
 949   int num_blocks = _linear_scan_order->length();
 950 
 951   assert(_linear_scan_order->at(0)->dominator() == NULL, "must not have dominator");
 952   assert(_linear_scan_order->at(0)->number_of_preds() == 0, "must not have predecessors");
 953   for (int i = 1; i < num_blocks; i++) {
 954     BlockBegin* block = _linear_scan_order->at(i);
 955 
 956     BlockBegin* dominator = block->pred_at(0);
 957     int num_preds = block->number_of_preds();
 958     for (int i = 1; i < num_preds; i++) {
 959       dominator = common_dominator(dominator, block->pred_at(i));
 960     }
 961 
 962     if (dominator != block->dominator()) {
 963       TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: updating dominator of B%d from B%d to B%d", block->block_id(), block->dominator()->block_id(), dominator->block_id()));
 964 
 965       block->set_dominator(dominator);
 966       changed = true;
 967     }
 968   }
 969   return changed;
 970 }
 971 
 972 void ComputeLinearScanOrder::compute_dominators() {
 973   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing dominators (iterative computation reqired: %d)", _iterative_dominators));
 974 
 975   // iterative computation of dominators is only required for methods with non-natural loops
 976   // and OSR-methods. For all other methods, the dominators computed when generating the 
 977   // linear scan block order are correct.
 978   if (_iterative_dominators) {
 979     do {
 980       TRACE_LINEAR_SCAN(1, tty->print_cr("DOM: next iteration of fix-point calculation"));
 981     } while (compute_dominators_iter());
 982   }
 983 
 984   // check that dominators are correct
 985   assert(!compute_dominators_iter(), "fix point not reached");
 986 }
 987 
 988 
 989 #ifndef PRODUCT
 990 void ComputeLinearScanOrder::print_blocks() {
 991   if (TraceLinearScanLevel >= 2) {
 992     tty->print_cr("----- loop information:");
 993     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
 994       BlockBegin* cur = _linear_scan_order->at(block_idx);
 995   
 996       tty->print("%4d: B%2d: ", cur->linear_scan_number(), cur->block_id());
 997       for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
 998         tty->print ("%d ", is_block_in_loop(loop_idx, cur));
 999       }
1000       tty->print_cr(" -> loop_index: %2d, loop_depth: %2d", cur->loop_index(), cur->loop_depth());
1001     }
1002   }
1003 
1004   if (TraceLinearScanLevel >= 1) {
1005     tty->print_cr("----- linear-scan block order:");
1006     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
1007       BlockBegin* cur = _linear_scan_order->at(block_idx);
1008       tty->print("%4d: B%2d    loop: %2d  depth: %2d", cur->linear_scan_number(), cur->block_id(), cur->loop_index(), cur->loop_depth());
1009 
1010       tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
1011       tty->print(cur->is_set(BlockBegin::critical_edge_split_flag)     ? " ce" : "   ");
1012       tty->print(cur->is_set(BlockBegin::linear_scan_loop_header_flag) ? " lh" : "   ");
1013       tty->print(cur->is_set(BlockBegin::linear_scan_loop_end_flag)    ? " le" : "   ");
1014 
1015       if (cur->dominator() != NULL) {
1016         tty->print("    dom: B%d ", cur->dominator()->block_id());
1017       } else {
1018         tty->print("    dom: NULL ");
1019       }
1020 
1021       if (cur->number_of_preds() > 0) {
1022         tty->print("    preds: ");
1023         for (int j = 0; j < cur->number_of_preds(); j++) {
1024           BlockBegin* pred = cur->pred_at(j);
1025           tty->print("B%d ", pred->block_id());
1026         }
1027       }
1028       if (cur->number_of_sux() > 0) {
1029         tty->print("    sux: ");
1030         for (int j = 0; j < cur->number_of_sux(); j++) {
1031           BlockBegin* sux = cur->sux_at(j);
1032           tty->print("B%d ", sux->block_id());
1033         }
1034       }
1035       if (cur->number_of_exception_handlers() > 0) {
1036         tty->print("    ex: ");
1037         for (int j = 0; j < cur->number_of_exception_handlers(); j++) {
1038           BlockBegin* ex = cur->exception_handler_at(j);
1039           tty->print("B%d ", ex->block_id());
1040         }
1041       }
1042       tty->cr();
1043     }
1044   }
1045 }
1046 #endif
1047 
1048 #ifdef ASSERT
1049 void ComputeLinearScanOrder::verify() {
1050   assert(_linear_scan_order->length() == _num_blocks, "wrong number of blocks in list");
1051 
1052   if (StressLinearScan) {
1053     // blocks are scrambled when StressLinearScan is used
1054     return;
1055   }
1056 
1057   // check that all successors of a block have a higher linear-scan-number
1058   // and that all predecessors of a block have a lower linear-scan-number
1059   // (only backward branches of loops are ignored)
1060   int i;
1061   for (i = 0; i < _linear_scan_order->length(); i++) {
1062     BlockBegin* cur = _linear_scan_order->at(i);
1063 
1064     assert(cur->linear_scan_number() == i, "incorrect linear_scan_number");
1065     assert(cur->linear_scan_number() >= 0 && cur->linear_scan_number() == _linear_scan_order->index_of(cur), "incorrect linear_scan_number");
1066 
1067     int j;
1068     for (j = cur->number_of_sux() - 1; j >= 0; j--) {
1069       BlockBegin* sux = cur->sux_at(j);
1070       
1071       assert(sux->linear_scan_number() >= 0 && sux->linear_scan_number() == _linear_scan_order->index_of(sux), "incorrect linear_scan_number");
1072       if (!cur->is_set(BlockBegin::linear_scan_loop_end_flag)) {
1073         assert(cur->linear_scan_number() < sux->linear_scan_number(), "invalid order");
1074       }
1075       if (cur->loop_depth() == sux->loop_depth()) {
1076         assert(cur->loop_index() == sux->loop_index() || sux->is_set(BlockBegin::linear_scan_loop_header_flag), "successing blocks with same loop depth must have same loop index");
1077       }
1078     }
1079 
1080     for (j = cur->number_of_preds() - 1; j >= 0; j--) {
1081       BlockBegin* pred = cur->pred_at(j);
1082 
1083       assert(pred->linear_scan_number() >= 0 && pred->linear_scan_number() == _linear_scan_order->index_of(pred), "incorrect linear_scan_number");
1084       if (!cur->is_set(BlockBegin::linear_scan_loop_header_flag)) {
1085         assert(cur->linear_scan_number() > pred->linear_scan_number(), "invalid order");
1086       }
1087       if (cur->loop_depth() == pred->loop_depth()) {
1088         assert(cur->loop_index() == pred->loop_index() || cur->is_set(BlockBegin::linear_scan_loop_header_flag), "successing blocks with same loop depth must have same loop index");
1089       }
1090 
1091       assert(cur->dominator()->linear_scan_number() <= cur->pred_at(j)->linear_scan_number(), "dominator must be before predecessors");
1092     }
1093 
1094     // check dominator
1095     if (i == 0) {
1096       assert(cur->dominator() == NULL, "first block has no dominator");
1097     } else {
1098       assert(cur->dominator() != NULL, "all but first block must have dominator");
1099     }
1100     assert(cur->number_of_preds() != 1 || cur->dominator() == cur->pred_at(0), "Single predecessor must also be dominator");
1101   }
1102 
1103   // check that all loops are continuous
1104   for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
1105     int block_idx = 0;
1106     assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "the first block must not be present in any loop");
1107 
1108     // skip blocks before the loop
1109     while (block_idx < _num_blocks && !is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1110       block_idx++;
1111     }
1112     // skip blocks of loop
1113     while (block_idx < _num_blocks && is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1114       block_idx++;
1115     }
1116     // after the first non-loop block, there must not be another loop-block
1117     while (block_idx < _num_blocks) {
1118       assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "loop not continuous in linear-scan order");
1119       block_idx++;
1120     }
1121   }
1122 }
1123 #endif
1124 
1125 
1126 void IR::compute_code() {
1127   assert(is_valid(), "IR must be valid");
1128 
1129   ComputeLinearScanOrder compute_order(start());
1130   _num_loops = compute_order.num_loops();
1131   _code = compute_order.linear_scan_order();
1132 }
1133 
1134 
1135 void IR::compute_use_counts() {
1136   // make sure all values coming out of this block get evaluated.
1137   int num_blocks = _code->length();
1138   for (int i = 0; i < num_blocks; i++) {
1139     _code->at(i)->end()->state()->pin_stack_for_linear_scan();
1140   }
1141 
1142   // compute use counts
1143   UseCountComputer::compute(_code);
1144 }
1145 
1146 
1147 void IR::iterate_preorder(BlockClosure* closure) {
1148   assert(is_valid(), "IR must be valid");
1149   start()->iterate_preorder(closure);
1150 }
1151 
1152 
1153 void IR::iterate_postorder(BlockClosure* closure) {
1154   assert(is_valid(), "IR must be valid");
1155   start()->iterate_postorder(closure);
1156 }
1157 
1158 void IR::iterate_linear_scan_order(BlockClosure* closure) {
1159   linear_scan_order()->iterate_forward(closure);
1160 }
1161 
1162 
1163 #ifndef PRODUCT
1164 class BlockPrinter: public BlockClosure {
1165  private:
1166   InstructionPrinter* _ip;
1167   bool                _cfg_only;
1168   bool                _live_only;
1169 
1170  public:
1171   BlockPrinter(InstructionPrinter* ip, bool cfg_only, bool live_only = false) {
1172     _ip       = ip;
1173     _cfg_only = cfg_only;
1174     _live_only = live_only;
1175   }
1176 
1177   virtual void block_do(BlockBegin* block) {
1178     if (_cfg_only) {
1179       _ip->print_instr(block); tty->cr();
1180     } else {
1181       block->print_block(*_ip, _live_only);
1182     }
1183   }
1184 };
1185 
1186 
1187 void IR::print(BlockBegin* start, bool cfg_only, bool live_only) {
1188   ttyLocker ttyl;
1189   InstructionPrinter ip(!cfg_only);
1190   BlockPrinter bp(&ip, cfg_only, live_only);
1191   start->iterate_preorder(&bp);
1192   tty->cr();
1193 }
1194 
1195 void IR::print(bool cfg_only, bool live_only) {
1196   if (is_valid()) {
1197     print(start(), cfg_only, live_only);
1198   } else {
1199     tty->print_cr("invalid IR");
1200   }
1201 }
1202 
1203 
1204 define_array(BlockListArray, BlockList*)
1205 define_stack(BlockListList, BlockListArray)
1206 
1207 class PredecessorValidator : public BlockClosure {
1208  private:
1209   BlockListList* _predecessors;
1210   BlockList*     _blocks;
1211 
1212   static int cmp(BlockBegin** a, BlockBegin** b) {
1213     return (*a)->block_id() - (*b)->block_id();
1214   }
1215 
1216  public:
1217   PredecessorValidator(IR* hir) {
1218     ResourceMark rm;
1219     _predecessors = new BlockListList(BlockBegin::number_of_blocks(), NULL);
1220     _blocks = new BlockList();
1221 
1222     int i;
1223     hir->start()->iterate_preorder(this);
1224     if (hir->code() != NULL) {
1225       assert(hir->code()->length() == _blocks->length(), "must match");
1226       for (i = 0; i < _blocks->length(); i++) {
1227         assert(hir->code()->contains(_blocks->at(i)), "should be in both lists");
1228       }
1229     }
1230 
1231     for (i = 0; i < _blocks->length(); i++) {
1232       BlockBegin* block = _blocks->at(i);
1233       BlockList* preds = _predecessors->at(block->block_id());
1234       if (preds == NULL) {
1235         assert(block->number_of_preds() == 0, "should be the same");
1236         continue;
1237       }
1238 
1239       // clone the pred list so we can mutate it
1240       BlockList* pred_copy = new BlockList();
1241       int j;
1242       for (j = 0; j < block->number_of_preds(); j++) {
1243         pred_copy->append(block->pred_at(j));
1244       }
1245       // sort them in the same order
1246       preds->sort(cmp);
1247       pred_copy->sort(cmp);
1248       int length = MIN2(preds->length(), block->number_of_preds());
1249       for (j = 0; j < block->number_of_preds(); j++) {
1250         assert(preds->at(j) == pred_copy->at(j), "must match");
1251       }
1252 
1253       assert(preds->length() == block->number_of_preds(), "should be the same");
1254     }
1255   }
1256   
1257   virtual void block_do(BlockBegin* block) {
1258     _blocks->append(block);
1259     BlockEnd* be = block->end();
1260     int n = be->number_of_sux();
1261     int i;
1262     for (i = 0; i < n; i++) {
1263       BlockBegin* sux = be->sux_at(i);
1264       assert(!sux->is_set(BlockBegin::exception_entry_flag), "must not be xhandler");
1265       
1266       BlockList* preds = _predecessors->at_grow(sux->block_id(), NULL);
1267       if (preds == NULL) {
1268         preds = new BlockList();
1269         _predecessors->at_put(sux->block_id(), preds);
1270       }
1271       preds->append(block);
1272     }
1273 
1274     n = block->number_of_exception_handlers();
1275     for (i = 0; i < n; i++) {
1276       BlockBegin* sux = block->exception_handler_at(i);
1277       assert(sux->is_set(BlockBegin::exception_entry_flag), "must be xhandler");
1278 
1279       BlockList* preds = _predecessors->at_grow(sux->block_id(), NULL);
1280       if (preds == NULL) {
1281         preds = new BlockList();
1282         _predecessors->at_put(sux->block_id(), preds);
1283       }
1284       preds->append(block);
1285     }
1286   }
1287 };
1288 
1289 void IR::verify() {
1290 #ifdef ASSERT
1291   PredecessorValidator pv(this);
1292 #endif
1293 }
1294 
1295 #endif // PRODUCT
1296 
1297 void SubstitutionResolver::substitute(Value* v) {
1298   Value v0 = *v;
1299   if (v0) {
1300     Value vs = v0->subst();
1301     if (vs != v0) {
1302       *v = v0->subst();
1303     }
1304   }
1305 }
1306 
1307 #ifdef ASSERT
1308 void check_substitute(Value* v) {
1309   Value v0 = *v;
1310   if (v0) {
1311     Value vs = v0->subst();
1312     assert(vs == v0, "missed substitution");
1313   }
1314 }
1315 #endif
1316 
1317 
1318 void SubstitutionResolver::block_do(BlockBegin* block) {
1319   Instruction* last = NULL;
1320   for (Instruction* n = block; n != NULL;) {
1321     n->values_do(substitute);
1322     // need to remove this instruction from the instruction stream
1323     if (n->subst() != n) {
1324       assert(last != NULL, "must have last");
1325       last->set_next(n->next(), n->next()->bci());
1326     } else {
1327       last = n;
1328     }
1329     n = last->next();
1330   }
1331 
1332 #ifdef ASSERT
1333   if (block->state()) block->state()->values_do(check_substitute);
1334   block->block_values_do(check_substitute); 
1335   if (block->end() && block->end()->state()) block->end()->state()->values_do(check_substitute);
1336 #endif
1337 }