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