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