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