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