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