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