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