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