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