1 /*
   2  * Copyright (c) 1998, 2014, 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 "asm/assembler.inline.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/debugInfo.hpp"
  29 #include "code/debugInfoRec.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "compiler/compilerDirectives.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "opto/ad.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/locknode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/optoreg.hpp"
  40 #include "opto/output.hpp"
  41 #include "opto/regalloc.hpp"
  42 #include "opto/runtime.hpp"
  43 #include "opto/subnode.hpp"
  44 #include "opto/type.hpp"
  45 #include "runtime/handles.inline.hpp"
  46 #include "utilities/xmlstream.hpp"
  47 
  48 #ifndef PRODUCT
  49 #define DEBUG_ARG(x) , x
  50 #else
  51 #define DEBUG_ARG(x)
  52 #endif
  53 
  54 // Convert Nodes to instruction bits and pass off to the VM
  55 void Compile::Output() {
  56   // RootNode goes
  57   assert( _cfg->get_root_block()->number_of_nodes() == 0, "" );
  58 
  59   // The number of new nodes (mostly MachNop) is proportional to
  60   // the number of java calls and inner loops which are aligned.
  61   if ( C->check_node_count((NodeLimitFudgeFactor + C->java_calls()*3 +
  62                             C->inner_loops()*(OptoLoopAlignment-1)),
  63                            "out of nodes before code generation" ) ) {
  64     return;
  65   }
  66   // Make sure I can find the Start Node
  67   Block *entry = _cfg->get_block(1);
  68   Block *broot = _cfg->get_root_block();
  69 
  70   const StartNode *start = entry->head()->as_Start();
  71 
  72   // Replace StartNode with prolog
  73   MachPrologNode *prolog = new MachPrologNode();
  74   entry->map_node(prolog, 0);
  75   _cfg->map_node_to_block(prolog, entry);
  76   _cfg->unmap_node_from_block(start); // start is no longer in any block
  77 
  78   // Virtual methods need an unverified entry point
  79 
  80   if( is_osr_compilation() ) {
  81     if( PoisonOSREntry ) {
  82       // TODO: Should use a ShouldNotReachHereNode...
  83       _cfg->insert( broot, 0, new MachBreakpointNode() );
  84     }
  85   } else {
  86     if( _method && !_method->flags().is_static() ) {
  87       // Insert unvalidated entry point
  88       _cfg->insert( broot, 0, new MachUEPNode() );
  89     }
  90 
  91   }
  92 
  93   // Break before main entry point
  94   if( (_method && C->env()->dirset()->BreakAtExecuteOption)
  95 #ifndef PRODUCT
  96     ||(OptoBreakpoint && is_method_compilation())
  97     ||(OptoBreakpointOSR && is_osr_compilation())
  98     ||(OptoBreakpointC2R && !_method)
  99 #endif
 100     ) {
 101     // checking for _method means that OptoBreakpoint does not apply to
 102     // runtime stubs or frame converters
 103     _cfg->insert( entry, 1, new MachBreakpointNode() );
 104   }
 105 
 106   // Insert epilogs before every return
 107   for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
 108     Block* block = _cfg->get_block(i);
 109     if (!block->is_connector() && block->non_connector_successor(0) == _cfg->get_root_block()) { // Found a program exit point?
 110       Node* m = block->end();
 111       if (m->is_Mach() && m->as_Mach()->ideal_Opcode() != Op_Halt) {
 112         MachEpilogNode* epilog = new MachEpilogNode(m->as_Mach()->ideal_Opcode() == Op_Return);
 113         block->add_inst(epilog);
 114         _cfg->map_node_to_block(epilog, block);
 115       }
 116     }
 117   }
 118 
 119   uint* blk_starts = NEW_RESOURCE_ARRAY(uint, _cfg->number_of_blocks() + 1);
 120   blk_starts[0] = 0;
 121 
 122   // Initialize code buffer and process short branches.
 123   CodeBuffer* cb = init_buffer(blk_starts);
 124 
 125   if (cb == NULL || failing()) {
 126     return;
 127   }
 128 
 129   ScheduleAndBundle();
 130 
 131 #ifndef PRODUCT
 132   if (trace_opto_output()) {
 133     tty->print("\n---- After ScheduleAndBundle ----\n");
 134     for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
 135       tty->print("\nBB#%03d:\n", i);
 136       Block* block = _cfg->get_block(i);
 137       for (uint j = 0; j < block->number_of_nodes(); j++) {
 138         Node* n = block->get_node(j);
 139         OptoReg::Name reg = _regalloc->get_reg_first(n);
 140         tty->print(" %-6s ", reg >= 0 && reg < REG_COUNT ? Matcher::regName[reg] : "");
 141         n->dump();
 142       }
 143     }
 144   }
 145 #endif
 146 
 147   if (failing()) {
 148     return;
 149   }
 150 
 151   BuildOopMaps();
 152 
 153   if (failing())  {
 154     return;
 155   }
 156 
 157   fill_buffer(cb, blk_starts);
 158 }
 159 
 160 bool Compile::need_stack_bang(int frame_size_in_bytes) const {
 161   // Determine if we need to generate a stack overflow check.
 162   // Do it if the method is not a stub function and
 163   // has java calls or has frame size > vm_page_size/8.
 164   // The debug VM checks that deoptimization doesn't trigger an
 165   // unexpected stack overflow (compiled method stack banging should
 166   // guarantee it doesn't happen) so we always need the stack bang in
 167   // a debug VM.
 168   return (UseStackBanging && stub_function() == NULL &&
 169           (has_java_calls() || frame_size_in_bytes > os::vm_page_size()>>3
 170            DEBUG_ONLY(|| true)));
 171 }
 172 
 173 bool Compile::need_register_stack_bang() const {
 174   // Determine if we need to generate a register stack overflow check.
 175   // This is only used on architectures which have split register
 176   // and memory stacks (ie. IA64).
 177   // Bang if the method is not a stub function and has java calls
 178   return (stub_function() == NULL && has_java_calls());
 179 }
 180 
 181 
 182 // Compute the size of first NumberOfLoopInstrToAlign instructions at the top
 183 // of a loop. When aligning a loop we need to provide enough instructions
 184 // in cpu's fetch buffer to feed decoders. The loop alignment could be
 185 // avoided if we have enough instructions in fetch buffer at the head of a loop.
 186 // By default, the size is set to 999999 by Block's constructor so that
 187 // a loop will be aligned if the size is not reset here.
 188 //
 189 // Note: Mach instructions could contain several HW instructions
 190 // so the size is estimated only.
 191 //
 192 void Compile::compute_loop_first_inst_sizes() {
 193   // The next condition is used to gate the loop alignment optimization.
 194   // Don't aligned a loop if there are enough instructions at the head of a loop
 195   // or alignment padding is larger then MaxLoopPad. By default, MaxLoopPad
 196   // is equal to OptoLoopAlignment-1 except on new Intel cpus, where it is
 197   // equal to 11 bytes which is the largest address NOP instruction.
 198   if (MaxLoopPad < OptoLoopAlignment - 1) {
 199     uint last_block = _cfg->number_of_blocks() - 1;
 200     for (uint i = 1; i <= last_block; i++) {
 201       Block* block = _cfg->get_block(i);
 202       // Check the first loop's block which requires an alignment.
 203       if (block->loop_alignment() > (uint)relocInfo::addr_unit()) {
 204         uint sum_size = 0;
 205         uint inst_cnt = NumberOfLoopInstrToAlign;
 206         inst_cnt = block->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
 207 
 208         // Check subsequent fallthrough blocks if the loop's first
 209         // block(s) does not have enough instructions.
 210         Block *nb = block;
 211         while(inst_cnt > 0 &&
 212               i < last_block &&
 213               !_cfg->get_block(i + 1)->has_loop_alignment() &&
 214               !nb->has_successor(block)) {
 215           i++;
 216           nb = _cfg->get_block(i);
 217           inst_cnt  = nb->compute_first_inst_size(sum_size, inst_cnt, _regalloc);
 218         } // while( inst_cnt > 0 && i < last_block  )
 219 
 220         block->set_first_inst_size(sum_size);
 221       } // f( b->head()->is_Loop() )
 222     } // for( i <= last_block )
 223   } // if( MaxLoopPad < OptoLoopAlignment-1 )
 224 }
 225 
 226 // The architecture description provides short branch variants for some long
 227 // branch instructions. Replace eligible long branches with short branches.
 228 void Compile::shorten_branches(uint* blk_starts, int& code_size, int& reloc_size, int& stub_size) {
 229   // Compute size of each block, method size, and relocation information size
 230   uint nblocks  = _cfg->number_of_blocks();
 231 
 232   uint*      jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
 233   uint*      jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
 234   int*       jmp_nidx   = NEW_RESOURCE_ARRAY(int ,nblocks);
 235 
 236   // Collect worst case block paddings
 237   int* block_worst_case_pad = NEW_RESOURCE_ARRAY(int, nblocks);
 238   memset(block_worst_case_pad, 0, nblocks * sizeof(int));
 239 
 240   DEBUG_ONLY( uint *jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks); )
 241   DEBUG_ONLY( uint *jmp_rule = NEW_RESOURCE_ARRAY(uint,nblocks); )
 242 
 243   bool has_short_branch_candidate = false;
 244 
 245   // Initialize the sizes to 0
 246   code_size  = 0;          // Size in bytes of generated code
 247   stub_size  = 0;          // Size in bytes of all stub entries
 248   // Size in bytes of all relocation entries, including those in local stubs.
 249   // Start with 2-bytes of reloc info for the unvalidated entry point
 250   reloc_size = 1;          // Number of relocation entries
 251 
 252   // Make three passes.  The first computes pessimistic blk_starts,
 253   // relative jmp_offset and reloc_size information.  The second performs
 254   // short branch substitution using the pessimistic sizing.  The
 255   // third inserts nops where needed.
 256 
 257   // Step one, perform a pessimistic sizing pass.
 258   uint last_call_adr = max_juint;
 259   uint last_avoid_back_to_back_adr = max_juint;
 260   uint nop_size = (new MachNopNode())->size(_regalloc);
 261   for (uint i = 0; i < nblocks; i++) { // For all blocks
 262     Block* block = _cfg->get_block(i);
 263 
 264     // During short branch replacement, we store the relative (to blk_starts)
 265     // offset of jump in jmp_offset, rather than the absolute offset of jump.
 266     // This is so that we do not need to recompute sizes of all nodes when
 267     // we compute correct blk_starts in our next sizing pass.
 268     jmp_offset[i] = 0;
 269     jmp_size[i]   = 0;
 270     jmp_nidx[i]   = -1;
 271     DEBUG_ONLY( jmp_target[i] = 0; )
 272     DEBUG_ONLY( jmp_rule[i]   = 0; )
 273 
 274     // Sum all instruction sizes to compute block size
 275     uint last_inst = block->number_of_nodes();
 276     uint blk_size = 0;
 277     for (uint j = 0; j < last_inst; j++) {
 278       Node* nj = block->get_node(j);
 279       // Handle machine instruction nodes
 280       if (nj->is_Mach()) {
 281         MachNode *mach = nj->as_Mach();
 282         blk_size += (mach->alignment_required() - 1) * relocInfo::addr_unit(); // assume worst case padding
 283         reloc_size += mach->reloc();
 284         if (mach->is_MachCall()) {
 285           // add size information for trampoline stub
 286           // class CallStubImpl is platform-specific and defined in the *.ad files.
 287           stub_size  += CallStubImpl::size_call_trampoline();
 288           reloc_size += CallStubImpl::reloc_call_trampoline();
 289 
 290           MachCallNode *mcall = mach->as_MachCall();
 291           // This destination address is NOT PC-relative
 292 
 293           mcall->method_set((intptr_t)mcall->entry_point());
 294 
 295           if (mcall->is_MachCallJava() && mcall->as_MachCallJava()->_method) {
 296             stub_size  += CompiledStaticCall::to_interp_stub_size();
 297             reloc_size += CompiledStaticCall::reloc_to_interp_stub();
 298           }
 299         } else if (mach->is_MachSafePoint()) {
 300           // If call/safepoint are adjacent, account for possible
 301           // nop to disambiguate the two safepoints.
 302           // ScheduleAndBundle() can rearrange nodes in a block,
 303           // check for all offsets inside this block.
 304           if (last_call_adr >= blk_starts[i]) {
 305             blk_size += nop_size;
 306           }
 307         }
 308         if (mach->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
 309           // Nop is inserted between "avoid back to back" instructions.
 310           // ScheduleAndBundle() can rearrange nodes in a block,
 311           // check for all offsets inside this block.
 312           if (last_avoid_back_to_back_adr >= blk_starts[i]) {
 313             blk_size += nop_size;
 314           }
 315         }
 316         if (mach->may_be_short_branch()) {
 317           if (!nj->is_MachBranch()) {
 318 #ifndef PRODUCT
 319             nj->dump(3);
 320 #endif
 321             Unimplemented();
 322           }
 323           assert(jmp_nidx[i] == -1, "block should have only one branch");
 324           jmp_offset[i] = blk_size;
 325           jmp_size[i]   = nj->size(_regalloc);
 326           jmp_nidx[i]   = j;
 327           has_short_branch_candidate = true;
 328         }
 329       }
 330       blk_size += nj->size(_regalloc);
 331       // Remember end of call offset
 332       if (nj->is_MachCall() && !nj->is_MachCallLeaf()) {
 333         last_call_adr = blk_starts[i]+blk_size;
 334       }
 335       // Remember end of avoid_back_to_back offset
 336       if (nj->is_Mach() && nj->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
 337         last_avoid_back_to_back_adr = blk_starts[i]+blk_size;
 338       }
 339     }
 340 
 341     // When the next block starts a loop, we may insert pad NOP
 342     // instructions.  Since we cannot know our future alignment,
 343     // assume the worst.
 344     if (i < nblocks - 1) {
 345       Block* nb = _cfg->get_block(i + 1);
 346       int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
 347       if (max_loop_pad > 0) {
 348         assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
 349         // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
 350         // If either is the last instruction in this block, bump by
 351         // max_loop_pad in lock-step with blk_size, so sizing
 352         // calculations in subsequent blocks still can conservatively
 353         // detect that it may the last instruction in this block.
 354         if (last_call_adr == blk_starts[i]+blk_size) {
 355           last_call_adr += max_loop_pad;
 356         }
 357         if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
 358           last_avoid_back_to_back_adr += max_loop_pad;
 359         }
 360         blk_size += max_loop_pad;
 361         block_worst_case_pad[i + 1] = max_loop_pad;
 362       }
 363     }
 364 
 365     // Save block size; update total method size
 366     blk_starts[i+1] = blk_starts[i]+blk_size;
 367   }
 368 
 369   // Step two, replace eligible long jumps.
 370   bool progress = true;
 371   uint last_may_be_short_branch_adr = max_juint;
 372   while (has_short_branch_candidate && progress) {
 373     progress = false;
 374     has_short_branch_candidate = false;
 375     int adjust_block_start = 0;
 376     for (uint i = 0; i < nblocks; i++) {
 377       Block* block = _cfg->get_block(i);
 378       int idx = jmp_nidx[i];
 379       MachNode* mach = (idx == -1) ? NULL: block->get_node(idx)->as_Mach();
 380       if (mach != NULL && mach->may_be_short_branch()) {
 381 #ifdef ASSERT
 382         assert(jmp_size[i] > 0 && mach->is_MachBranch(), "sanity");
 383         int j;
 384         // Find the branch; ignore trailing NOPs.
 385         for (j = block->number_of_nodes()-1; j>=0; j--) {
 386           Node* n = block->get_node(j);
 387           if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con)
 388             break;
 389         }
 390         assert(j >= 0 && j == idx && block->get_node(j) == (Node*)mach, "sanity");
 391 #endif
 392         int br_size = jmp_size[i];
 393         int br_offs = blk_starts[i] + jmp_offset[i];
 394 
 395         // This requires the TRUE branch target be in succs[0]
 396         uint bnum = block->non_connector_successor(0)->_pre_order;
 397         int offset = blk_starts[bnum] - br_offs;
 398         if (bnum > i) { // adjust following block's offset
 399           offset -= adjust_block_start;
 400         }
 401 
 402         // This block can be a loop header, account for the padding
 403         // in the previous block.
 404         int block_padding = block_worst_case_pad[i];
 405         assert(i == 0 || block_padding == 0 || br_offs >= block_padding, "Should have at least a padding on top");
 406         // In the following code a nop could be inserted before
 407         // the branch which will increase the backward distance.
 408         bool needs_padding = ((uint)(br_offs - block_padding) == last_may_be_short_branch_adr);
 409         assert(!needs_padding || jmp_offset[i] == 0, "padding only branches at the beginning of block");
 410 
 411         if (needs_padding && offset <= 0)
 412           offset -= nop_size;
 413 
 414         if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
 415           // We've got a winner.  Replace this branch.
 416           MachNode* replacement = mach->as_MachBranch()->short_branch_version();
 417 
 418           // Update the jmp_size.
 419           int new_size = replacement->size(_regalloc);
 420           int diff     = br_size - new_size;
 421           assert(diff >= (int)nop_size, "short_branch size should be smaller");
 422           // Conservatively take into account padding between
 423           // avoid_back_to_back branches. Previous branch could be
 424           // converted into avoid_back_to_back branch during next
 425           // rounds.
 426           if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
 427             jmp_offset[i] += nop_size;
 428             diff -= nop_size;
 429           }
 430           adjust_block_start += diff;
 431           block->map_node(replacement, idx);
 432           mach->subsume_by(replacement, C);
 433           mach = replacement;
 434           progress = true;
 435 
 436           jmp_size[i] = new_size;
 437           DEBUG_ONLY( jmp_target[i] = bnum; );
 438           DEBUG_ONLY( jmp_rule[i] = mach->rule(); );
 439         } else {
 440           // The jump distance is not short, try again during next iteration.
 441           has_short_branch_candidate = true;
 442         }
 443       } // (mach->may_be_short_branch())
 444       if (mach != NULL && (mach->may_be_short_branch() ||
 445                            mach->avoid_back_to_back(MachNode::AVOID_AFTER))) {
 446         last_may_be_short_branch_adr = blk_starts[i] + jmp_offset[i] + jmp_size[i];
 447       }
 448       blk_starts[i+1] -= adjust_block_start;
 449     }
 450   }
 451 
 452 #ifdef ASSERT
 453   for (uint i = 0; i < nblocks; i++) { // For all blocks
 454     if (jmp_target[i] != 0) {
 455       int br_size = jmp_size[i];
 456       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
 457       if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
 458         tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
 459       }
 460       assert(_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset), "Displacement too large for short jmp");
 461     }
 462   }
 463 #endif
 464 
 465   // Step 3, compute the offsets of all blocks, will be done in fill_buffer()
 466   // after ScheduleAndBundle().
 467 
 468   // ------------------
 469   // Compute size for code buffer
 470   code_size = blk_starts[nblocks];
 471 
 472   // Relocation records
 473   reloc_size += 1;              // Relo entry for exception handler
 474 
 475   // Adjust reloc_size to number of record of relocation info
 476   // Min is 2 bytes, max is probably 6 or 8, with a tax up to 25% for
 477   // a relocation index.
 478   // The CodeBuffer will expand the locs array if this estimate is too low.
 479   reloc_size *= 10 / sizeof(relocInfo);
 480 }
 481 
 482 //------------------------------FillLocArray-----------------------------------
 483 // Create a bit of debug info and append it to the array.  The mapping is from
 484 // Java local or expression stack to constant, register or stack-slot.  For
 485 // doubles, insert 2 mappings and return 1 (to tell the caller that the next
 486 // entry has been taken care of and caller should skip it).
 487 static LocationValue *new_loc_value( PhaseRegAlloc *ra, OptoReg::Name regnum, Location::Type l_type ) {
 488   // This should never have accepted Bad before
 489   assert(OptoReg::is_valid(regnum), "location must be valid");
 490   return (OptoReg::is_reg(regnum))
 491     ? new LocationValue(Location::new_reg_loc(l_type, OptoReg::as_VMReg(regnum)) )
 492     : new LocationValue(Location::new_stk_loc(l_type,  ra->reg2offset(regnum)));
 493 }
 494 
 495 
 496 ObjectValue*
 497 Compile::sv_for_node_id(GrowableArray<ScopeValue*> *objs, int id) {
 498   for (int i = 0; i < objs->length(); i++) {
 499     assert(objs->at(i)->is_object(), "corrupt object cache");
 500     ObjectValue* sv = (ObjectValue*) objs->at(i);
 501     if (sv->id() == id) {
 502       return sv;
 503     }
 504   }
 505   // Otherwise..
 506   return NULL;
 507 }
 508 
 509 void Compile::set_sv_for_object_node(GrowableArray<ScopeValue*> *objs,
 510                                      ObjectValue* sv ) {
 511   assert(sv_for_node_id(objs, sv->id()) == NULL, "Precondition");
 512   objs->append(sv);
 513 }
 514 
 515 
 516 void Compile::FillLocArray( int idx, MachSafePointNode* sfpt, Node *local,
 517                             GrowableArray<ScopeValue*> *array,
 518                             GrowableArray<ScopeValue*> *objs ) {
 519   assert( local, "use _top instead of null" );
 520   if (array->length() != idx) {
 521     assert(array->length() == idx + 1, "Unexpected array count");
 522     // Old functionality:
 523     //   return
 524     // New functionality:
 525     //   Assert if the local is not top. In product mode let the new node
 526     //   override the old entry.
 527     assert(local == top(), "LocArray collision");
 528     if (local == top()) {
 529       return;
 530     }
 531     array->pop();
 532   }
 533   const Type *t = local->bottom_type();
 534 
 535   // Is it a safepoint scalar object node?
 536   if (local->is_SafePointScalarObject()) {
 537     SafePointScalarObjectNode* spobj = local->as_SafePointScalarObject();
 538 
 539     ObjectValue* sv = Compile::sv_for_node_id(objs, spobj->_idx);
 540     if (sv == NULL) {
 541       ciKlass* cik = t->is_oopptr()->klass();
 542       assert(cik->is_instance_klass() ||
 543              cik->is_array_klass(), "Not supported allocation.");
 544       sv = new ObjectValue(spobj->_idx,
 545                            new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
 546       Compile::set_sv_for_object_node(objs, sv);
 547 
 548       uint first_ind = spobj->first_index(sfpt->jvms());
 549       for (uint i = 0; i < spobj->n_fields(); i++) {
 550         Node* fld_node = sfpt->in(first_ind+i);
 551         (void)FillLocArray(sv->field_values()->length(), sfpt, fld_node, sv->field_values(), objs);
 552       }
 553     }
 554     array->append(sv);
 555     return;
 556   }
 557 
 558   // Grab the register number for the local
 559   OptoReg::Name regnum = _regalloc->get_reg_first(local);
 560   if( OptoReg::is_valid(regnum) ) {// Got a register/stack?
 561     // Record the double as two float registers.
 562     // The register mask for such a value always specifies two adjacent
 563     // float registers, with the lower register number even.
 564     // Normally, the allocation of high and low words to these registers
 565     // is irrelevant, because nearly all operations on register pairs
 566     // (e.g., StoreD) treat them as a single unit.
 567     // Here, we assume in addition that the words in these two registers
 568     // stored "naturally" (by operations like StoreD and double stores
 569     // within the interpreter) such that the lower-numbered register
 570     // is written to the lower memory address.  This may seem like
 571     // a machine dependency, but it is not--it is a requirement on
 572     // the author of the <arch>.ad file to ensure that, for every
 573     // even/odd double-register pair to which a double may be allocated,
 574     // the word in the even single-register is stored to the first
 575     // memory word.  (Note that register numbers are completely
 576     // arbitrary, and are not tied to any machine-level encodings.)
 577 #ifdef _LP64
 578     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon ) {
 579       array->append(new ConstantIntValue(0));
 580       array->append(new_loc_value( _regalloc, regnum, Location::dbl ));
 581     } else if ( t->base() == Type::Long ) {
 582       array->append(new ConstantIntValue(0));
 583       array->append(new_loc_value( _regalloc, regnum, Location::lng ));
 584     } else if ( t->base() == Type::RawPtr ) {
 585       // jsr/ret return address which must be restored into a the full
 586       // width 64-bit stack slot.
 587       array->append(new_loc_value( _regalloc, regnum, Location::lng ));
 588     }
 589 #else //_LP64
 590 #ifdef SPARC
 591     if (t->base() == Type::Long && OptoReg::is_reg(regnum)) {
 592       // For SPARC we have to swap high and low words for
 593       // long values stored in a single-register (g0-g7).
 594       array->append(new_loc_value( _regalloc,              regnum   , Location::normal ));
 595       array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
 596     } else
 597 #endif //SPARC
 598     if( t->base() == Type::DoubleBot || t->base() == Type::DoubleCon || t->base() == Type::Long ) {
 599       // Repack the double/long as two jints.
 600       // The convention the interpreter uses is that the second local
 601       // holds the first raw word of the native double representation.
 602       // This is actually reasonable, since locals and stack arrays
 603       // grow downwards in all implementations.
 604       // (If, on some machine, the interpreter's Java locals or stack
 605       // were to grow upwards, the embedded doubles would be word-swapped.)
 606       array->append(new_loc_value( _regalloc, OptoReg::add(regnum,1), Location::normal ));
 607       array->append(new_loc_value( _regalloc,              regnum   , Location::normal ));
 608     }
 609 #endif //_LP64
 610     else if( (t->base() == Type::FloatBot || t->base() == Type::FloatCon) &&
 611                OptoReg::is_reg(regnum) ) {
 612       array->append(new_loc_value( _regalloc, regnum, Matcher::float_in_double()
 613                                    ? Location::float_in_dbl : Location::normal ));
 614     } else if( t->base() == Type::Int && OptoReg::is_reg(regnum) ) {
 615       array->append(new_loc_value( _regalloc, regnum, Matcher::int_in_long
 616                                    ? Location::int_in_long : Location::normal ));
 617     } else if( t->base() == Type::NarrowOop ) {
 618       array->append(new_loc_value( _regalloc, regnum, Location::narrowoop ));
 619     } else {
 620       array->append(new_loc_value( _regalloc, regnum, _regalloc->is_oop(local) ? Location::oop : Location::normal ));
 621     }
 622     return;
 623   }
 624 
 625   // No register.  It must be constant data.
 626   switch (t->base()) {
 627   case Type::Half:              // Second half of a double
 628     ShouldNotReachHere();       // Caller should skip 2nd halves
 629     break;
 630   case Type::AnyPtr:
 631     array->append(new ConstantOopWriteValue(NULL));
 632     break;
 633   case Type::AryPtr:
 634   case Type::InstPtr:          // fall through
 635     array->append(new ConstantOopWriteValue(t->isa_oopptr()->const_oop()->constant_encoding()));
 636     break;
 637   case Type::NarrowOop:
 638     if (t == TypeNarrowOop::NULL_PTR) {
 639       array->append(new ConstantOopWriteValue(NULL));
 640     } else {
 641       array->append(new ConstantOopWriteValue(t->make_ptr()->isa_oopptr()->const_oop()->constant_encoding()));
 642     }
 643     break;
 644   case Type::Int:
 645     array->append(new ConstantIntValue(t->is_int()->get_con()));
 646     break;
 647   case Type::RawPtr:
 648     // A return address (T_ADDRESS).
 649     assert((intptr_t)t->is_ptr()->get_con() < (intptr_t)0x10000, "must be a valid BCI");
 650 #ifdef _LP64
 651     // Must be restored to the full-width 64-bit stack slot.
 652     array->append(new ConstantLongValue(t->is_ptr()->get_con()));
 653 #else
 654     array->append(new ConstantIntValue(t->is_ptr()->get_con()));
 655 #endif
 656     break;
 657   case Type::FloatCon: {
 658     float f = t->is_float_constant()->getf();
 659     array->append(new ConstantIntValue(jint_cast(f)));
 660     break;
 661   }
 662   case Type::DoubleCon: {
 663     jdouble d = t->is_double_constant()->getd();
 664 #ifdef _LP64
 665     array->append(new ConstantIntValue(0));
 666     array->append(new ConstantDoubleValue(d));
 667 #else
 668     // Repack the double as two jints.
 669     // The convention the interpreter uses is that the second local
 670     // holds the first raw word of the native double representation.
 671     // This is actually reasonable, since locals and stack arrays
 672     // grow downwards in all implementations.
 673     // (If, on some machine, the interpreter's Java locals or stack
 674     // were to grow upwards, the embedded doubles would be word-swapped.)
 675     jlong_accessor acc;
 676     acc.long_value = jlong_cast(d);
 677     array->append(new ConstantIntValue(acc.words[1]));
 678     array->append(new ConstantIntValue(acc.words[0]));
 679 #endif
 680     break;
 681   }
 682   case Type::Long: {
 683     jlong d = t->is_long()->get_con();
 684 #ifdef _LP64
 685     array->append(new ConstantIntValue(0));
 686     array->append(new ConstantLongValue(d));
 687 #else
 688     // Repack the long as two jints.
 689     // The convention the interpreter uses is that the second local
 690     // holds the first raw word of the native double representation.
 691     // This is actually reasonable, since locals and stack arrays
 692     // grow downwards in all implementations.
 693     // (If, on some machine, the interpreter's Java locals or stack
 694     // were to grow upwards, the embedded doubles would be word-swapped.)
 695     jlong_accessor acc;
 696     acc.long_value = d;
 697     array->append(new ConstantIntValue(acc.words[1]));
 698     array->append(new ConstantIntValue(acc.words[0]));
 699 #endif
 700     break;
 701   }
 702   case Type::Top:               // Add an illegal value here
 703     array->append(new LocationValue(Location()));
 704     break;
 705   default:
 706     ShouldNotReachHere();
 707     break;
 708   }
 709 }
 710 
 711 // Determine if this node starts a bundle
 712 bool Compile::starts_bundle(const Node *n) const {
 713   return (_node_bundling_limit > n->_idx &&
 714           _node_bundling_base[n->_idx].starts_bundle());
 715 }
 716 
 717 //--------------------------Process_OopMap_Node--------------------------------
 718 void Compile::Process_OopMap_Node(MachNode *mach, int current_offset) {
 719 
 720   // Handle special safepoint nodes for synchronization
 721   MachSafePointNode *sfn   = mach->as_MachSafePoint();
 722   MachCallNode      *mcall;
 723 
 724   int safepoint_pc_offset = current_offset;
 725   bool is_method_handle_invoke = false;
 726   bool return_oop = false;
 727 
 728   // Add the safepoint in the DebugInfoRecorder
 729   if( !mach->is_MachCall() ) {
 730     mcall = NULL;
 731     debug_info()->add_safepoint(safepoint_pc_offset, sfn->_oop_map);
 732   } else {
 733     mcall = mach->as_MachCall();
 734 
 735     // Is the call a MethodHandle call?
 736     if (mcall->is_MachCallJava()) {
 737       if (mcall->as_MachCallJava()->_method_handle_invoke) {
 738         assert(has_method_handle_invokes(), "must have been set during call generation");
 739         is_method_handle_invoke = true;
 740       }
 741     }
 742 
 743     // Check if a call returns an object.
 744     if (mcall->returns_pointer()) {
 745       return_oop = true;
 746     }
 747     safepoint_pc_offset += mcall->ret_addr_offset();
 748     debug_info()->add_safepoint(safepoint_pc_offset, mcall->_oop_map);
 749   }
 750 
 751   // Loop over the JVMState list to add scope information
 752   // Do not skip safepoints with a NULL method, they need monitor info
 753   JVMState* youngest_jvms = sfn->jvms();
 754   int max_depth = youngest_jvms->depth();
 755 
 756   // Allocate the object pool for scalar-replaced objects -- the map from
 757   // small-integer keys (which can be recorded in the local and ostack
 758   // arrays) to descriptions of the object state.
 759   GrowableArray<ScopeValue*> *objs = new GrowableArray<ScopeValue*>();
 760 
 761   // Visit scopes from oldest to youngest.
 762   for (int depth = 1; depth <= max_depth; depth++) {
 763     JVMState* jvms = youngest_jvms->of_depth(depth);
 764     int idx;
 765     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
 766     // Safepoints that do not have method() set only provide oop-map and monitor info
 767     // to support GC; these do not support deoptimization.
 768     int num_locs = (method == NULL) ? 0 : jvms->loc_size();
 769     int num_exps = (method == NULL) ? 0 : jvms->stk_size();
 770     int num_mon  = jvms->nof_monitors();
 771     assert(method == NULL || jvms->bci() < 0 || num_locs == method->max_locals(),
 772            "JVMS local count must match that of the method");
 773 
 774     // Add Local and Expression Stack Information
 775 
 776     // Insert locals into the locarray
 777     GrowableArray<ScopeValue*> *locarray = new GrowableArray<ScopeValue*>(num_locs);
 778     for( idx = 0; idx < num_locs; idx++ ) {
 779       FillLocArray( idx, sfn, sfn->local(jvms, idx), locarray, objs );
 780     }
 781 
 782     // Insert expression stack entries into the exparray
 783     GrowableArray<ScopeValue*> *exparray = new GrowableArray<ScopeValue*>(num_exps);
 784     for( idx = 0; idx < num_exps; idx++ ) {
 785       FillLocArray( idx,  sfn, sfn->stack(jvms, idx), exparray, objs );
 786     }
 787 
 788     // Add in mappings of the monitors
 789     assert( !method ||
 790             !method->is_synchronized() ||
 791             method->is_native() ||
 792             num_mon > 0 ||
 793             !GenerateSynchronizationCode,
 794             "monitors must always exist for synchronized methods");
 795 
 796     // Build the growable array of ScopeValues for exp stack
 797     GrowableArray<MonitorValue*> *monarray = new GrowableArray<MonitorValue*>(num_mon);
 798 
 799     // Loop over monitors and insert into array
 800     for (idx = 0; idx < num_mon; idx++) {
 801       // Grab the node that defines this monitor
 802       Node* box_node = sfn->monitor_box(jvms, idx);
 803       Node* obj_node = sfn->monitor_obj(jvms, idx);
 804 
 805       // Create ScopeValue for object
 806       ScopeValue *scval = NULL;
 807 
 808       if (obj_node->is_SafePointScalarObject()) {
 809         SafePointScalarObjectNode* spobj = obj_node->as_SafePointScalarObject();
 810         scval = Compile::sv_for_node_id(objs, spobj->_idx);
 811         if (scval == NULL) {
 812           const Type *t = spobj->bottom_type();
 813           ciKlass* cik = t->is_oopptr()->klass();
 814           assert(cik->is_instance_klass() ||
 815                  cik->is_array_klass(), "Not supported allocation.");
 816           ObjectValue* sv = new ObjectValue(spobj->_idx,
 817                                             new ConstantOopWriteValue(cik->java_mirror()->constant_encoding()));
 818           Compile::set_sv_for_object_node(objs, sv);
 819 
 820           uint first_ind = spobj->first_index(youngest_jvms);
 821           for (uint i = 0; i < spobj->n_fields(); i++) {
 822             Node* fld_node = sfn->in(first_ind+i);
 823             (void)FillLocArray(sv->field_values()->length(), sfn, fld_node, sv->field_values(), objs);
 824           }
 825           scval = sv;
 826         }
 827       } else if (!obj_node->is_Con()) {
 828         OptoReg::Name obj_reg = _regalloc->get_reg_first(obj_node);
 829         if( obj_node->bottom_type()->base() == Type::NarrowOop ) {
 830           scval = new_loc_value( _regalloc, obj_reg, Location::narrowoop );
 831         } else {
 832           scval = new_loc_value( _regalloc, obj_reg, Location::oop );
 833         }
 834       } else {
 835         const TypePtr *tp = obj_node->get_ptr_type();
 836         scval = new ConstantOopWriteValue(tp->is_oopptr()->const_oop()->constant_encoding());
 837       }
 838 
 839       OptoReg::Name box_reg = BoxLockNode::reg(box_node);
 840       Location basic_lock = Location::new_stk_loc(Location::normal,_regalloc->reg2offset(box_reg));
 841       bool eliminated = (box_node->is_BoxLock() && box_node->as_BoxLock()->is_eliminated());
 842       monarray->append(new MonitorValue(scval, basic_lock, eliminated));
 843     }
 844 
 845     // We dump the object pool first, since deoptimization reads it in first.
 846     debug_info()->dump_object_pool(objs);
 847 
 848     // Build first class objects to pass to scope
 849     DebugToken *locvals = debug_info()->create_scope_values(locarray);
 850     DebugToken *expvals = debug_info()->create_scope_values(exparray);
 851     DebugToken *monvals = debug_info()->create_monitor_values(monarray);
 852 
 853     // Make method available for all Safepoints
 854     ciMethod* scope_method = method ? method : _method;
 855     // Describe the scope here
 856     assert(jvms->bci() >= InvocationEntryBci && jvms->bci() <= 0x10000, "must be a valid or entry BCI");
 857     assert(!jvms->should_reexecute() || depth == max_depth, "reexecute allowed only for the youngest");
 858     // Now we can describe the scope.
 859     debug_info()->describe_scope(safepoint_pc_offset, scope_method, jvms->bci(), jvms->should_reexecute(), is_method_handle_invoke, return_oop, locvals, expvals, monvals);
 860   } // End jvms loop
 861 
 862   // Mark the end of the scope set.
 863   debug_info()->end_safepoint(safepoint_pc_offset);
 864 }
 865 
 866 
 867 
 868 // A simplified version of Process_OopMap_Node, to handle non-safepoints.
 869 class NonSafepointEmitter {
 870   Compile*  C;
 871   JVMState* _pending_jvms;
 872   int       _pending_offset;
 873 
 874   void emit_non_safepoint();
 875 
 876  public:
 877   NonSafepointEmitter(Compile* compile) {
 878     this->C = compile;
 879     _pending_jvms = NULL;
 880     _pending_offset = 0;
 881   }
 882 
 883   void observe_instruction(Node* n, int pc_offset) {
 884     if (!C->debug_info()->recording_non_safepoints())  return;
 885 
 886     Node_Notes* nn = C->node_notes_at(n->_idx);
 887     if (nn == NULL || nn->jvms() == NULL)  return;
 888     if (_pending_jvms != NULL &&
 889         _pending_jvms->same_calls_as(nn->jvms())) {
 890       // Repeated JVMS?  Stretch it up here.
 891       _pending_offset = pc_offset;
 892     } else {
 893       if (_pending_jvms != NULL &&
 894           _pending_offset < pc_offset) {
 895         emit_non_safepoint();
 896       }
 897       _pending_jvms = NULL;
 898       if (pc_offset > C->debug_info()->last_pc_offset()) {
 899         // This is the only way _pending_jvms can become non-NULL:
 900         _pending_jvms = nn->jvms();
 901         _pending_offset = pc_offset;
 902       }
 903     }
 904   }
 905 
 906   // Stay out of the way of real safepoints:
 907   void observe_safepoint(JVMState* jvms, int pc_offset) {
 908     if (_pending_jvms != NULL &&
 909         !_pending_jvms->same_calls_as(jvms) &&
 910         _pending_offset < pc_offset) {
 911       emit_non_safepoint();
 912     }
 913     _pending_jvms = NULL;
 914   }
 915 
 916   void flush_at_end() {
 917     if (_pending_jvms != NULL) {
 918       emit_non_safepoint();
 919     }
 920     _pending_jvms = NULL;
 921   }
 922 };
 923 
 924 void NonSafepointEmitter::emit_non_safepoint() {
 925   JVMState* youngest_jvms = _pending_jvms;
 926   int       pc_offset     = _pending_offset;
 927 
 928   // Clear it now:
 929   _pending_jvms = NULL;
 930 
 931   DebugInformationRecorder* debug_info = C->debug_info();
 932   assert(debug_info->recording_non_safepoints(), "sanity");
 933 
 934   debug_info->add_non_safepoint(pc_offset);
 935   int max_depth = youngest_jvms->depth();
 936 
 937   // Visit scopes from oldest to youngest.
 938   for (int depth = 1; depth <= max_depth; depth++) {
 939     JVMState* jvms = youngest_jvms->of_depth(depth);
 940     ciMethod* method = jvms->has_method() ? jvms->method() : NULL;
 941     assert(!jvms->should_reexecute() || depth==max_depth, "reexecute allowed only for the youngest");
 942     debug_info->describe_scope(pc_offset, method, jvms->bci(), jvms->should_reexecute());
 943   }
 944 
 945   // Mark the end of the scope set.
 946   debug_info->end_non_safepoint(pc_offset);
 947 }
 948 
 949 //------------------------------init_buffer------------------------------------
 950 CodeBuffer* Compile::init_buffer(uint* blk_starts) {
 951 
 952   // Set the initially allocated size
 953   int  code_req   = initial_code_capacity;
 954   int  locs_req   = initial_locs_capacity;
 955   int  stub_req   = TraceJumps ? initial_stub_capacity * 10 : initial_stub_capacity;
 956   int  const_req  = initial_const_capacity;
 957 
 958   int  pad_req    = NativeCall::instruction_size;
 959   // The extra spacing after the code is necessary on some platforms.
 960   // Sometimes we need to patch in a jump after the last instruction,
 961   // if the nmethod has been deoptimized.  (See 4932387, 4894843.)
 962 
 963   // Compute the byte offset where we can store the deopt pc.
 964   if (fixed_slots() != 0) {
 965     _orig_pc_slot_offset_in_bytes = _regalloc->reg2offset(OptoReg::stack2reg(_orig_pc_slot));
 966   }
 967 
 968   // Compute prolog code size
 969   _method_size = 0;
 970   _frame_slots = OptoReg::reg2stack(_matcher->_old_SP)+_regalloc->_framesize;
 971 #if defined(IA64) && !defined(AIX)
 972   if (save_argument_registers()) {
 973     // 4815101: this is a stub with implicit and unknown precision fp args.
 974     // The usual spill mechanism can only generate stfd's in this case, which
 975     // doesn't work if the fp reg to spill contains a single-precision denorm.
 976     // Instead, we hack around the normal spill mechanism using stfspill's and
 977     // ldffill's in the MachProlog and MachEpilog emit methods.  We allocate
 978     // space here for the fp arg regs (f8-f15) we're going to thusly spill.
 979     //
 980     // If we ever implement 16-byte 'registers' == stack slots, we can
 981     // get rid of this hack and have SpillCopy generate stfspill/ldffill
 982     // instead of stfd/stfs/ldfd/ldfs.
 983     _frame_slots += 8*(16/BytesPerInt);
 984   }
 985 #endif
 986   assert(_frame_slots >= 0 && _frame_slots < 1000000, "sanity check");
 987 
 988   if (has_mach_constant_base_node()) {
 989     uint add_size = 0;
 990     // Fill the constant table.
 991     // Note:  This must happen before shorten_branches.
 992     for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
 993       Block* b = _cfg->get_block(i);
 994 
 995       for (uint j = 0; j < b->number_of_nodes(); j++) {
 996         Node* n = b->get_node(j);
 997 
 998         // If the node is a MachConstantNode evaluate the constant
 999         // value section.
1000         if (n->is_MachConstant()) {
1001           MachConstantNode* machcon = n->as_MachConstant();
1002           machcon->eval_constant(C);
1003         } else if (n->is_Mach()) {
1004           // On Power there are more nodes that issue constants.
1005           add_size += (n->as_Mach()->ins_num_consts() * 8);
1006         }
1007       }
1008     }
1009 
1010     // Calculate the offsets of the constants and the size of the
1011     // constant table (including the padding to the next section).
1012     constant_table().calculate_offsets_and_size();
1013     const_req = constant_table().size() + add_size;
1014   }
1015 
1016   // Initialize the space for the BufferBlob used to find and verify
1017   // instruction size in MachNode::emit_size()
1018   init_scratch_buffer_blob(const_req);
1019   if (failing())  return NULL; // Out of memory
1020 
1021   // Pre-compute the length of blocks and replace
1022   // long branches with short if machine supports it.
1023   shorten_branches(blk_starts, code_req, locs_req, stub_req);
1024 
1025   // nmethod and CodeBuffer count stubs & constants as part of method's code.
1026   // class HandlerImpl is platform-specific and defined in the *.ad files.
1027   int exception_handler_req = HandlerImpl::size_exception_handler() + MAX_stubs_size; // add marginal slop for handler
1028   int deopt_handler_req     = HandlerImpl::size_deopt_handler()     + MAX_stubs_size; // add marginal slop for handler
1029   stub_req += MAX_stubs_size;   // ensure per-stub margin
1030   code_req += MAX_inst_size;    // ensure per-instruction margin
1031 
1032   if (StressCodeBuffers)
1033     code_req = const_req = stub_req = exception_handler_req = deopt_handler_req = 0x10;  // force expansion
1034 
1035   int total_req =
1036     const_req +
1037     code_req +
1038     pad_req +
1039     stub_req +
1040     exception_handler_req +
1041     deopt_handler_req;               // deopt handler
1042 
1043   if (has_method_handle_invokes())
1044     total_req += deopt_handler_req;  // deopt MH handler
1045 
1046   CodeBuffer* cb = code_buffer();
1047   cb->initialize(total_req, locs_req);
1048 
1049   // Have we run out of code space?
1050   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1051     C->record_failure("CodeCache is full");
1052     return NULL;
1053   }
1054   // Configure the code buffer.
1055   cb->initialize_consts_size(const_req);
1056   cb->initialize_stubs_size(stub_req);
1057   cb->initialize_oop_recorder(env()->oop_recorder());
1058 
1059   // fill in the nop array for bundling computations
1060   MachNode *_nop_list[Bundle::_nop_count];
1061   Bundle::initialize_nops(_nop_list);
1062 
1063   return cb;
1064 }
1065 
1066 //------------------------------fill_buffer------------------------------------
1067 void Compile::fill_buffer(CodeBuffer* cb, uint* blk_starts) {
1068   // blk_starts[] contains offsets calculated during short branches processing,
1069   // offsets should not be increased during following steps.
1070 
1071   // Compute the size of first NumberOfLoopInstrToAlign instructions at head
1072   // of a loop. It is used to determine the padding for loop alignment.
1073   compute_loop_first_inst_sizes();
1074 
1075   // Create oopmap set.
1076   _oop_map_set = new OopMapSet();
1077 
1078   // !!!!! This preserves old handling of oopmaps for now
1079   debug_info()->set_oopmaps(_oop_map_set);
1080 
1081   uint nblocks  = _cfg->number_of_blocks();
1082   // Count and start of implicit null check instructions
1083   uint inct_cnt = 0;
1084   uint *inct_starts = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1085 
1086   // Count and start of calls
1087   uint *call_returns = NEW_RESOURCE_ARRAY(uint, nblocks+1);
1088 
1089   uint  return_offset = 0;
1090   int nop_size = (new MachNopNode())->size(_regalloc);
1091 
1092   int previous_offset = 0;
1093   int current_offset  = 0;
1094   int last_call_offset = -1;
1095   int last_avoid_back_to_back_offset = -1;
1096 #ifdef ASSERT
1097   uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
1098   uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
1099   uint* jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
1100   uint* jmp_rule   = NEW_RESOURCE_ARRAY(uint,nblocks);
1101 #endif
1102 
1103   // Create an array of unused labels, one for each basic block, if printing is enabled
1104 #ifndef PRODUCT
1105   int *node_offsets      = NULL;
1106   uint node_offset_limit = unique();
1107 
1108   if (print_assembly())
1109     node_offsets         = NEW_RESOURCE_ARRAY(int, node_offset_limit);
1110 #endif
1111 
1112   NonSafepointEmitter non_safepoints(this);  // emit non-safepoints lazily
1113 
1114   // Emit the constant table.
1115   if (has_mach_constant_base_node()) {
1116     constant_table().emit(*cb);
1117   }
1118 
1119   // Create an array of labels, one for each basic block
1120   Label *blk_labels = NEW_RESOURCE_ARRAY(Label, nblocks+1);
1121   for (uint i=0; i <= nblocks; i++) {
1122     blk_labels[i].init();
1123   }
1124 
1125   // ------------------
1126   // Now fill in the code buffer
1127   Node *delay_slot = NULL;
1128 
1129   for (uint i = 0; i < nblocks; i++) {
1130     Block* block = _cfg->get_block(i);
1131     Node* head = block->head();
1132 
1133     // If this block needs to start aligned (i.e, can be reached other
1134     // than by falling-thru from the previous block), then force the
1135     // start of a new bundle.
1136     if (Pipeline::requires_bundling() && starts_bundle(head)) {
1137       cb->flush_bundle(true);
1138     }
1139 
1140 #ifdef ASSERT
1141     if (!block->is_connector()) {
1142       stringStream st;
1143       block->dump_head(_cfg, &st);
1144       MacroAssembler(cb).block_comment(st.as_string());
1145     }
1146     jmp_target[i] = 0;
1147     jmp_offset[i] = 0;
1148     jmp_size[i]   = 0;
1149     jmp_rule[i]   = 0;
1150 #endif
1151     int blk_offset = current_offset;
1152 
1153     // Define the label at the beginning of the basic block
1154     MacroAssembler(cb).bind(blk_labels[block->_pre_order]);
1155 
1156     uint last_inst = block->number_of_nodes();
1157 
1158     // Emit block normally, except for last instruction.
1159     // Emit means "dump code bits into code buffer".
1160     for (uint j = 0; j<last_inst; j++) {
1161 
1162       // Get the node
1163       Node* n = block->get_node(j);
1164 
1165       // See if delay slots are supported
1166       if (valid_bundle_info(n) &&
1167           node_bundling(n)->used_in_unconditional_delay()) {
1168         assert(delay_slot == NULL, "no use of delay slot node");
1169         assert(n->size(_regalloc) == Pipeline::instr_unit_size(), "delay slot instruction wrong size");
1170 
1171         delay_slot = n;
1172         continue;
1173       }
1174 
1175       // If this starts a new instruction group, then flush the current one
1176       // (but allow split bundles)
1177       if (Pipeline::requires_bundling() && starts_bundle(n))
1178         cb->flush_bundle(false);
1179 
1180       // Special handling for SafePoint/Call Nodes
1181       bool is_mcall = false;
1182       if (n->is_Mach()) {
1183         MachNode *mach = n->as_Mach();
1184         is_mcall = n->is_MachCall();
1185         bool is_sfn = n->is_MachSafePoint();
1186 
1187         // If this requires all previous instructions be flushed, then do so
1188         if (is_sfn || is_mcall || mach->alignment_required() != 1) {
1189           cb->flush_bundle(true);
1190           current_offset = cb->insts_size();
1191         }
1192 
1193         // A padding may be needed again since a previous instruction
1194         // could be moved to delay slot.
1195 
1196         // align the instruction if necessary
1197         int padding = mach->compute_padding(current_offset);
1198         // Make sure safepoint node for polling is distinct from a call's
1199         // return by adding a nop if needed.
1200         if (is_sfn && !is_mcall && padding == 0 && current_offset == last_call_offset) {
1201           padding = nop_size;
1202         }
1203         if (padding == 0 && mach->avoid_back_to_back(MachNode::AVOID_BEFORE) &&
1204             current_offset == last_avoid_back_to_back_offset) {
1205           // Avoid back to back some instructions.
1206           padding = nop_size;
1207         }
1208 
1209         if(padding > 0) {
1210           assert((padding % nop_size) == 0, "padding is not a multiple of NOP size");
1211           int nops_cnt = padding / nop_size;
1212           MachNode *nop = new MachNopNode(nops_cnt);
1213           block->insert_node(nop, j++);
1214           last_inst++;
1215           _cfg->map_node_to_block(nop, block);
1216           nop->emit(*cb, _regalloc);
1217           cb->flush_bundle(true);
1218           current_offset = cb->insts_size();
1219         }
1220 
1221         // Remember the start of the last call in a basic block
1222         if (is_mcall) {
1223           MachCallNode *mcall = mach->as_MachCall();
1224 
1225           // This destination address is NOT PC-relative
1226           mcall->method_set((intptr_t)mcall->entry_point());
1227 
1228           // Save the return address
1229           call_returns[block->_pre_order] = current_offset + mcall->ret_addr_offset();
1230 
1231           if (mcall->is_MachCallLeaf()) {
1232             is_mcall = false;
1233             is_sfn = false;
1234           }
1235         }
1236 
1237         // sfn will be valid whenever mcall is valid now because of inheritance
1238         if (is_sfn || is_mcall) {
1239 
1240           // Handle special safepoint nodes for synchronization
1241           if (!is_mcall) {
1242             MachSafePointNode *sfn = mach->as_MachSafePoint();
1243             // !!!!! Stubs only need an oopmap right now, so bail out
1244             if (sfn->jvms()->method() == NULL) {
1245               // Write the oopmap directly to the code blob??!!
1246               continue;
1247             }
1248           } // End synchronization
1249 
1250           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1251                                            current_offset);
1252           Process_OopMap_Node(mach, current_offset);
1253         } // End if safepoint
1254 
1255         // If this is a null check, then add the start of the previous instruction to the list
1256         else if( mach->is_MachNullCheck() ) {
1257           inct_starts[inct_cnt++] = previous_offset;
1258         }
1259 
1260         // If this is a branch, then fill in the label with the target BB's label
1261         else if (mach->is_MachBranch()) {
1262           // This requires the TRUE branch target be in succs[0]
1263           uint block_num = block->non_connector_successor(0)->_pre_order;
1264 
1265           // Try to replace long branch if delay slot is not used,
1266           // it is mostly for back branches since forward branch's
1267           // distance is not updated yet.
1268           bool delay_slot_is_used = valid_bundle_info(n) &&
1269                                     node_bundling(n)->use_unconditional_delay();
1270           if (!delay_slot_is_used && mach->may_be_short_branch()) {
1271            assert(delay_slot == NULL, "not expecting delay slot node");
1272            int br_size = n->size(_regalloc);
1273             int offset = blk_starts[block_num] - current_offset;
1274             if (block_num >= i) {
1275               // Current and following block's offset are not
1276               // finalized yet, adjust distance by the difference
1277               // between calculated and final offsets of current block.
1278               offset -= (blk_starts[i] - blk_offset);
1279             }
1280             // In the following code a nop could be inserted before
1281             // the branch which will increase the backward distance.
1282             bool needs_padding = (current_offset == last_avoid_back_to_back_offset);
1283             if (needs_padding && offset <= 0)
1284               offset -= nop_size;
1285 
1286             if (_matcher->is_short_branch_offset(mach->rule(), br_size, offset)) {
1287               // We've got a winner.  Replace this branch.
1288               MachNode* replacement = mach->as_MachBranch()->short_branch_version();
1289 
1290               // Update the jmp_size.
1291               int new_size = replacement->size(_regalloc);
1292               assert((br_size - new_size) >= (int)nop_size, "short_branch size should be smaller");
1293               // Insert padding between avoid_back_to_back branches.
1294               if (needs_padding && replacement->avoid_back_to_back(MachNode::AVOID_BEFORE)) {
1295                 MachNode *nop = new MachNopNode();
1296                 block->insert_node(nop, j++);
1297                 _cfg->map_node_to_block(nop, block);
1298                 last_inst++;
1299                 nop->emit(*cb, _regalloc);
1300                 cb->flush_bundle(true);
1301                 current_offset = cb->insts_size();
1302               }
1303 #ifdef ASSERT
1304               jmp_target[i] = block_num;
1305               jmp_offset[i] = current_offset - blk_offset;
1306               jmp_size[i]   = new_size;
1307               jmp_rule[i]   = mach->rule();
1308 #endif
1309               block->map_node(replacement, j);
1310               mach->subsume_by(replacement, C);
1311               n    = replacement;
1312               mach = replacement;
1313             }
1314           }
1315           mach->as_MachBranch()->label_set( &blk_labels[block_num], block_num );
1316         } else if (mach->ideal_Opcode() == Op_Jump) {
1317           for (uint h = 0; h < block->_num_succs; h++) {
1318             Block* succs_block = block->_succs[h];
1319             for (uint j = 1; j < succs_block->num_preds(); j++) {
1320               Node* jpn = succs_block->pred(j);
1321               if (jpn->is_JumpProj() && jpn->in(0) == mach) {
1322                 uint block_num = succs_block->non_connector()->_pre_order;
1323                 Label *blkLabel = &blk_labels[block_num];
1324                 mach->add_case_label(jpn->as_JumpProj()->proj_no(), blkLabel);
1325               }
1326             }
1327           }
1328         }
1329 #ifdef ASSERT
1330         // Check that oop-store precedes the card-mark
1331         else if (mach->ideal_Opcode() == Op_StoreCM) {
1332           uint storeCM_idx = j;
1333           int count = 0;
1334           for (uint prec = mach->req(); prec < mach->len(); prec++) {
1335             Node *oop_store = mach->in(prec);  // Precedence edge
1336             if (oop_store == NULL) continue;
1337             count++;
1338             uint i4;
1339             for (i4 = 0; i4 < last_inst; ++i4) {
1340               if (block->get_node(i4) == oop_store) {
1341                 break;
1342               }
1343             }
1344             // Note: This test can provide a false failure if other precedence
1345             // edges have been added to the storeCMNode.
1346             assert(i4 == last_inst || i4 < storeCM_idx, "CM card-mark executes before oop-store");
1347           }
1348           assert(count > 0, "storeCM expects at least one precedence edge");
1349         }
1350 #endif
1351         else if (!n->is_Proj()) {
1352           // Remember the beginning of the previous instruction, in case
1353           // it's followed by a flag-kill and a null-check.  Happens on
1354           // Intel all the time, with add-to-memory kind of opcodes.
1355           previous_offset = current_offset;
1356         }
1357 
1358         // Not an else-if!
1359         // If this is a trap based cmp then add its offset to the list.
1360         if (mach->is_TrapBasedCheckNode()) {
1361           inct_starts[inct_cnt++] = current_offset;
1362         }
1363       }
1364 
1365       // Verify that there is sufficient space remaining
1366       cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
1367       if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1368         C->record_failure("CodeCache is full");
1369         return;
1370       }
1371 
1372       // Save the offset for the listing
1373 #ifndef PRODUCT
1374       if (node_offsets && n->_idx < node_offset_limit)
1375         node_offsets[n->_idx] = cb->insts_size();
1376 #endif
1377 
1378       // "Normal" instruction case
1379       DEBUG_ONLY( uint instr_offset = cb->insts_size(); )
1380       n->emit(*cb, _regalloc);
1381       current_offset  = cb->insts_size();
1382 
1383       // Above we only verified that there is enough space in the instruction section.
1384       // However, the instruction may emit stubs that cause code buffer expansion.
1385       // Bail out here if expansion failed due to a lack of code cache space.
1386       if (failing()) {
1387         return;
1388       }
1389 
1390 #ifdef ASSERT
1391       if (n->size(_regalloc) < (current_offset-instr_offset)) {
1392         n->dump();
1393         assert(false, "wrong size of mach node");
1394       }
1395 #endif
1396       non_safepoints.observe_instruction(n, current_offset);
1397 
1398       // mcall is last "call" that can be a safepoint
1399       // record it so we can see if a poll will directly follow it
1400       // in which case we'll need a pad to make the PcDesc sites unique
1401       // see  5010568. This can be slightly inaccurate but conservative
1402       // in the case that return address is not actually at current_offset.
1403       // This is a small price to pay.
1404 
1405       if (is_mcall) {
1406         last_call_offset = current_offset;
1407       }
1408 
1409       if (n->is_Mach() && n->as_Mach()->avoid_back_to_back(MachNode::AVOID_AFTER)) {
1410         // Avoid back to back some instructions.
1411         last_avoid_back_to_back_offset = current_offset;
1412       }
1413 
1414       // See if this instruction has a delay slot
1415       if (valid_bundle_info(n) && node_bundling(n)->use_unconditional_delay()) {
1416         assert(delay_slot != NULL, "expecting delay slot node");
1417 
1418         // Back up 1 instruction
1419         cb->set_insts_end(cb->insts_end() - Pipeline::instr_unit_size());
1420 
1421         // Save the offset for the listing
1422 #ifndef PRODUCT
1423         if (node_offsets && delay_slot->_idx < node_offset_limit)
1424           node_offsets[delay_slot->_idx] = cb->insts_size();
1425 #endif
1426 
1427         // Support a SafePoint in the delay slot
1428         if (delay_slot->is_MachSafePoint()) {
1429           MachNode *mach = delay_slot->as_Mach();
1430           // !!!!! Stubs only need an oopmap right now, so bail out
1431           if (!mach->is_MachCall() && mach->as_MachSafePoint()->jvms()->method() == NULL) {
1432             // Write the oopmap directly to the code blob??!!
1433             delay_slot = NULL;
1434             continue;
1435           }
1436 
1437           int adjusted_offset = current_offset - Pipeline::instr_unit_size();
1438           non_safepoints.observe_safepoint(mach->as_MachSafePoint()->jvms(),
1439                                            adjusted_offset);
1440           // Generate an OopMap entry
1441           Process_OopMap_Node(mach, adjusted_offset);
1442         }
1443 
1444         // Insert the delay slot instruction
1445         delay_slot->emit(*cb, _regalloc);
1446 
1447         // Don't reuse it
1448         delay_slot = NULL;
1449       }
1450 
1451     } // End for all instructions in block
1452 
1453     // If the next block is the top of a loop, pad this block out to align
1454     // the loop top a little. Helps prevent pipe stalls at loop back branches.
1455     if (i < nblocks-1) {
1456       Block *nb = _cfg->get_block(i + 1);
1457       int padding = nb->alignment_padding(current_offset);
1458       if( padding > 0 ) {
1459         MachNode *nop = new MachNopNode(padding / nop_size);
1460         block->insert_node(nop, block->number_of_nodes());
1461         _cfg->map_node_to_block(nop, block);
1462         nop->emit(*cb, _regalloc);
1463         current_offset = cb->insts_size();
1464       }
1465     }
1466     // Verify that the distance for generated before forward
1467     // short branches is still valid.
1468     guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
1469 
1470     // Save new block start offset
1471     blk_starts[i] = blk_offset;
1472   } // End of for all blocks
1473   blk_starts[nblocks] = current_offset;
1474 
1475   non_safepoints.flush_at_end();
1476 
1477   // Offset too large?
1478   if (failing())  return;
1479 
1480   // Define a pseudo-label at the end of the code
1481   MacroAssembler(cb).bind( blk_labels[nblocks] );
1482 
1483   // Compute the size of the first block
1484   _first_block_size = blk_labels[1].loc_pos() - blk_labels[0].loc_pos();
1485 
1486   assert(cb->insts_size() < 500000, "method is unreasonably large");
1487 
1488 #ifdef ASSERT
1489   for (uint i = 0; i < nblocks; i++) { // For all blocks
1490     if (jmp_target[i] != 0) {
1491       int br_size = jmp_size[i];
1492       int offset = blk_starts[jmp_target[i]]-(blk_starts[i] + jmp_offset[i]);
1493       if (!_matcher->is_short_branch_offset(jmp_rule[i], br_size, offset)) {
1494         tty->print_cr("target (%d) - jmp_offset(%d) = offset (%d), jump_size(%d), jmp_block B%d, target_block B%d", blk_starts[jmp_target[i]], blk_starts[i] + jmp_offset[i], offset, br_size, i, jmp_target[i]);
1495         assert(false, "Displacement too large for short jmp");
1496       }
1497     }
1498   }
1499 #endif
1500 
1501 #ifndef PRODUCT
1502   // Information on the size of the method, without the extraneous code
1503   Scheduling::increment_method_size(cb->insts_size());
1504 #endif
1505 
1506   // ------------------
1507   // Fill in exception table entries.
1508   FillExceptionTables(inct_cnt, call_returns, inct_starts, blk_labels);
1509 
1510   // Only java methods have exception handlers and deopt handlers
1511   // class HandlerImpl is platform-specific and defined in the *.ad files.
1512   if (_method) {
1513     // Emit the exception handler code.
1514     _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
1515     if (failing()) {
1516       return; // CodeBuffer::expand failed
1517     }
1518     // Emit the deopt handler code.
1519     _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
1520 
1521     // Emit the MethodHandle deopt handler code (if required).
1522     if (has_method_handle_invokes() && !failing()) {
1523       // We can use the same code as for the normal deopt handler, we
1524       // just need a different entry point address.
1525       _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
1526     }
1527   }
1528 
1529   // One last check for failed CodeBuffer::expand:
1530   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
1531     C->record_failure("CodeCache is full");
1532     return;
1533   }
1534 
1535 #ifndef PRODUCT
1536   // Dump the assembly code, including basic-block numbers
1537   if (print_assembly()) {
1538     ttyLocker ttyl;  // keep the following output all in one block
1539     if (!VMThread::should_terminate()) {  // test this under the tty lock
1540       // This output goes directly to the tty, not the compiler log.
1541       // To enable tools to match it up with the compilation activity,
1542       // be sure to tag this tty output with the compile ID.
1543       if (xtty != NULL) {
1544         xtty->head("opto_assembly compile_id='%d'%s", compile_id(),
1545                    is_osr_compilation()    ? " compile_kind='osr'" :
1546                    "");
1547       }
1548       if (method() != NULL) {
1549         method()->print_metadata();
1550       }
1551       dump_asm(node_offsets, node_offset_limit);
1552       if (xtty != NULL) {
1553         xtty->tail("opto_assembly");
1554       }
1555     }
1556   }
1557 #endif
1558 
1559 }
1560 
1561 void Compile::FillExceptionTables(uint cnt, uint *call_returns, uint *inct_starts, Label *blk_labels) {
1562   _inc_table.set_size(cnt);
1563 
1564   uint inct_cnt = 0;
1565   for (uint i = 0; i < _cfg->number_of_blocks(); i++) {
1566     Block* block = _cfg->get_block(i);
1567     Node *n = NULL;
1568     int j;
1569 
1570     // Find the branch; ignore trailing NOPs.
1571     for (j = block->number_of_nodes() - 1; j >= 0; j--) {
1572       n = block->get_node(j);
1573       if (!n->is_Mach() || n->as_Mach()->ideal_Opcode() != Op_Con) {
1574         break;
1575       }
1576     }
1577 
1578     // If we didn't find anything, continue
1579     if (j < 0) {
1580       continue;
1581     }
1582 
1583     // Compute ExceptionHandlerTable subtable entry and add it
1584     // (skip empty blocks)
1585     if (n->is_Catch()) {
1586 
1587       // Get the offset of the return from the call
1588       uint call_return = call_returns[block->_pre_order];
1589 #ifdef ASSERT
1590       assert( call_return > 0, "no call seen for this basic block" );
1591       while (block->get_node(--j)->is_MachProj()) ;
1592       assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");
1593 #endif
1594       // last instruction is a CatchNode, find it's CatchProjNodes
1595       int nof_succs = block->_num_succs;
1596       // allocate space
1597       GrowableArray<intptr_t> handler_bcis(nof_succs);
1598       GrowableArray<intptr_t> handler_pcos(nof_succs);
1599       // iterate through all successors
1600       for (int j = 0; j < nof_succs; j++) {
1601         Block* s = block->_succs[j];
1602         bool found_p = false;
1603         for (uint k = 1; k < s->num_preds(); k++) {
1604           Node* pk = s->pred(k);
1605           if (pk->is_CatchProj() && pk->in(0) == n) {
1606             const CatchProjNode* p = pk->as_CatchProj();
1607             found_p = true;
1608             // add the corresponding handler bci & pco information
1609             if (p->_con != CatchProjNode::fall_through_index) {
1610               // p leads to an exception handler (and is not fall through)
1611               assert(s == _cfg->get_block(s->_pre_order), "bad numbering");
1612               // no duplicates, please
1613               if (!handler_bcis.contains(p->handler_bci())) {
1614                 uint block_num = s->non_connector()->_pre_order;
1615                 handler_bcis.append(p->handler_bci());
1616                 handler_pcos.append(blk_labels[block_num].loc_pos());
1617               }
1618             }
1619           }
1620         }
1621         assert(found_p, "no matching predecessor found");
1622         // Note:  Due to empty block removal, one block may have
1623         // several CatchProj inputs, from the same Catch.
1624       }
1625 
1626       // Set the offset of the return from the call
1627       _handler_table.add_subtable(call_return, &handler_bcis, NULL, &handler_pcos);
1628       continue;
1629     }
1630 
1631     // Handle implicit null exception table updates
1632     if (n->is_MachNullCheck()) {
1633       uint block_num = block->non_connector_successor(0)->_pre_order;
1634       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1635       continue;
1636     }
1637     // Handle implicit exception table updates: trap instructions.
1638     if (n->is_Mach() && n->as_Mach()->is_TrapBasedCheckNode()) {
1639       uint block_num = block->non_connector_successor(0)->_pre_order;
1640       _inc_table.append(inct_starts[inct_cnt++], blk_labels[block_num].loc_pos());
1641       continue;
1642     }
1643   } // End of for all blocks fill in exception table entries
1644 }
1645 
1646 // Static Variables
1647 #ifndef PRODUCT
1648 uint Scheduling::_total_nop_size = 0;
1649 uint Scheduling::_total_method_size = 0;
1650 uint Scheduling::_total_branches = 0;
1651 uint Scheduling::_total_unconditional_delays = 0;
1652 uint Scheduling::_total_instructions_per_bundle[Pipeline::_max_instrs_per_cycle+1];
1653 #endif
1654 
1655 // Initializer for class Scheduling
1656 
1657 Scheduling::Scheduling(Arena *arena, Compile &compile)
1658   : _arena(arena),
1659     _cfg(compile.cfg()),
1660     _regalloc(compile.regalloc()),
1661     _reg_node(arena),
1662     _bundle_instr_count(0),
1663     _bundle_cycle_number(0),
1664     _scheduled(arena),
1665     _available(arena),
1666     _next_node(NULL),
1667     _bundle_use(0, 0, resource_count, &_bundle_use_elements[0]),
1668     _pinch_free_list(arena)
1669 #ifndef PRODUCT
1670   , _branches(0)
1671   , _unconditional_delays(0)
1672 #endif
1673 {
1674   // Create a MachNopNode
1675   _nop = new MachNopNode();
1676 
1677   // Now that the nops are in the array, save the count
1678   // (but allow entries for the nops)
1679   _node_bundling_limit = compile.unique();
1680   uint node_max = _regalloc->node_regs_max_index();
1681 
1682   compile.set_node_bundling_limit(_node_bundling_limit);
1683 
1684   // This one is persistent within the Compile class
1685   _node_bundling_base = NEW_ARENA_ARRAY(compile.comp_arena(), Bundle, node_max);
1686 
1687   // Allocate space for fixed-size arrays
1688   _node_latency    = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1689   _uses            = NEW_ARENA_ARRAY(arena, short,          node_max);
1690   _current_latency = NEW_ARENA_ARRAY(arena, unsigned short, node_max);
1691 
1692   // Clear the arrays
1693   memset(_node_bundling_base, 0, node_max * sizeof(Bundle));
1694   memset(_node_latency,       0, node_max * sizeof(unsigned short));
1695   memset(_uses,               0, node_max * sizeof(short));
1696   memset(_current_latency,    0, node_max * sizeof(unsigned short));
1697 
1698   // Clear the bundling information
1699   memcpy(_bundle_use_elements, Pipeline_Use::elaborated_elements, sizeof(Pipeline_Use::elaborated_elements));
1700 
1701   // Get the last node
1702   Block* block = _cfg->get_block(_cfg->number_of_blocks() - 1);
1703 
1704   _next_node = block->get_node(block->number_of_nodes() - 1);
1705 }
1706 
1707 #ifndef PRODUCT
1708 // Scheduling destructor
1709 Scheduling::~Scheduling() {
1710   _total_branches             += _branches;
1711   _total_unconditional_delays += _unconditional_delays;
1712 }
1713 #endif
1714 
1715 // Step ahead "i" cycles
1716 void Scheduling::step(uint i) {
1717 
1718   Bundle *bundle = node_bundling(_next_node);
1719   bundle->set_starts_bundle();
1720 
1721   // Update the bundle record, but leave the flags information alone
1722   if (_bundle_instr_count > 0) {
1723     bundle->set_instr_count(_bundle_instr_count);
1724     bundle->set_resources_used(_bundle_use.resourcesUsed());
1725   }
1726 
1727   // Update the state information
1728   _bundle_instr_count = 0;
1729   _bundle_cycle_number += i;
1730   _bundle_use.step(i);
1731 }
1732 
1733 void Scheduling::step_and_clear() {
1734   Bundle *bundle = node_bundling(_next_node);
1735   bundle->set_starts_bundle();
1736 
1737   // Update the bundle record
1738   if (_bundle_instr_count > 0) {
1739     bundle->set_instr_count(_bundle_instr_count);
1740     bundle->set_resources_used(_bundle_use.resourcesUsed());
1741 
1742     _bundle_cycle_number += 1;
1743   }
1744 
1745   // Clear the bundling information
1746   _bundle_instr_count = 0;
1747   _bundle_use.reset();
1748 
1749   memcpy(_bundle_use_elements,
1750     Pipeline_Use::elaborated_elements,
1751     sizeof(Pipeline_Use::elaborated_elements));
1752 }
1753 
1754 // Perform instruction scheduling and bundling over the sequence of
1755 // instructions in backwards order.
1756 void Compile::ScheduleAndBundle() {
1757 
1758   // Don't optimize this if it isn't a method
1759   if (!_method)
1760     return;
1761 
1762   // Don't optimize this if scheduling is disabled
1763   if (!do_scheduling())
1764     return;
1765 
1766   // Scheduling code works only with pairs (16 bytes) maximum.
1767   if (max_vector_size() > 16)
1768     return;
1769 
1770   TracePhase tp("isched", &timers[_t_instrSched]);
1771 
1772   // Create a data structure for all the scheduling information
1773   Scheduling scheduling(Thread::current()->resource_area(), *this);
1774 
1775   // Walk backwards over each basic block, computing the needed alignment
1776   // Walk over all the basic blocks
1777   scheduling.DoScheduling();
1778 }
1779 
1780 // Compute the latency of all the instructions.  This is fairly simple,
1781 // because we already have a legal ordering.  Walk over the instructions
1782 // from first to last, and compute the latency of the instruction based
1783 // on the latency of the preceding instruction(s).
1784 void Scheduling::ComputeLocalLatenciesForward(const Block *bb) {
1785 #ifndef PRODUCT
1786   if (_cfg->C->trace_opto_output())
1787     tty->print("# -> ComputeLocalLatenciesForward\n");
1788 #endif
1789 
1790   // Walk over all the schedulable instructions
1791   for( uint j=_bb_start; j < _bb_end; j++ ) {
1792 
1793     // This is a kludge, forcing all latency calculations to start at 1.
1794     // Used to allow latency 0 to force an instruction to the beginning
1795     // of the bb
1796     uint latency = 1;
1797     Node *use = bb->get_node(j);
1798     uint nlen = use->len();
1799 
1800     // Walk over all the inputs
1801     for ( uint k=0; k < nlen; k++ ) {
1802       Node *def = use->in(k);
1803       if (!def)
1804         continue;
1805 
1806       uint l = _node_latency[def->_idx] + use->latency(k);
1807       if (latency < l)
1808         latency = l;
1809     }
1810 
1811     _node_latency[use->_idx] = latency;
1812 
1813 #ifndef PRODUCT
1814     if (_cfg->C->trace_opto_output()) {
1815       tty->print("# latency %4d: ", latency);
1816       use->dump();
1817     }
1818 #endif
1819   }
1820 
1821 #ifndef PRODUCT
1822   if (_cfg->C->trace_opto_output())
1823     tty->print("# <- ComputeLocalLatenciesForward\n");
1824 #endif
1825 
1826 } // end ComputeLocalLatenciesForward
1827 
1828 // See if this node fits into the present instruction bundle
1829 bool Scheduling::NodeFitsInBundle(Node *n) {
1830   uint n_idx = n->_idx;
1831 
1832   // If this is the unconditional delay instruction, then it fits
1833   if (n == _unconditional_delay_slot) {
1834 #ifndef PRODUCT
1835     if (_cfg->C->trace_opto_output())
1836       tty->print("#     NodeFitsInBundle [%4d]: TRUE; is in unconditional delay slot\n", n->_idx);
1837 #endif
1838     return (true);
1839   }
1840 
1841   // If the node cannot be scheduled this cycle, skip it
1842   if (_current_latency[n_idx] > _bundle_cycle_number) {
1843 #ifndef PRODUCT
1844     if (_cfg->C->trace_opto_output())
1845       tty->print("#     NodeFitsInBundle [%4d]: FALSE; latency %4d > %d\n",
1846         n->_idx, _current_latency[n_idx], _bundle_cycle_number);
1847 #endif
1848     return (false);
1849   }
1850 
1851   const Pipeline *node_pipeline = n->pipeline();
1852 
1853   uint instruction_count = node_pipeline->instructionCount();
1854   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
1855     instruction_count = 0;
1856   else if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
1857     instruction_count++;
1858 
1859   if (_bundle_instr_count + instruction_count > Pipeline::_max_instrs_per_cycle) {
1860 #ifndef PRODUCT
1861     if (_cfg->C->trace_opto_output())
1862       tty->print("#     NodeFitsInBundle [%4d]: FALSE; too many instructions: %d > %d\n",
1863         n->_idx, _bundle_instr_count + instruction_count, Pipeline::_max_instrs_per_cycle);
1864 #endif
1865     return (false);
1866   }
1867 
1868   // Don't allow non-machine nodes to be handled this way
1869   if (!n->is_Mach() && instruction_count == 0)
1870     return (false);
1871 
1872   // See if there is any overlap
1873   uint delay = _bundle_use.full_latency(0, node_pipeline->resourceUse());
1874 
1875   if (delay > 0) {
1876 #ifndef PRODUCT
1877     if (_cfg->C->trace_opto_output())
1878       tty->print("#     NodeFitsInBundle [%4d]: FALSE; functional units overlap\n", n_idx);
1879 #endif
1880     return false;
1881   }
1882 
1883 #ifndef PRODUCT
1884   if (_cfg->C->trace_opto_output())
1885     tty->print("#     NodeFitsInBundle [%4d]:  TRUE\n", n_idx);
1886 #endif
1887 
1888   return true;
1889 }
1890 
1891 Node * Scheduling::ChooseNodeToBundle() {
1892   uint siz = _available.size();
1893 
1894   if (siz == 0) {
1895 
1896 #ifndef PRODUCT
1897     if (_cfg->C->trace_opto_output())
1898       tty->print("#   ChooseNodeToBundle: NULL\n");
1899 #endif
1900     return (NULL);
1901   }
1902 
1903   // Fast path, if only 1 instruction in the bundle
1904   if (siz == 1) {
1905 #ifndef PRODUCT
1906     if (_cfg->C->trace_opto_output()) {
1907       tty->print("#   ChooseNodeToBundle (only 1): ");
1908       _available[0]->dump();
1909     }
1910 #endif
1911     return (_available[0]);
1912   }
1913 
1914   // Don't bother, if the bundle is already full
1915   if (_bundle_instr_count < Pipeline::_max_instrs_per_cycle) {
1916     for ( uint i = 0; i < siz; i++ ) {
1917       Node *n = _available[i];
1918 
1919       // Skip projections, we'll handle them another way
1920       if (n->is_Proj())
1921         continue;
1922 
1923       // This presupposed that instructions are inserted into the
1924       // available list in a legality order; i.e. instructions that
1925       // must be inserted first are at the head of the list
1926       if (NodeFitsInBundle(n)) {
1927 #ifndef PRODUCT
1928         if (_cfg->C->trace_opto_output()) {
1929           tty->print("#   ChooseNodeToBundle: ");
1930           n->dump();
1931         }
1932 #endif
1933         return (n);
1934       }
1935     }
1936   }
1937 
1938   // Nothing fits in this bundle, choose the highest priority
1939 #ifndef PRODUCT
1940   if (_cfg->C->trace_opto_output()) {
1941     tty->print("#   ChooseNodeToBundle: ");
1942     _available[0]->dump();
1943   }
1944 #endif
1945 
1946   return _available[0];
1947 }
1948 
1949 void Scheduling::AddNodeToAvailableList(Node *n) {
1950   assert( !n->is_Proj(), "projections never directly made available" );
1951 #ifndef PRODUCT
1952   if (_cfg->C->trace_opto_output()) {
1953     tty->print("#   AddNodeToAvailableList: ");
1954     n->dump();
1955   }
1956 #endif
1957 
1958   int latency = _current_latency[n->_idx];
1959 
1960   // Insert in latency order (insertion sort)
1961   uint i;
1962   for ( i=0; i < _available.size(); i++ )
1963     if (_current_latency[_available[i]->_idx] > latency)
1964       break;
1965 
1966   // Special Check for compares following branches
1967   if( n->is_Mach() && _scheduled.size() > 0 ) {
1968     int op = n->as_Mach()->ideal_Opcode();
1969     Node *last = _scheduled[0];
1970     if( last->is_MachIf() && last->in(1) == n &&
1971         ( op == Op_CmpI ||
1972           op == Op_CmpU ||
1973           op == Op_CmpP ||
1974           op == Op_CmpF ||
1975           op == Op_CmpD ||
1976           op == Op_CmpL ) ) {
1977 
1978       // Recalculate position, moving to front of same latency
1979       for ( i=0 ; i < _available.size(); i++ )
1980         if (_current_latency[_available[i]->_idx] >= latency)
1981           break;
1982     }
1983   }
1984 
1985   // Insert the node in the available list
1986   _available.insert(i, n);
1987 
1988 #ifndef PRODUCT
1989   if (_cfg->C->trace_opto_output())
1990     dump_available();
1991 #endif
1992 }
1993 
1994 void Scheduling::DecrementUseCounts(Node *n, const Block *bb) {
1995   for ( uint i=0; i < n->len(); i++ ) {
1996     Node *def = n->in(i);
1997     if (!def) continue;
1998     if( def->is_Proj() )        // If this is a machine projection, then
1999       def = def->in(0);         // propagate usage thru to the base instruction
2000 
2001     if(_cfg->get_block_for_node(def) != bb) { // Ignore if not block-local
2002       continue;
2003     }
2004 
2005     // Compute the latency
2006     uint l = _bundle_cycle_number + n->latency(i);
2007     if (_current_latency[def->_idx] < l)
2008       _current_latency[def->_idx] = l;
2009 
2010     // If this does not have uses then schedule it
2011     if ((--_uses[def->_idx]) == 0)
2012       AddNodeToAvailableList(def);
2013   }
2014 }
2015 
2016 void Scheduling::AddNodeToBundle(Node *n, const Block *bb) {
2017 #ifndef PRODUCT
2018   if (_cfg->C->trace_opto_output()) {
2019     tty->print("#   AddNodeToBundle: ");
2020     n->dump();
2021   }
2022 #endif
2023 
2024   // Remove this from the available list
2025   uint i;
2026   for (i = 0; i < _available.size(); i++)
2027     if (_available[i] == n)
2028       break;
2029   assert(i < _available.size(), "entry in _available list not found");
2030   _available.remove(i);
2031 
2032   // See if this fits in the current bundle
2033   const Pipeline *node_pipeline = n->pipeline();
2034   const Pipeline_Use& node_usage = node_pipeline->resourceUse();
2035 
2036   // Check for instructions to be placed in the delay slot. We
2037   // do this before we actually schedule the current instruction,
2038   // because the delay slot follows the current instruction.
2039   if (Pipeline::_branch_has_delay_slot &&
2040       node_pipeline->hasBranchDelay() &&
2041       !_unconditional_delay_slot) {
2042 
2043     uint siz = _available.size();
2044 
2045     // Conditional branches can support an instruction that
2046     // is unconditionally executed and not dependent by the
2047     // branch, OR a conditionally executed instruction if
2048     // the branch is taken.  In practice, this means that
2049     // the first instruction at the branch target is
2050     // copied to the delay slot, and the branch goes to
2051     // the instruction after that at the branch target
2052     if ( n->is_MachBranch() ) {
2053 
2054       assert( !n->is_MachNullCheck(), "should not look for delay slot for Null Check" );
2055       assert( !n->is_Catch(),         "should not look for delay slot for Catch" );
2056 
2057 #ifndef PRODUCT
2058       _branches++;
2059 #endif
2060 
2061       // At least 1 instruction is on the available list
2062       // that is not dependent on the branch
2063       for (uint i = 0; i < siz; i++) {
2064         Node *d = _available[i];
2065         const Pipeline *avail_pipeline = d->pipeline();
2066 
2067         // Don't allow safepoints in the branch shadow, that will
2068         // cause a number of difficulties
2069         if ( avail_pipeline->instructionCount() == 1 &&
2070             !avail_pipeline->hasMultipleBundles() &&
2071             !avail_pipeline->hasBranchDelay() &&
2072             Pipeline::instr_has_unit_size() &&
2073             d->size(_regalloc) == Pipeline::instr_unit_size() &&
2074             NodeFitsInBundle(d) &&
2075             !node_bundling(d)->used_in_delay()) {
2076 
2077           if (d->is_Mach() && !d->is_MachSafePoint()) {
2078             // A node that fits in the delay slot was found, so we need to
2079             // set the appropriate bits in the bundle pipeline information so
2080             // that it correctly indicates resource usage.  Later, when we
2081             // attempt to add this instruction to the bundle, we will skip
2082             // setting the resource usage.
2083             _unconditional_delay_slot = d;
2084             node_bundling(n)->set_use_unconditional_delay();
2085             node_bundling(d)->set_used_in_unconditional_delay();
2086             _bundle_use.add_usage(avail_pipeline->resourceUse());
2087             _current_latency[d->_idx] = _bundle_cycle_number;
2088             _next_node = d;
2089             ++_bundle_instr_count;
2090 #ifndef PRODUCT
2091             _unconditional_delays++;
2092 #endif
2093             break;
2094           }
2095         }
2096       }
2097     }
2098 
2099     // No delay slot, add a nop to the usage
2100     if (!_unconditional_delay_slot) {
2101       // See if adding an instruction in the delay slot will overflow
2102       // the bundle.
2103       if (!NodeFitsInBundle(_nop)) {
2104 #ifndef PRODUCT
2105         if (_cfg->C->trace_opto_output())
2106           tty->print("#  *** STEP(1 instruction for delay slot) ***\n");
2107 #endif
2108         step(1);
2109       }
2110 
2111       _bundle_use.add_usage(_nop->pipeline()->resourceUse());
2112       _next_node = _nop;
2113       ++_bundle_instr_count;
2114     }
2115 
2116     // See if the instruction in the delay slot requires a
2117     // step of the bundles
2118     if (!NodeFitsInBundle(n)) {
2119 #ifndef PRODUCT
2120         if (_cfg->C->trace_opto_output())
2121           tty->print("#  *** STEP(branch won't fit) ***\n");
2122 #endif
2123         // Update the state information
2124         _bundle_instr_count = 0;
2125         _bundle_cycle_number += 1;
2126         _bundle_use.step(1);
2127     }
2128   }
2129 
2130   // Get the number of instructions
2131   uint instruction_count = node_pipeline->instructionCount();
2132   if (node_pipeline->mayHaveNoCode() && n->size(_regalloc) == 0)
2133     instruction_count = 0;
2134 
2135   // Compute the latency information
2136   uint delay = 0;
2137 
2138   if (instruction_count > 0 || !node_pipeline->mayHaveNoCode()) {
2139     int relative_latency = _current_latency[n->_idx] - _bundle_cycle_number;
2140     if (relative_latency < 0)
2141       relative_latency = 0;
2142 
2143     delay = _bundle_use.full_latency(relative_latency, node_usage);
2144 
2145     // Does not fit in this bundle, start a new one
2146     if (delay > 0) {
2147       step(delay);
2148 
2149 #ifndef PRODUCT
2150       if (_cfg->C->trace_opto_output())
2151         tty->print("#  *** STEP(%d) ***\n", delay);
2152 #endif
2153     }
2154   }
2155 
2156   // If this was placed in the delay slot, ignore it
2157   if (n != _unconditional_delay_slot) {
2158 
2159     if (delay == 0) {
2160       if (node_pipeline->hasMultipleBundles()) {
2161 #ifndef PRODUCT
2162         if (_cfg->C->trace_opto_output())
2163           tty->print("#  *** STEP(multiple instructions) ***\n");
2164 #endif
2165         step(1);
2166       }
2167 
2168       else if (instruction_count + _bundle_instr_count > Pipeline::_max_instrs_per_cycle) {
2169 #ifndef PRODUCT
2170         if (_cfg->C->trace_opto_output())
2171           tty->print("#  *** STEP(%d >= %d instructions) ***\n",
2172             instruction_count + _bundle_instr_count,
2173             Pipeline::_max_instrs_per_cycle);
2174 #endif
2175         step(1);
2176       }
2177     }
2178 
2179     if (node_pipeline->hasBranchDelay() && !_unconditional_delay_slot)
2180       _bundle_instr_count++;
2181 
2182     // Set the node's latency
2183     _current_latency[n->_idx] = _bundle_cycle_number;
2184 
2185     // Now merge the functional unit information
2186     if (instruction_count > 0 || !node_pipeline->mayHaveNoCode())
2187       _bundle_use.add_usage(node_usage);
2188 
2189     // Increment the number of instructions in this bundle
2190     _bundle_instr_count += instruction_count;
2191 
2192     // Remember this node for later
2193     if (n->is_Mach())
2194       _next_node = n;
2195   }
2196 
2197   // It's possible to have a BoxLock in the graph and in the _bbs mapping but
2198   // not in the bb->_nodes array.  This happens for debug-info-only BoxLocks.
2199   // 'Schedule' them (basically ignore in the schedule) but do not insert them
2200   // into the block.  All other scheduled nodes get put in the schedule here.
2201   int op = n->Opcode();
2202   if( (op == Op_Node && n->req() == 0) || // anti-dependence node OR
2203       (op != Op_Node &&         // Not an unused antidepedence node and
2204        // not an unallocated boxlock
2205        (OptoReg::is_valid(_regalloc->get_reg_first(n)) || op != Op_BoxLock)) ) {
2206 
2207     // Push any trailing projections
2208     if( bb->get_node(bb->number_of_nodes()-1) != n ) {
2209       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2210         Node *foi = n->fast_out(i);
2211         if( foi->is_Proj() )
2212           _scheduled.push(foi);
2213       }
2214     }
2215 
2216     // Put the instruction in the schedule list
2217     _scheduled.push(n);
2218   }
2219 
2220 #ifndef PRODUCT
2221   if (_cfg->C->trace_opto_output())
2222     dump_available();
2223 #endif
2224 
2225   // Walk all the definitions, decrementing use counts, and
2226   // if a definition has a 0 use count, place it in the available list.
2227   DecrementUseCounts(n,bb);
2228 }
2229 
2230 // This method sets the use count within a basic block.  We will ignore all
2231 // uses outside the current basic block.  As we are doing a backwards walk,
2232 // any node we reach that has a use count of 0 may be scheduled.  This also
2233 // avoids the problem of cyclic references from phi nodes, as long as phi
2234 // nodes are at the front of the basic block.  This method also initializes
2235 // the available list to the set of instructions that have no uses within this
2236 // basic block.
2237 void Scheduling::ComputeUseCount(const Block *bb) {
2238 #ifndef PRODUCT
2239   if (_cfg->C->trace_opto_output())
2240     tty->print("# -> ComputeUseCount\n");
2241 #endif
2242 
2243   // Clear the list of available and scheduled instructions, just in case
2244   _available.clear();
2245   _scheduled.clear();
2246 
2247   // No delay slot specified
2248   _unconditional_delay_slot = NULL;
2249 
2250 #ifdef ASSERT
2251   for( uint i=0; i < bb->number_of_nodes(); i++ )
2252     assert( _uses[bb->get_node(i)->_idx] == 0, "_use array not clean" );
2253 #endif
2254 
2255   // Force the _uses count to never go to zero for unscheduable pieces
2256   // of the block
2257   for( uint k = 0; k < _bb_start; k++ )
2258     _uses[bb->get_node(k)->_idx] = 1;
2259   for( uint l = _bb_end; l < bb->number_of_nodes(); l++ )
2260     _uses[bb->get_node(l)->_idx] = 1;
2261 
2262   // Iterate backwards over the instructions in the block.  Don't count the
2263   // branch projections at end or the block header instructions.
2264   for( uint j = _bb_end-1; j >= _bb_start; j-- ) {
2265     Node *n = bb->get_node(j);
2266     if( n->is_Proj() ) continue; // Projections handled another way
2267 
2268     // Account for all uses
2269     for ( uint k = 0; k < n->len(); k++ ) {
2270       Node *inp = n->in(k);
2271       if (!inp) continue;
2272       assert(inp != n, "no cycles allowed" );
2273       if (_cfg->get_block_for_node(inp) == bb) { // Block-local use?
2274         if (inp->is_Proj()) { // Skip through Proj's
2275           inp = inp->in(0);
2276         }
2277         ++_uses[inp->_idx];     // Count 1 block-local use
2278       }
2279     }
2280 
2281     // If this instruction has a 0 use count, then it is available
2282     if (!_uses[n->_idx]) {
2283       _current_latency[n->_idx] = _bundle_cycle_number;
2284       AddNodeToAvailableList(n);
2285     }
2286 
2287 #ifndef PRODUCT
2288     if (_cfg->C->trace_opto_output()) {
2289       tty->print("#   uses: %3d: ", _uses[n->_idx]);
2290       n->dump();
2291     }
2292 #endif
2293   }
2294 
2295 #ifndef PRODUCT
2296   if (_cfg->C->trace_opto_output())
2297     tty->print("# <- ComputeUseCount\n");
2298 #endif
2299 }
2300 
2301 // This routine performs scheduling on each basic block in reverse order,
2302 // using instruction latencies and taking into account function unit
2303 // availability.
2304 void Scheduling::DoScheduling() {
2305 #ifndef PRODUCT
2306   if (_cfg->C->trace_opto_output())
2307     tty->print("# -> DoScheduling\n");
2308 #endif
2309 
2310   Block *succ_bb = NULL;
2311   Block *bb;
2312 
2313   // Walk over all the basic blocks in reverse order
2314   for (int i = _cfg->number_of_blocks() - 1; i >= 0; succ_bb = bb, i--) {
2315     bb = _cfg->get_block(i);
2316 
2317 #ifndef PRODUCT
2318     if (_cfg->C->trace_opto_output()) {
2319       tty->print("#  Schedule BB#%03d (initial)\n", i);
2320       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2321         bb->get_node(j)->dump();
2322       }
2323     }
2324 #endif
2325 
2326     // On the head node, skip processing
2327     if (bb == _cfg->get_root_block()) {
2328       continue;
2329     }
2330 
2331     // Skip empty, connector blocks
2332     if (bb->is_connector())
2333       continue;
2334 
2335     // If the following block is not the sole successor of
2336     // this one, then reset the pipeline information
2337     if (bb->_num_succs != 1 || bb->non_connector_successor(0) != succ_bb) {
2338 #ifndef PRODUCT
2339       if (_cfg->C->trace_opto_output()) {
2340         tty->print("*** bundle start of next BB, node %d, for %d instructions\n",
2341                    _next_node->_idx, _bundle_instr_count);
2342       }
2343 #endif
2344       step_and_clear();
2345     }
2346 
2347     // Leave untouched the starting instruction, any Phis, a CreateEx node
2348     // or Top.  bb->get_node(_bb_start) is the first schedulable instruction.
2349     _bb_end = bb->number_of_nodes()-1;
2350     for( _bb_start=1; _bb_start <= _bb_end; _bb_start++ ) {
2351       Node *n = bb->get_node(_bb_start);
2352       // Things not matched, like Phinodes and ProjNodes don't get scheduled.
2353       // Also, MachIdealNodes do not get scheduled
2354       if( !n->is_Mach() ) continue;     // Skip non-machine nodes
2355       MachNode *mach = n->as_Mach();
2356       int iop = mach->ideal_Opcode();
2357       if( iop == Op_CreateEx ) continue; // CreateEx is pinned
2358       if( iop == Op_Con ) continue;      // Do not schedule Top
2359       if( iop == Op_Node &&     // Do not schedule PhiNodes, ProjNodes
2360           mach->pipeline() == MachNode::pipeline_class() &&
2361           !n->is_SpillCopy() && !n->is_MachMerge() )  // Breakpoints, Prolog, etc
2362         continue;
2363       break;                    // Funny loop structure to be sure...
2364     }
2365     // Compute last "interesting" instruction in block - last instruction we
2366     // might schedule.  _bb_end points just after last schedulable inst.  We
2367     // normally schedule conditional branches (despite them being forced last
2368     // in the block), because they have delay slots we can fill.  Calls all
2369     // have their delay slots filled in the template expansions, so we don't
2370     // bother scheduling them.
2371     Node *last = bb->get_node(_bb_end);
2372     // Ignore trailing NOPs.
2373     while (_bb_end > 0 && last->is_Mach() &&
2374            last->as_Mach()->ideal_Opcode() == Op_Con) {
2375       last = bb->get_node(--_bb_end);
2376     }
2377     assert(!last->is_Mach() || last->as_Mach()->ideal_Opcode() != Op_Con, "");
2378     if( last->is_Catch() ||
2379        // Exclude unreachable path case when Halt node is in a separate block.
2380        (_bb_end > 1 && last->is_Mach() && last->as_Mach()->ideal_Opcode() == Op_Halt) ) {
2381       // There must be a prior call.  Skip it.
2382       while( !bb->get_node(--_bb_end)->is_MachCall() ) {
2383         assert( bb->get_node(_bb_end)->is_MachProj(), "skipping projections after expected call" );
2384       }
2385     } else if( last->is_MachNullCheck() ) {
2386       // Backup so the last null-checked memory instruction is
2387       // outside the schedulable range. Skip over the nullcheck,
2388       // projection, and the memory nodes.
2389       Node *mem = last->in(1);
2390       do {
2391         _bb_end--;
2392       } while (mem != bb->get_node(_bb_end));
2393     } else {
2394       // Set _bb_end to point after last schedulable inst.
2395       _bb_end++;
2396     }
2397 
2398     assert( _bb_start <= _bb_end, "inverted block ends" );
2399 
2400     // Compute the register antidependencies for the basic block
2401     ComputeRegisterAntidependencies(bb);
2402     if (_cfg->C->failing())  return;  // too many D-U pinch points
2403 
2404     // Compute intra-bb latencies for the nodes
2405     ComputeLocalLatenciesForward(bb);
2406 
2407     // Compute the usage within the block, and set the list of all nodes
2408     // in the block that have no uses within the block.
2409     ComputeUseCount(bb);
2410 
2411     // Schedule the remaining instructions in the block
2412     while ( _available.size() > 0 ) {
2413       Node *n = ChooseNodeToBundle();
2414       guarantee(n != NULL, "no nodes available");
2415       AddNodeToBundle(n,bb);
2416     }
2417 
2418     assert( _scheduled.size() == _bb_end - _bb_start, "wrong number of instructions" );
2419 #ifdef ASSERT
2420     for( uint l = _bb_start; l < _bb_end; l++ ) {
2421       Node *n = bb->get_node(l);
2422       uint m;
2423       for( m = 0; m < _bb_end-_bb_start; m++ )
2424         if( _scheduled[m] == n )
2425           break;
2426       assert( m < _bb_end-_bb_start, "instruction missing in schedule" );
2427     }
2428 #endif
2429 
2430     // Now copy the instructions (in reverse order) back to the block
2431     for ( uint k = _bb_start; k < _bb_end; k++ )
2432       bb->map_node(_scheduled[_bb_end-k-1], k);
2433 
2434 #ifndef PRODUCT
2435     if (_cfg->C->trace_opto_output()) {
2436       tty->print("#  Schedule BB#%03d (final)\n", i);
2437       uint current = 0;
2438       for (uint j = 0; j < bb->number_of_nodes(); j++) {
2439         Node *n = bb->get_node(j);
2440         if( valid_bundle_info(n) ) {
2441           Bundle *bundle = node_bundling(n);
2442           if (bundle->instr_count() > 0 || bundle->flags() > 0) {
2443             tty->print("*** Bundle: ");
2444             bundle->dump();
2445           }
2446           n->dump();
2447         }
2448       }
2449     }
2450 #endif
2451 #ifdef ASSERT
2452   verify_good_schedule(bb,"after block local scheduling");
2453 #endif
2454   }
2455 
2456 #ifndef PRODUCT
2457   if (_cfg->C->trace_opto_output())
2458     tty->print("# <- DoScheduling\n");
2459 #endif
2460 
2461   // Record final node-bundling array location
2462   _regalloc->C->set_node_bundling_base(_node_bundling_base);
2463 
2464 } // end DoScheduling
2465 
2466 // Verify that no live-range used in the block is killed in the block by a
2467 // wrong DEF.  This doesn't verify live-ranges that span blocks.
2468 
2469 // Check for edge existence.  Used to avoid adding redundant precedence edges.
2470 static bool edge_from_to( Node *from, Node *to ) {
2471   for( uint i=0; i<from->len(); i++ )
2472     if( from->in(i) == to )
2473       return true;
2474   return false;
2475 }
2476 
2477 #ifdef ASSERT
2478 void Scheduling::verify_do_def( Node *n, OptoReg::Name def, const char *msg ) {
2479   // Check for bad kills
2480   if( OptoReg::is_valid(def) ) { // Ignore stores & control flow
2481     Node *prior_use = _reg_node[def];
2482     if( prior_use && !edge_from_to(prior_use,n) ) {
2483       tty->print("%s = ",OptoReg::as_VMReg(def)->name());
2484       n->dump();
2485       tty->print_cr("...");
2486       prior_use->dump();
2487       assert(edge_from_to(prior_use,n),msg);
2488     }
2489     _reg_node.map(def,NULL); // Kill live USEs
2490   }
2491 }
2492 
2493 void Scheduling::verify_good_schedule( Block *b, const char *msg ) {
2494 
2495   // Zap to something reasonable for the verify code
2496   _reg_node.clear();
2497 
2498   // Walk over the block backwards.  Check to make sure each DEF doesn't
2499   // kill a live value (other than the one it's supposed to).  Add each
2500   // USE to the live set.
2501   for( uint i = b->number_of_nodes()-1; i >= _bb_start; i-- ) {
2502     Node *n = b->get_node(i);
2503     int n_op = n->Opcode();
2504     if( n_op == Op_MachProj && n->ideal_reg() == MachProjNode::fat_proj ) {
2505       // Fat-proj kills a slew of registers
2506       RegMask rm = n->out_RegMask();// Make local copy
2507       while( rm.is_NotEmpty() ) {
2508         OptoReg::Name kill = rm.find_first_elem();
2509         rm.Remove(kill);
2510         verify_do_def( n, kill, msg );
2511       }
2512     } else if( n_op != Op_Node ) { // Avoid brand new antidependence nodes
2513       // Get DEF'd registers the normal way
2514       verify_do_def( n, _regalloc->get_reg_first(n), msg );
2515       verify_do_def( n, _regalloc->get_reg_second(n), msg );
2516     }
2517 
2518     // Now make all USEs live
2519     for( uint i=1; i<n->req(); i++ ) {
2520       Node *def = n->in(i);
2521       assert(def != 0, "input edge required");
2522       OptoReg::Name reg_lo = _regalloc->get_reg_first(def);
2523       OptoReg::Name reg_hi = _regalloc->get_reg_second(def);
2524       if( OptoReg::is_valid(reg_lo) ) {
2525         assert(!_reg_node[reg_lo] || edge_from_to(_reg_node[reg_lo],def), msg);
2526         _reg_node.map(reg_lo,n);
2527       }
2528       if( OptoReg::is_valid(reg_hi) ) {
2529         assert(!_reg_node[reg_hi] || edge_from_to(_reg_node[reg_hi],def), msg);
2530         _reg_node.map(reg_hi,n);
2531       }
2532     }
2533 
2534   }
2535 
2536   // Zap to something reasonable for the Antidependence code
2537   _reg_node.clear();
2538 }
2539 #endif
2540 
2541 // Conditionally add precedence edges.  Avoid putting edges on Projs.
2542 static void add_prec_edge_from_to( Node *from, Node *to ) {
2543   if( from->is_Proj() ) {       // Put precedence edge on Proj's input
2544     assert( from->req() == 1 && (from->len() == 1 || from->in(1)==0), "no precedence edges on projections" );
2545     from = from->in(0);
2546   }
2547   if( from != to &&             // No cycles (for things like LD L0,[L0+4] )
2548       !edge_from_to( from, to ) ) // Avoid duplicate edge
2549     from->add_prec(to);
2550 }
2551 
2552 void Scheduling::anti_do_def( Block *b, Node *def, OptoReg::Name def_reg, int is_def ) {
2553   if( !OptoReg::is_valid(def_reg) ) // Ignore stores & control flow
2554     return;
2555 
2556   Node *pinch = _reg_node[def_reg]; // Get pinch point
2557   if ((pinch == NULL) || _cfg->get_block_for_node(pinch) != b || // No pinch-point yet?
2558       is_def ) {    // Check for a true def (not a kill)
2559     _reg_node.map(def_reg,def); // Record def/kill as the optimistic pinch-point
2560     return;
2561   }
2562 
2563   Node *kill = def;             // Rename 'def' to more descriptive 'kill'
2564   debug_only( def = (Node*)0xdeadbeef; )
2565 
2566   // After some number of kills there _may_ be a later def
2567   Node *later_def = NULL;
2568 
2569   // Finding a kill requires a real pinch-point.
2570   // Check for not already having a pinch-point.
2571   // Pinch points are Op_Node's.
2572   if( pinch->Opcode() != Op_Node ) { // Or later-def/kill as pinch-point?
2573     later_def = pinch;            // Must be def/kill as optimistic pinch-point
2574     if ( _pinch_free_list.size() > 0) {
2575       pinch = _pinch_free_list.pop();
2576     } else {
2577       pinch = new Node(1); // Pinch point to-be
2578     }
2579     if (pinch->_idx >= _regalloc->node_regs_max_index()) {
2580       _cfg->C->record_method_not_compilable("too many D-U pinch points");
2581       return;
2582     }
2583     _cfg->map_node_to_block(pinch, b);      // Pretend it's valid in this block (lazy init)
2584     _reg_node.map(def_reg,pinch); // Record pinch-point
2585     //_regalloc->set_bad(pinch->_idx); // Already initialized this way.
2586     if( later_def->outcnt() == 0 || later_def->ideal_reg() == MachProjNode::fat_proj ) { // Distinguish def from kill
2587       pinch->init_req(0, _cfg->C->top());     // set not NULL for the next call
2588       add_prec_edge_from_to(later_def,pinch); // Add edge from kill to pinch
2589       later_def = NULL;           // and no later def
2590     }
2591     pinch->set_req(0,later_def);  // Hook later def so we can find it
2592   } else {                        // Else have valid pinch point
2593     if( pinch->in(0) )            // If there is a later-def
2594       later_def = pinch->in(0);   // Get it
2595   }
2596 
2597   // Add output-dependence edge from later def to kill
2598   if( later_def )               // If there is some original def
2599     add_prec_edge_from_to(later_def,kill); // Add edge from def to kill
2600 
2601   // See if current kill is also a use, and so is forced to be the pinch-point.
2602   if( pinch->Opcode() == Op_Node ) {
2603     Node *uses = kill->is_Proj() ? kill->in(0) : kill;
2604     for( uint i=1; i<uses->req(); i++ ) {
2605       if( _regalloc->get_reg_first(uses->in(i)) == def_reg ||
2606           _regalloc->get_reg_second(uses->in(i)) == def_reg ) {
2607         // Yes, found a use/kill pinch-point
2608         pinch->set_req(0,NULL);  //
2609         pinch->replace_by(kill); // Move anti-dep edges up
2610         pinch = kill;
2611         _reg_node.map(def_reg,pinch);
2612         return;
2613       }
2614     }
2615   }
2616 
2617   // Add edge from kill to pinch-point
2618   add_prec_edge_from_to(kill,pinch);
2619 }
2620 
2621 void Scheduling::anti_do_use( Block *b, Node *use, OptoReg::Name use_reg ) {
2622   if( !OptoReg::is_valid(use_reg) ) // Ignore stores & control flow
2623     return;
2624   Node *pinch = _reg_node[use_reg]; // Get pinch point
2625   // Check for no later def_reg/kill in block
2626   if ((pinch != NULL) && _cfg->get_block_for_node(pinch) == b &&
2627       // Use has to be block-local as well
2628       _cfg->get_block_for_node(use) == b) {
2629     if( pinch->Opcode() == Op_Node && // Real pinch-point (not optimistic?)
2630         pinch->req() == 1 ) {   // pinch not yet in block?
2631       pinch->del_req(0);        // yank pointer to later-def, also set flag
2632       // Insert the pinch-point in the block just after the last use
2633       b->insert_node(pinch, b->find_node(use) + 1);
2634       _bb_end++;                // Increase size scheduled region in block
2635     }
2636 
2637     add_prec_edge_from_to(pinch,use);
2638   }
2639 }
2640 
2641 // We insert antidependences between the reads and following write of
2642 // allocated registers to prevent illegal code motion. Hopefully, the
2643 // number of added references should be fairly small, especially as we
2644 // are only adding references within the current basic block.
2645 void Scheduling::ComputeRegisterAntidependencies(Block *b) {
2646 
2647 #ifdef ASSERT
2648   verify_good_schedule(b,"before block local scheduling");
2649 #endif
2650 
2651   // A valid schedule, for each register independently, is an endless cycle
2652   // of: a def, then some uses (connected to the def by true dependencies),
2653   // then some kills (defs with no uses), finally the cycle repeats with a new
2654   // def.  The uses are allowed to float relative to each other, as are the
2655   // kills.  No use is allowed to slide past a kill (or def).  This requires
2656   // antidependencies between all uses of a single def and all kills that
2657   // follow, up to the next def.  More edges are redundant, because later defs
2658   // & kills are already serialized with true or antidependencies.  To keep
2659   // the edge count down, we add a 'pinch point' node if there's more than
2660   // one use or more than one kill/def.
2661 
2662   // We add dependencies in one bottom-up pass.
2663 
2664   // For each instruction we handle it's DEFs/KILLs, then it's USEs.
2665 
2666   // For each DEF/KILL, we check to see if there's a prior DEF/KILL for this
2667   // register.  If not, we record the DEF/KILL in _reg_node, the
2668   // register-to-def mapping.  If there is a prior DEF/KILL, we insert a
2669   // "pinch point", a new Node that's in the graph but not in the block.
2670   // We put edges from the prior and current DEF/KILLs to the pinch point.
2671   // We put the pinch point in _reg_node.  If there's already a pinch point
2672   // we merely add an edge from the current DEF/KILL to the pinch point.
2673 
2674   // After doing the DEF/KILLs, we handle USEs.  For each used register, we
2675   // put an edge from the pinch point to the USE.
2676 
2677   // To be expedient, the _reg_node array is pre-allocated for the whole
2678   // compilation.  _reg_node is lazily initialized; it either contains a NULL,
2679   // or a valid def/kill/pinch-point, or a leftover node from some prior
2680   // block.  Leftover node from some prior block is treated like a NULL (no
2681   // prior def, so no anti-dependence needed).  Valid def is distinguished by
2682   // it being in the current block.
2683   bool fat_proj_seen = false;
2684   uint last_safept = _bb_end-1;
2685   Node* end_node         = (_bb_end-1 >= _bb_start) ? b->get_node(last_safept) : NULL;
2686   Node* last_safept_node = end_node;
2687   for( uint i = _bb_end-1; i >= _bb_start; i-- ) {
2688     Node *n = b->get_node(i);
2689     int is_def = n->outcnt();   // def if some uses prior to adding precedence edges
2690     if( n->is_MachProj() && n->ideal_reg() == MachProjNode::fat_proj ) {
2691       // Fat-proj kills a slew of registers
2692       // This can add edges to 'n' and obscure whether or not it was a def,
2693       // hence the is_def flag.
2694       fat_proj_seen = true;
2695       RegMask rm = n->out_RegMask();// Make local copy
2696       while( rm.is_NotEmpty() ) {
2697         OptoReg::Name kill = rm.find_first_elem();
2698         rm.Remove(kill);
2699         anti_do_def( b, n, kill, is_def );
2700       }
2701     } else {
2702       // Get DEF'd registers the normal way
2703       anti_do_def( b, n, _regalloc->get_reg_first(n), is_def );
2704       anti_do_def( b, n, _regalloc->get_reg_second(n), is_def );
2705     }
2706 
2707     // Kill projections on a branch should appear to occur on the
2708     // branch, not afterwards, so grab the masks from the projections
2709     // and process them.
2710     if (n->is_MachBranch() || n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_Jump) {
2711       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2712         Node* use = n->fast_out(i);
2713         if (use->is_Proj()) {
2714           RegMask rm = use->out_RegMask();// Make local copy
2715           while( rm.is_NotEmpty() ) {
2716             OptoReg::Name kill = rm.find_first_elem();
2717             rm.Remove(kill);
2718             anti_do_def( b, n, kill, false );
2719           }
2720         }
2721       }
2722     }
2723 
2724     // Check each register used by this instruction for a following DEF/KILL
2725     // that must occur afterward and requires an anti-dependence edge.
2726     for( uint j=0; j<n->req(); j++ ) {
2727       Node *def = n->in(j);
2728       if( def ) {
2729         assert( !def->is_MachProj() || def->ideal_reg() != MachProjNode::fat_proj, "" );
2730         anti_do_use( b, n, _regalloc->get_reg_first(def) );
2731         anti_do_use( b, n, _regalloc->get_reg_second(def) );
2732       }
2733     }
2734     // Do not allow defs of new derived values to float above GC
2735     // points unless the base is definitely available at the GC point.
2736 
2737     Node *m = b->get_node(i);
2738 
2739     // Add precedence edge from following safepoint to use of derived pointer
2740     if( last_safept_node != end_node &&
2741         m != last_safept_node) {
2742       for (uint k = 1; k < m->req(); k++) {
2743         const Type *t = m->in(k)->bottom_type();
2744         if( t->isa_oop_ptr() &&
2745             t->is_ptr()->offset() != 0 ) {
2746           last_safept_node->add_prec( m );
2747           break;
2748         }
2749       }
2750     }
2751 
2752     if( n->jvms() ) {           // Precedence edge from derived to safept
2753       // Check if last_safept_node was moved by pinch-point insertion in anti_do_use()
2754       if( b->get_node(last_safept) != last_safept_node ) {
2755         last_safept = b->find_node(last_safept_node);
2756       }
2757       for( uint j=last_safept; j > i; j-- ) {
2758         Node *mach = b->get_node(j);
2759         if( mach->is_Mach() && mach->as_Mach()->ideal_Opcode() == Op_AddP )
2760           mach->add_prec( n );
2761       }
2762       last_safept = i;
2763       last_safept_node = m;
2764     }
2765   }
2766 
2767   if (fat_proj_seen) {
2768     // Garbage collect pinch nodes that were not consumed.
2769     // They are usually created by a fat kill MachProj for a call.
2770     garbage_collect_pinch_nodes();
2771   }
2772 }
2773 
2774 // Garbage collect pinch nodes for reuse by other blocks.
2775 //
2776 // The block scheduler's insertion of anti-dependence
2777 // edges creates many pinch nodes when the block contains
2778 // 2 or more Calls.  A pinch node is used to prevent a
2779 // combinatorial explosion of edges.  If a set of kills for a
2780 // register is anti-dependent on a set of uses (or defs), rather
2781 // than adding an edge in the graph between each pair of kill
2782 // and use (or def), a pinch is inserted between them:
2783 //
2784 //            use1   use2  use3
2785 //                \   |   /
2786 //                 \  |  /
2787 //                  pinch
2788 //                 /  |  \
2789 //                /   |   \
2790 //            kill1 kill2 kill3
2791 //
2792 // One pinch node is created per register killed when
2793 // the second call is encountered during a backwards pass
2794 // over the block.  Most of these pinch nodes are never
2795 // wired into the graph because the register is never
2796 // used or def'ed in the block.
2797 //
2798 void Scheduling::garbage_collect_pinch_nodes() {
2799 #ifndef PRODUCT
2800     if (_cfg->C->trace_opto_output()) tty->print("Reclaimed pinch nodes:");
2801 #endif
2802     int trace_cnt = 0;
2803     for (uint k = 0; k < _reg_node.Size(); k++) {
2804       Node* pinch = _reg_node[k];
2805       if ((pinch != NULL) && pinch->Opcode() == Op_Node &&
2806           // no predecence input edges
2807           (pinch->req() == pinch->len() || pinch->in(pinch->req()) == NULL) ) {
2808         cleanup_pinch(pinch);
2809         _pinch_free_list.push(pinch);
2810         _reg_node.map(k, NULL);
2811 #ifndef PRODUCT
2812         if (_cfg->C->trace_opto_output()) {
2813           trace_cnt++;
2814           if (trace_cnt > 40) {
2815             tty->print("\n");
2816             trace_cnt = 0;
2817           }
2818           tty->print(" %d", pinch->_idx);
2819         }
2820 #endif
2821       }
2822     }
2823 #ifndef PRODUCT
2824     if (_cfg->C->trace_opto_output()) tty->print("\n");
2825 #endif
2826 }
2827 
2828 // Clean up a pinch node for reuse.
2829 void Scheduling::cleanup_pinch( Node *pinch ) {
2830   assert (pinch && pinch->Opcode() == Op_Node && pinch->req() == 1, "just checking");
2831 
2832   for (DUIterator_Last imin, i = pinch->last_outs(imin); i >= imin; ) {
2833     Node* use = pinch->last_out(i);
2834     uint uses_found = 0;
2835     for (uint j = use->req(); j < use->len(); j++) {
2836       if (use->in(j) == pinch) {
2837         use->rm_prec(j);
2838         uses_found++;
2839       }
2840     }
2841     assert(uses_found > 0, "must be a precedence edge");
2842     i -= uses_found;    // we deleted 1 or more copies of this edge
2843   }
2844   // May have a later_def entry
2845   pinch->set_req(0, NULL);
2846 }
2847 
2848 #ifndef PRODUCT
2849 
2850 void Scheduling::dump_available() const {
2851   tty->print("#Availist  ");
2852   for (uint i = 0; i < _available.size(); i++)
2853     tty->print(" N%d/l%d", _available[i]->_idx,_current_latency[_available[i]->_idx]);
2854   tty->cr();
2855 }
2856 
2857 // Print Scheduling Statistics
2858 void Scheduling::print_statistics() {
2859   // Print the size added by nops for bundling
2860   tty->print("Nops added %d bytes to total of %d bytes",
2861     _total_nop_size, _total_method_size);
2862   if (_total_method_size > 0)
2863     tty->print(", for %.2f%%",
2864       ((double)_total_nop_size) / ((double) _total_method_size) * 100.0);
2865   tty->print("\n");
2866 
2867   // Print the number of branch shadows filled
2868   if (Pipeline::_branch_has_delay_slot) {
2869     tty->print("Of %d branches, %d had unconditional delay slots filled",
2870       _total_branches, _total_unconditional_delays);
2871     if (_total_branches > 0)
2872       tty->print(", for %.2f%%",
2873         ((double)_total_unconditional_delays) / ((double)_total_branches) * 100.0);
2874     tty->print("\n");
2875   }
2876 
2877   uint total_instructions = 0, total_bundles = 0;
2878 
2879   for (uint i = 1; i <= Pipeline::_max_instrs_per_cycle; i++) {
2880     uint bundle_count   = _total_instructions_per_bundle[i];
2881     total_instructions += bundle_count * i;
2882     total_bundles      += bundle_count;
2883   }
2884 
2885   if (total_bundles > 0)
2886     tty->print("Average ILP (excluding nops) is %.2f\n",
2887       ((double)total_instructions) / ((double)total_bundles));
2888 }
2889 #endif