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