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