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