1 /*
   2  * Copyright (c) 2000, 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 "compiler/compileLog.hpp"
  26 #include "compiler/oopMap.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/block.hpp"
  31 #include "opto/callnode.hpp"
  32 #include "opto/cfgnode.hpp"
  33 #include "opto/chaitin.hpp"
  34 #include "opto/coalesce.hpp"
  35 #include "opto/connode.hpp"
  36 #include "opto/idealGraphPrinter.hpp"
  37 #include "opto/indexSet.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/memnode.hpp"
  40 #include "opto/movenode.hpp"
  41 #include "opto/opcodes.hpp"
  42 #include "opto/rootnode.hpp"
  43 #include "utilities/align.hpp"
  44 
  45 #ifndef PRODUCT
  46 void LRG::dump() const {
  47   ttyLocker ttyl;
  48   tty->print("%d ",num_regs());
  49   _mask.dump();
  50   if( _msize_valid ) {
  51     if( mask_size() == compute_mask_size() ) tty->print(", #%d ",_mask_size);
  52     else tty->print(", #!!!_%d_vs_%d ",_mask_size,_mask.Size());
  53   } else {
  54     tty->print(", #?(%d) ",_mask.Size());
  55   }
  56 
  57   tty->print("EffDeg: ");
  58   if( _degree_valid ) tty->print( "%d ", _eff_degree );
  59   else tty->print("? ");
  60 
  61   if( is_multidef() ) {
  62     tty->print("MultiDef ");
  63     if (_defs != nullptr) {
  64       tty->print("(");
  65       for (int i = 0; i < _defs->length(); i++) {
  66         tty->print("N%d ", _defs->at(i)->_idx);
  67       }
  68       tty->print(") ");
  69     }
  70   }
  71   else if( _def == nullptr ) tty->print("Dead ");
  72   else tty->print("Def: N%d ",_def->_idx);
  73 
  74   tty->print("Cost:%4.2g Area:%4.2g Score:%4.2g ",_cost,_area, score());
  75   // Flags
  76   if( _is_oop ) tty->print("Oop ");
  77   if( _is_float ) tty->print("Float ");
  78   if( _is_vector ) tty->print("Vector ");
  79   if( _is_predicate ) tty->print("Predicate ");
  80   if( _is_scalable ) tty->print("Scalable ");
  81   if( _was_spilled1 ) tty->print("Spilled ");
  82   if( _was_spilled2 ) tty->print("Spilled2 ");
  83   if( _direct_conflict ) tty->print("Direct_conflict ");
  84   if( _fat_proj ) tty->print("Fat ");
  85   if( _was_lo ) tty->print("Lo ");
  86   if( _has_copy ) tty->print("Copy ");
  87   if( _at_risk ) tty->print("Risk ");
  88 
  89   if( _must_spill ) tty->print("Must_spill ");
  90   if( _is_bound ) tty->print("Bound ");
  91   if( _msize_valid ) {
  92     if( _degree_valid && lo_degree() ) tty->print("Trivial ");
  93   }
  94 
  95   tty->cr();
  96 }
  97 #endif
  98 
  99 // Compute score from cost and area.  Low score is best to spill.
 100 static double raw_score( double cost, double area ) {
 101   return cost - (area*RegisterCostAreaRatio) * 1.52588e-5;
 102 }
 103 
 104 double LRG::score() const {
 105   // Scale _area by RegisterCostAreaRatio/64K then subtract from cost.
 106   // Bigger area lowers score, encourages spilling this live range.
 107   // Bigger cost raise score, prevents spilling this live range.
 108   // (Note: 1/65536 is the magic constant below; I dont trust the C optimizer
 109   // to turn a divide by a constant into a multiply by the reciprical).
 110   double score = raw_score( _cost, _area);
 111 
 112   // Account for area.  Basically, LRGs covering large areas are better
 113   // to spill because more other LRGs get freed up.
 114   if( _area == 0.0 )            // No area?  Then no progress to spill
 115     return 1e35;
 116 
 117   if( _was_spilled2 )           // If spilled once before, we are unlikely
 118     return score + 1e30;        // to make progress again.
 119 
 120   if( _cost >= _area*3.0 )      // Tiny area relative to cost
 121     return score + 1e17;        // Probably no progress to spill
 122 
 123   if( (_cost+_cost) >= _area*3.0 ) // Small area relative to cost
 124     return score + 1e10;        // Likely no progress to spill
 125 
 126   return score;
 127 }
 128 
 129 #define NUMBUCKS 3
 130 
 131 // Straight out of Tarjan's union-find algorithm
 132 uint LiveRangeMap::find_compress(uint lrg) {
 133   uint cur = lrg;
 134   uint next = _uf_map.at(cur);
 135   while (next != cur) { // Scan chain of equivalences
 136     assert( next < cur, "always union smaller");
 137     cur = next; // until find a fixed-point
 138     next = _uf_map.at(cur);
 139   }
 140 
 141   // Core of union-find algorithm: update chain of
 142   // equivalences to be equal to the root.
 143   while (lrg != next) {
 144     uint tmp = _uf_map.at(lrg);
 145     _uf_map.at_put(lrg, next);
 146     lrg = tmp;
 147   }
 148   return lrg;
 149 }
 150 
 151 // Reset the Union-Find map to identity
 152 void LiveRangeMap::reset_uf_map(uint max_lrg_id) {
 153   _max_lrg_id= max_lrg_id;
 154   // Force the Union-Find mapping to be at least this large
 155   _uf_map.at_put_grow(_max_lrg_id, 0);
 156   // Initialize it to be the ID mapping.
 157   for (uint i = 0; i < _max_lrg_id; ++i) {
 158     _uf_map.at_put(i, i);
 159   }
 160 }
 161 
 162 // Make all Nodes map directly to their final live range; no need for
 163 // the Union-Find mapping after this call.
 164 void LiveRangeMap::compress_uf_map_for_nodes() {
 165   // For all Nodes, compress mapping
 166   uint unique = _names.length();
 167   for (uint i = 0; i < unique; ++i) {
 168     uint lrg = _names.at(i);
 169     uint compressed_lrg = find(lrg);
 170     if (lrg != compressed_lrg) {
 171       _names.at_put(i, compressed_lrg);
 172     }
 173   }
 174 }
 175 
 176 // Like Find above, but no path compress, so bad asymptotic behavior
 177 uint LiveRangeMap::find_const(uint lrg) const {
 178   if (!lrg) {
 179     return lrg; // Ignore the zero LRG
 180   }
 181 
 182   // Off the end?  This happens during debugging dumps when you got
 183   // brand new live ranges but have not told the allocator yet.
 184   if (lrg >= _max_lrg_id) {
 185     return lrg;
 186   }
 187 
 188   uint next = _uf_map.at(lrg);
 189   while (next != lrg) { // Scan chain of equivalences
 190     assert(next < lrg, "always union smaller");
 191     lrg = next; // until find a fixed-point
 192     next = _uf_map.at(lrg);
 193   }
 194   return next;
 195 }
 196 
 197 PhaseChaitin::PhaseChaitin(uint unique, PhaseCFG &cfg, Matcher &matcher, bool scheduling_info_generated)
 198   : PhaseRegAlloc(unique, cfg, matcher,
 199 #ifndef PRODUCT
 200        print_chaitin_statistics
 201 #else
 202        nullptr
 203 #endif
 204        )
 205   , _live(nullptr)
 206   , _lo_degree(0), _lo_stk_degree(0), _hi_degree(0), _simplified(0)
 207   , _oldphi(unique)
 208 #ifndef PRODUCT
 209   , _trace_spilling(C->directive()->TraceSpillingOption)
 210 #endif
 211   , _lrg_map(Thread::current()->resource_area(), unique)
 212   , _scheduling_info_generated(scheduling_info_generated)
 213   , _sched_int_pressure(0, Matcher::int_pressure_limit())
 214   , _sched_float_pressure(0, Matcher::float_pressure_limit())
 215   , _scratch_int_pressure(0, Matcher::int_pressure_limit())
 216   , _scratch_float_pressure(0, Matcher::float_pressure_limit())
 217 {
 218   Compile::TracePhase tp(_t_ctorChaitin);
 219 
 220   _high_frequency_lrg = MIN2(double(OPTO_LRG_HIGH_FREQ), _cfg.get_outer_loop_frequency());
 221 
 222   // Build a list of basic blocks, sorted by frequency
 223   // Experiment with sorting strategies to speed compilation
 224   uint nr_blocks = _cfg.number_of_blocks();
 225   double  cutoff = BLOCK_FREQUENCY(1.0); // Cutoff for high frequency bucket
 226   Block **buckets[NUMBUCKS];             // Array of buckets
 227   uint    buckcnt[NUMBUCKS];             // Array of bucket counters
 228   double  buckval[NUMBUCKS];             // Array of bucket value cutoffs
 229 
 230   // The space which our buckets point into.
 231   Block** start = NEW_RESOURCE_ARRAY(Block *, nr_blocks*NUMBUCKS);
 232 
 233   for (uint i = 0; i < NUMBUCKS; i++) {
 234     buckets[i] = &start[i*nr_blocks];
 235     buckcnt[i] = 0;
 236     // Bump by three orders of magnitude each time
 237     cutoff *= 0.001;
 238     buckval[i] = cutoff;
 239   }
 240 
 241   // Sort blocks into buckets
 242   for (uint i = 0; i < nr_blocks; i++) {
 243     for (uint j = 0; j < NUMBUCKS; j++) {
 244       double bval = buckval[j];
 245       Block* blk = _cfg.get_block(i);
 246       if (j == NUMBUCKS - 1 || blk->_freq > bval) {
 247         uint cnt = buckcnt[j];
 248         // Assign block to end of list for appropriate bucket
 249         buckets[j][cnt] = blk;
 250         buckcnt[j] = cnt+1;
 251         break; // kick out of inner loop
 252       }
 253     }
 254   }
 255 
 256   // Squash the partially filled buckets together into the first one.
 257   static_assert(NUMBUCKS >= 2, "must"); // If this isn't true then it'll mess up the squashing.
 258   Block** offset = &buckets[0][buckcnt[0]];
 259   for (int i = 1; i < NUMBUCKS; i++) {
 260     ::memmove(offset, buckets[i], buckcnt[i]*sizeof(Block*));
 261     offset += buckcnt[i];
 262   }
 263   assert((&buckets[0][0] + nr_blocks) == offset, "should be");
 264 
 265   // Free the now unused memory
 266   FREE_RESOURCE_ARRAY(Block*, buckets[1], (NUMBUCKS-1)*nr_blocks);
 267   // Finally, point the _blks to our memory
 268   _blks = buckets[0];
 269 
 270 #ifdef ASSERT
 271   uint blkcnt = 0;
 272   for (uint i = 0; i < NUMBUCKS; i++) {
 273     blkcnt += buckcnt[i];
 274   }
 275   assert(blkcnt == nr_blocks, "Block array not totally filled");
 276 #endif
 277 }
 278 
 279 // union 2 sets together.
 280 void PhaseChaitin::Union( const Node *src_n, const Node *dst_n ) {
 281   uint src = _lrg_map.find(src_n);
 282   uint dst = _lrg_map.find(dst_n);
 283   assert(src, "");
 284   assert(dst, "");
 285   assert(src < _lrg_map.max_lrg_id(), "oob");
 286   assert(dst < _lrg_map.max_lrg_id(), "oob");
 287   assert(src < dst, "always union smaller");
 288   _lrg_map.uf_map(dst, src);
 289 }
 290 
 291 void PhaseChaitin::new_lrg(const Node *x, uint lrg) {
 292   // Make the Node->LRG mapping
 293   _lrg_map.extend(x->_idx,lrg);
 294   // Make the Union-Find mapping an identity function
 295   _lrg_map.uf_extend(lrg, lrg);
 296 }
 297 
 298 
 299 int PhaseChaitin::clone_projs(Block* b, uint idx, Node* orig, Node* copy, uint& max_lrg_id) {
 300   assert(b->find_node(copy) == (idx - 1), "incorrect insert index for copy kill projections");
 301   DEBUG_ONLY( Block* borig = _cfg.get_block_for_node(orig); )
 302   int found_projs = 0;
 303   uint cnt = orig->outcnt();
 304   for (uint i = 0; i < cnt; i++) {
 305     Node* proj = orig->raw_out(i);
 306     if (proj->is_MachProj()) {
 307       assert(proj->outcnt() == 0, "only kill projections are expected here");
 308       assert(_cfg.get_block_for_node(proj) == borig, "incorrect block for kill projections");
 309       found_projs++;
 310       // Copy kill projections after the cloned node
 311       Node* kills = proj->clone();
 312       kills->set_req(0, copy);
 313       b->insert_node(kills, idx++);
 314       _cfg.map_node_to_block(kills, b);
 315       new_lrg(kills, max_lrg_id++);
 316     }
 317   }
 318   return found_projs;
 319 }
 320 
 321 // Renumber the live ranges to compact them.  Makes the IFG smaller.
 322 void PhaseChaitin::compact() {
 323   Compile::TracePhase tp(_t_chaitinCompact);
 324 
 325   // Current the _uf_map contains a series of short chains which are headed
 326   // by a self-cycle.  All the chains run from big numbers to little numbers.
 327   // The Find() call chases the chains & shortens them for the next Find call.
 328   // We are going to change this structure slightly.  Numbers above a moving
 329   // wave 'i' are unchanged.  Numbers below 'j' point directly to their
 330   // compacted live range with no further chaining.  There are no chains or
 331   // cycles below 'i', so the Find call no longer works.
 332   uint j=1;
 333   uint i;
 334   for (i = 1; i < _lrg_map.max_lrg_id(); i++) {
 335     uint lr = _lrg_map.uf_live_range_id(i);
 336     // Ignore unallocated live ranges
 337     if (!lr) {
 338       continue;
 339     }
 340     assert(lr <= i, "");
 341     _lrg_map.uf_map(i, ( lr == i ) ? j++ : _lrg_map.uf_live_range_id(lr));
 342   }
 343   // Now change the Node->LR mapping to reflect the compacted names
 344   uint unique = _lrg_map.size();
 345   for (i = 0; i < unique; i++) {
 346     uint lrg_id = _lrg_map.live_range_id(i);
 347     _lrg_map.map(i, _lrg_map.uf_live_range_id(lrg_id));
 348   }
 349 
 350   // Reset the Union-Find mapping
 351   _lrg_map.reset_uf_map(j);
 352 }
 353 
 354 void PhaseChaitin::Register_Allocate() {
 355 
 356   // Above the OLD FP (and in registers) are the incoming arguments.  Stack
 357   // slots in this area are called "arg_slots".  Above the NEW FP (and in
 358   // registers) is the outgoing argument area; above that is the spill/temp
 359   // area.  These are all "frame_slots".  Arg_slots start at the zero
 360   // stack_slots and count up to the known arg_size.  Frame_slots start at
 361   // the stack_slot #arg_size and go up.  After allocation I map stack
 362   // slots to actual offsets.  Stack-slots in the arg_slot area are biased
 363   // by the frame_size; stack-slots in the frame_slot area are biased by 0.
 364 
 365   _trip_cnt = 0;
 366   _alternate = 0;
 367   _matcher._allocation_started = true;
 368 
 369   ResourceArea split_arena(mtCompiler, Arena::Tag::tag_regsplit);     // Arena for Split local resources
 370   ResourceArea live_arena(mtCompiler, Arena::Tag::tag_reglive);     // Arena for liveness & IFG info
 371   ResourceMark rm(&live_arena);
 372 
 373   // Need live-ness for the IFG; need the IFG for coalescing.  If the
 374   // liveness is JUST for coalescing, then I can get some mileage by renaming
 375   // all copy-related live ranges low and then using the max copy-related
 376   // live range as a cut-off for LIVE and the IFG.  In other words, I can
 377   // build a subset of LIVE and IFG just for copies.
 378   PhaseLive live(_cfg, _lrg_map.names(), &live_arena, false);
 379 
 380   // Need IFG for coalescing and coloring
 381   PhaseIFG ifg(&live_arena);
 382   _ifg = &ifg;
 383 
 384   // Come out of SSA world to the Named world.  Assign (virtual) registers to
 385   // Nodes.  Use the same register for all inputs and the output of PhiNodes
 386   // - effectively ending SSA form.  This requires either coalescing live
 387   // ranges or inserting copies.  For the moment, we insert "virtual copies"
 388   // - we pretend there is a copy prior to each Phi in predecessor blocks.
 389   // We will attempt to coalesce such "virtual copies" before we manifest
 390   // them for real.
 391   de_ssa();
 392 
 393 #ifdef ASSERT
 394   // Verify the graph before RA.
 395   verify(&live_arena);
 396 #endif
 397 
 398   {
 399     Compile::TracePhase tp(_t_computeLive);
 400     _live = nullptr;              // Mark live as being not available
 401     rm.reset_to_mark();           // Reclaim working storage
 402     IndexSet::reset_memory(C, &live_arena);
 403     ifg.init(_lrg_map.max_lrg_id()); // Empty IFG
 404     gather_lrg_masks( false );    // Collect LRG masks
 405     live.compute(_lrg_map.max_lrg_id()); // Compute liveness
 406     _live = &live;                // Mark LIVE as being available
 407   }
 408 
 409   C->print_method(PHASE_INITIAL_LIVENESS, 4);
 410 
 411   // Base pointers are currently "used" by instructions which define new
 412   // derived pointers.  This makes base pointers live up to the where the
 413   // derived pointer is made, but not beyond.  Really, they need to be live
 414   // across any GC point where the derived value is live.  So this code looks
 415   // at all the GC points, and "stretches" the live range of any base pointer
 416   // to the GC point.
 417   if (stretch_base_pointer_live_ranges(&live_arena)) {
 418     Compile::TracePhase tp("computeLive (sbplr)", _t_computeLive);
 419     // Since some live range stretched, I need to recompute live
 420     _live = nullptr;
 421     rm.reset_to_mark();         // Reclaim working storage
 422     IndexSet::reset_memory(C, &live_arena);
 423     ifg.init(_lrg_map.max_lrg_id());
 424     gather_lrg_masks(false);
 425     live.compute(_lrg_map.max_lrg_id());
 426     _live = &live;
 427     C->print_method(PHASE_LIVE_RANGE_STRETCHING, 4);
 428   }
 429 
 430   // Create the interference graph using virtual copies
 431   build_ifg_virtual();  // Include stack slots this time
 432   if (C->failing()) {
 433     return;
 434   }
 435 
 436   // The IFG is/was triangular.  I am 'squaring it up' so Union can run
 437   // faster.  Union requires a 'for all' operation which is slow on the
 438   // triangular adjacency matrix (quick reminder: the IFG is 'sparse' -
 439   // meaning I can visit all the Nodes neighbors less than a Node in time
 440   // O(# of neighbors), but I have to visit all the Nodes greater than a
 441   // given Node and search them for an instance, i.e., time O(#MaxLRG)).
 442   _ifg->SquareUp();
 443 
 444   // Aggressive (but pessimistic) copy coalescing.
 445   // This pass works on virtual copies.  Any virtual copies which are not
 446   // coalesced get manifested as actual copies
 447   {
 448     Compile::TracePhase tp(_t_chaitinCoalesce1);
 449 
 450     PhaseAggressiveCoalesce coalesce(*this);
 451     coalesce.coalesce_driver();
 452     // Insert un-coalesced copies.  Visit all Phis.  Where inputs to a Phi do
 453     // not match the Phi itself, insert a copy.
 454     coalesce.insert_copies(_matcher);
 455     if (C->failing()) {
 456       return;
 457     }
 458   }
 459 
 460   // After aggressive coalesce, attempt a first cut at coloring.
 461   // To color, we need the IFG and for that we need LIVE.
 462   {
 463     Compile::TracePhase tp(_t_computeLive);
 464     _live = nullptr;
 465     rm.reset_to_mark();           // Reclaim working storage
 466     IndexSet::reset_memory(C, &live_arena);
 467     ifg.init(_lrg_map.max_lrg_id());
 468     gather_lrg_masks( true );
 469     live.compute(_lrg_map.max_lrg_id());
 470     _live = &live;
 471   }
 472 
 473   C->print_method(PHASE_AGGRESSIVE_COALESCING, 4);
 474 
 475   // Build physical interference graph
 476   uint must_spill = 0;
 477   must_spill = build_ifg_physical(&live_arena);
 478   if (C->failing()) {
 479     return;
 480   }
 481   // If we have a guaranteed spill, might as well spill now
 482   if (must_spill) {
 483     if(!_lrg_map.max_lrg_id()) {
 484       return;
 485     }
 486     // Bail out if unique gets too large (ie - unique > MaxNodeLimit)
 487     C->check_node_count(10*must_spill, "out of nodes before split");
 488     if (C->failing()) {
 489       return;
 490     }
 491 
 492     uint new_max_lrg_id = Split(_lrg_map.max_lrg_id(), &split_arena);  // Split spilling LRG everywhere
 493     if (C->failing()) {
 494       return;
 495     }
 496     _lrg_map.set_max_lrg_id(new_max_lrg_id);
 497     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
 498     // or we failed to split
 499     C->check_node_count(2*NodeLimitFudgeFactor, "out of nodes after physical split");
 500     if (C->failing()) {
 501       return;
 502     }
 503 
 504     NOT_PRODUCT(C->verify_graph_edges();)
 505 
 506     compact();                  // Compact LRGs; return new lower max lrg
 507 
 508     {
 509       Compile::TracePhase tp(_t_computeLive);
 510       _live = nullptr;
 511       rm.reset_to_mark();         // Reclaim working storage
 512       IndexSet::reset_memory(C, &live_arena);
 513       ifg.init(_lrg_map.max_lrg_id()); // Build a new interference graph
 514       gather_lrg_masks( true );   // Collect intersect mask
 515       live.compute(_lrg_map.max_lrg_id()); // Compute LIVE
 516       _live = &live;
 517     }
 518 
 519     C->print_method(PHASE_INITIAL_SPILLING, 4);
 520 
 521     build_ifg_physical(&live_arena);
 522     if (C->failing()) {
 523       return;
 524     }
 525     _ifg->SquareUp();
 526     _ifg->Compute_Effective_Degree();
 527     // Only do conservative coalescing if requested
 528     if (OptoCoalesce) {
 529       Compile::TracePhase tp(_t_chaitinCoalesce2);
 530       // Conservative (and pessimistic) copy coalescing of those spills
 531       PhaseConservativeCoalesce coalesce(*this);
 532       // If max live ranges greater than cutoff, don't color the stack.
 533       // This cutoff can be larger than below since it is only done once.
 534       coalesce.coalesce_driver();
 535     }
 536     _lrg_map.compress_uf_map_for_nodes();
 537 
 538     if (OptoCoalesce) {
 539       C->print_method(PHASE_CONSERVATIVE_COALESCING, 4);
 540     }
 541 
 542 #ifdef ASSERT
 543     verify(&live_arena, true);
 544 #endif
 545   } else {
 546     ifg.SquareUp();
 547     ifg.Compute_Effective_Degree();
 548 #ifdef ASSERT
 549     set_was_low();
 550 #endif
 551   }
 552 
 553   // Prepare for Simplify & Select
 554   cache_lrg_info();           // Count degree of LRGs
 555 
 556   // Simplify the InterFerence Graph by removing LRGs of low degree.
 557   // LRGs of low degree are trivially colorable.
 558   Simplify();
 559 
 560   // Select colors by re-inserting LRGs back into the IFG in reverse order.
 561   // Return whether or not something spills.
 562   uint spills = Select( );
 563   if (C->failing()) {
 564     return;
 565   }
 566 
 567   // If we spill, split and recycle the entire thing
 568   while( spills ) {
 569     if( _trip_cnt++ > 24 ) {
 570       DEBUG_ONLY( dump_for_spill_split_recycle(); )
 571       if( _trip_cnt > 27 ) {
 572         C->record_method_not_compilable("failed spill-split-recycle sanity check");
 573         return;
 574       }
 575     }
 576 
 577     if (!_lrg_map.max_lrg_id()) {
 578       return;
 579     }
 580     uint new_max_lrg_id = Split(_lrg_map.max_lrg_id(), &split_arena);  // Split spilling LRG everywhere
 581     if (C->failing()) {
 582       return;
 583     }
 584     _lrg_map.set_max_lrg_id(new_max_lrg_id);
 585     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
 586     C->check_node_count(2 * NodeLimitFudgeFactor, "out of nodes after split");
 587     if (C->failing()) {
 588       return;
 589     }
 590 
 591     compact(); // Compact LRGs; return new lower max lrg
 592 
 593     // Nuke the live-ness and interference graph and LiveRanGe info
 594     {
 595       Compile::TracePhase tp(_t_computeLive);
 596       _live = nullptr;
 597       rm.reset_to_mark();         // Reclaim working storage
 598       IndexSet::reset_memory(C, &live_arena);
 599       ifg.init(_lrg_map.max_lrg_id());
 600 
 601       // Create LiveRanGe array.
 602       // Intersect register masks for all USEs and DEFs
 603       gather_lrg_masks(true);
 604       live.compute(_lrg_map.max_lrg_id());
 605       _live = &live;
 606     }
 607 
 608     C->print_method(PHASE_ITERATIVE_SPILLING, 4);
 609 
 610     must_spill = build_ifg_physical(&live_arena);
 611     if (C->failing()) {
 612       return;
 613     }
 614     _ifg->SquareUp();
 615     _ifg->Compute_Effective_Degree();
 616 
 617     // Only do conservative coalescing if requested
 618     if (OptoCoalesce) {
 619       Compile::TracePhase tp(_t_chaitinCoalesce3);
 620       // Conservative (and pessimistic) copy coalescing
 621       PhaseConservativeCoalesce coalesce(*this);
 622       // Check for few live ranges determines how aggressive coalesce is.
 623       coalesce.coalesce_driver();
 624     }
 625     _lrg_map.compress_uf_map_for_nodes();
 626 
 627     if (OptoCoalesce) {
 628       C->print_method(PHASE_CONSERVATIVE_COALESCING, 4);
 629     }
 630 
 631 #ifdef ASSERT
 632     verify(&live_arena, true);
 633 #endif
 634     cache_lrg_info();           // Count degree of LRGs
 635 
 636     // Simplify the InterFerence Graph by removing LRGs of low degree.
 637     // LRGs of low degree are trivially colorable.
 638     Simplify();
 639 
 640     // Select colors by re-inserting LRGs back into the IFG in reverse order.
 641     // Return whether or not something spills.
 642     spills = Select();
 643     if (C->failing()) {
 644       return;
 645     }
 646   }
 647 
 648   C->print_method(PHASE_AFTER_ITERATIVE_SPILLING, 4);
 649 
 650   // Count number of Simplify-Select trips per coloring success.
 651   _allocator_attempts += _trip_cnt + 1;
 652   _allocator_successes += 1;
 653 
 654   // Peephole remove copies
 655   post_allocate_copy_removal();
 656 
 657   C->print_method(PHASE_POST_ALLOCATION_COPY_REMOVAL, 4);
 658 
 659   // Merge multidefs if multiple defs representing the same value are used in a single block.
 660   merge_multidefs();
 661 
 662   C->print_method(PHASE_MERGE_MULTI_DEFS, 4);
 663 
 664 #ifdef ASSERT
 665   // Verify the graph after RA.
 666   verify(&live_arena);
 667 #endif
 668 
 669   // max_reg is past the largest *register* used.
 670   // Convert that to a frame_slot number.
 671   if (_max_reg <= _matcher._new_SP) {
 672     _framesize = C->out_preserve_stack_slots();
 673   }
 674   else {
 675     _framesize = _max_reg -_matcher._new_SP;
 676   }
 677   assert((int)(_matcher._new_SP+_framesize) >= (int)_matcher._out_arg_limit, "framesize must be large enough");
 678 
 679   // This frame must preserve the required fp alignment
 680   _framesize = align_up(_framesize, Matcher::stack_alignment_in_slots());
 681   assert(_framesize <= 1000000, "sanity check");
 682 #ifndef PRODUCT
 683   _total_framesize += _framesize;
 684   if ((int)_framesize > _max_framesize) {
 685     _max_framesize = _framesize;
 686   }
 687 #endif
 688 
 689   // Convert CISC spills
 690   fixup_spills();
 691 
 692   C->print_method(PHASE_FIX_UP_SPILLS, 4);
 693 
 694   // Log regalloc results
 695   CompileLog* log = Compile::current()->log();
 696   if (log != nullptr) {
 697     log->elem("regalloc attempts='%d' success='%d'", _trip_cnt, !C->failing());
 698   }
 699 
 700   if (C->failing()) {
 701     return;
 702   }
 703 
 704   NOT_PRODUCT(C->verify_graph_edges();)
 705 
 706   // Move important info out of the live_arena to longer lasting storage.
 707   alloc_node_regs(_lrg_map.size());
 708   for (uint i=0; i < _lrg_map.size(); i++) {
 709     if (_lrg_map.live_range_id(i)) { // Live range associated with Node?
 710       LRG &lrg = lrgs(_lrg_map.live_range_id(i));
 711       if (!lrg.alive()) {
 712         set_bad(i);
 713       } else if ((lrg.num_regs() == 1 && !lrg.is_scalable()) ||
 714                  (lrg.is_scalable() && lrg.scalable_reg_slots() == 1)) {
 715         set1(i, lrg.reg());
 716       } else {                  // Must be a register-set
 717         if (!lrg._fat_proj) {   // Must be aligned adjacent register set
 718           // Live ranges record the highest register in their mask.
 719           // We want the low register for the AD file writer's convenience.
 720           OptoReg::Name hi = lrg.reg(); // Get hi register
 721           int num_regs = lrg.num_regs();
 722           if (lrg.is_scalable() && OptoReg::is_stack(hi)) {
 723             // For scalable vector registers, when they are allocated in physical
 724             // registers, num_regs is RegMask::SlotsPerVecA for reg mask of scalable
 725             // vector. If they are allocated on stack, we need to get the actual
 726             // num_regs, which reflects the physical length of scalable registers.
 727             num_regs = lrg.scalable_reg_slots();
 728           }
 729           if (num_regs == 1) {
 730             set1(i, hi);
 731           } else {
 732             OptoReg::Name lo = OptoReg::add(hi, (1 - num_regs)); // Find lo
 733             // We have to use pair [lo,lo+1] even for wide vectors/vmasks because
 734             // the rest of code generation works only with pairs. It is safe
 735             // since for registers encoding only 'lo' is used.
 736             // Second reg from pair is used in ScheduleAndBundle with vector max
 737             // size 8 which corresponds to registers pair.
 738             // It is also used in BuildOopMaps but oop operations are not
 739             // vectorized.
 740             set2(i, lo);
 741           }
 742         } else {                // Misaligned; extract 2 bits
 743           OptoReg::Name hi = lrg.reg(); // Get hi register
 744           lrg.Remove(hi);       // Yank from mask
 745           int lo = lrg.mask().find_first_elem(); // Find lo
 746           set_pair(i, hi, lo);
 747         }
 748       }
 749       if( lrg._is_oop ) _node_oops.set(i);
 750     } else {
 751       set_bad(i);
 752     }
 753   }
 754 
 755   // Done!
 756   _live = nullptr;
 757   _ifg = nullptr;
 758   C->set_indexSet_arena(nullptr);  // ResourceArea is at end of scope
 759 }
 760 
 761 void PhaseChaitin::de_ssa() {
 762   // Set initial Names for all Nodes.  Most Nodes get the virtual register
 763   // number.  A few get the ZERO live range number.  These do not
 764   // get allocated, but instead rely on correct scheduling to ensure that
 765   // only one instance is simultaneously live at a time.
 766   uint lr_counter = 1;
 767   for( uint i = 0; i < _cfg.number_of_blocks(); i++ ) {
 768     Block* block = _cfg.get_block(i);
 769     uint cnt = block->number_of_nodes();
 770 
 771     // Handle all the normal Nodes in the block
 772     for( uint j = 0; j < cnt; j++ ) {
 773       Node *n = block->get_node(j);
 774       // Pre-color to the zero live range, or pick virtual register
 775       const RegMask &rm = n->out_RegMask();
 776       _lrg_map.map(n->_idx, !rm.is_Empty() ? lr_counter++ : 0);
 777     }
 778   }
 779 
 780   // Reset the Union-Find mapping to be identity
 781   _lrg_map.reset_uf_map(lr_counter);
 782 }
 783 
 784 void PhaseChaitin::mark_ssa() {
 785   // Use ssa names to populate the live range maps or if no mask
 786   // is available, use the 0 entry.
 787   uint max_idx = 0;
 788   for ( uint i = 0; i < _cfg.number_of_blocks(); i++ ) {
 789     Block* block = _cfg.get_block(i);
 790     uint cnt = block->number_of_nodes();
 791 
 792     // Handle all the normal Nodes in the block
 793     for ( uint j = 0; j < cnt; j++ ) {
 794       Node *n = block->get_node(j);
 795       // Pre-color to the zero live range, or pick virtual register
 796       const RegMask &rm = n->out_RegMask();
 797       _lrg_map.map(n->_idx, !rm.is_Empty() ? n->_idx : 0);
 798       max_idx = (n->_idx > max_idx) ? n->_idx : max_idx;
 799     }
 800   }
 801   _lrg_map.set_max_lrg_id(max_idx+1);
 802 
 803   // Reset the Union-Find mapping to be identity
 804   _lrg_map.reset_uf_map(max_idx+1);
 805 }
 806 
 807 
 808 // Gather LiveRanGe information, including register masks.  Modification of
 809 // cisc spillable in_RegMasks should not be done before AggressiveCoalesce.
 810 void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) {
 811 
 812   // Nail down the frame pointer live range
 813   uint fp_lrg = _lrg_map.live_range_id(_cfg.get_root_node()->in(1)->in(TypeFunc::FramePtr));
 814   lrgs(fp_lrg)._cost += 1e12;   // Cost is infinite
 815 
 816   // For all blocks
 817   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
 818     Block* block = _cfg.get_block(i);
 819 
 820     // For all instructions
 821     for (uint j = 1; j < block->number_of_nodes(); j++) {
 822       Node* n = block->get_node(j);
 823       uint input_edge_start =1; // Skip control most nodes
 824       bool is_machine_node = false;
 825       if (n->is_Mach()) {
 826         is_machine_node = true;
 827         input_edge_start = n->as_Mach()->oper_input_base();
 828       }
 829       uint idx = n->is_Copy();
 830 
 831       // Get virtual register number, same as LiveRanGe index
 832       uint vreg = _lrg_map.live_range_id(n);
 833       LRG& lrg = lrgs(vreg);
 834       if (vreg) {              // No vreg means un-allocable (e.g. memory)
 835 
 836         // Check for float-vs-int live range (used in register-pressure
 837         // calculations)
 838         const Type *n_type = n->bottom_type();
 839         if (n_type->is_floatingpoint()) {
 840           lrg._is_float = 1;
 841         }
 842 
 843         // Check for twice prior spilling.  Once prior spilling might have
 844         // spilled 'soft', 2nd prior spill should have spilled 'hard' and
 845         // further spilling is unlikely to make progress.
 846         if (_spilled_once.test(n->_idx)) {
 847           lrg._was_spilled1 = 1;
 848           if (_spilled_twice.test(n->_idx)) {
 849             lrg._was_spilled2 = 1;
 850           }
 851         }
 852 
 853 #ifndef PRODUCT
 854         // Collect bits not used by product code, but which may be useful for
 855         // debugging.
 856 
 857         // Collect has-copy bit
 858         if (idx) {
 859           lrg._has_copy = 1;
 860           uint clidx = _lrg_map.live_range_id(n->in(idx));
 861           LRG& copy_src = lrgs(clidx);
 862           copy_src._has_copy = 1;
 863         }
 864 
 865         if (trace_spilling() && lrg._def != nullptr) {
 866           // collect defs for MultiDef printing
 867           if (lrg._defs == nullptr) {
 868             lrg._defs = new (_ifg->_arena) GrowableArray<Node*>(_ifg->_arena, 2, 0, nullptr);
 869             lrg._defs->append(lrg._def);
 870           }
 871           lrg._defs->append(n);
 872         }
 873 #endif
 874 
 875         // Check for a single def LRG; these can spill nicely
 876         // via rematerialization.  Flag as null for no def found
 877         // yet, or 'n' for single def or -1 for many defs.
 878         lrg._def = lrg._def ? NodeSentinel : n;
 879 
 880         // Limit result register mask to acceptable registers
 881         const RegMask &rm = n->out_RegMask();
 882         lrg.AND( rm );
 883 
 884         uint ireg = n->ideal_reg();
 885         assert( !n->bottom_type()->isa_oop_ptr() || ireg == Op_RegP,
 886                 "oops must be in Op_RegP's" );
 887 
 888         // Check for vector live range (only if vector register is used).
 889         // On SPARC vector uses RegD which could be misaligned so it is not
 890         // processes as vector in RA.
 891         if (RegMask::is_vector(ireg)) {
 892           lrg._is_vector = 1;
 893           if (Matcher::implements_scalable_vector && ireg == Op_VecA) {
 894             assert(Matcher::supports_scalable_vector(), "scalable vector should be supported");
 895             lrg._is_scalable = 1;
 896             // For scalable vector, when it is allocated in physical register,
 897             // num_regs is RegMask::SlotsPerVecA for reg mask,
 898             // which may not be the actual physical register size.
 899             // If it is allocated in stack, we need to get the actual
 900             // physical length of scalable vector register.
 901             lrg.set_scalable_reg_slots(Matcher::scalable_vector_reg_size(T_FLOAT));
 902           }
 903         }
 904 
 905         if (ireg == Op_RegVectMask) {
 906           assert(Matcher::has_predicated_vectors(), "predicated vector should be supported");
 907           lrg._is_predicate = 1;
 908           if (Matcher::supports_scalable_vector()) {
 909             lrg._is_scalable = 1;
 910             // For scalable predicate, when it is allocated in physical register,
 911             // num_regs is RegMask::SlotsPerRegVectMask for reg mask,
 912             // which may not be the actual physical register size.
 913             // If it is allocated in stack, we need to get the actual
 914             // physical length of scalable predicate register.
 915             lrg.set_scalable_reg_slots(Matcher::scalable_predicate_reg_slots());
 916           }
 917         }
 918         assert(n_type->isa_vect() == nullptr || lrg._is_vector ||
 919                ireg == Op_RegD || ireg == Op_RegL || ireg == Op_RegVectMask,
 920                "vector must be in vector registers");
 921 
 922         // Check for bound register masks
 923         const RegMask &lrgmask = lrg.mask();
 924         if (lrgmask.is_bound(ireg)) {
 925           lrg._is_bound = 1;
 926         }
 927 
 928         // Check for maximum frequency value
 929         if (lrg._maxfreq < block->_freq) {
 930           lrg._maxfreq = block->_freq;
 931         }
 932 
 933         // Check for oop-iness, or long/double
 934         // Check for multi-kill projection
 935         switch (ireg) {
 936         case MachProjNode::fat_proj:
 937           // Fat projections have size equal to number of registers killed
 938           lrg.set_num_regs(rm.Size());
 939           lrg.set_reg_pressure(lrg.num_regs());
 940           lrg._fat_proj = 1;
 941           lrg._is_bound = 1;
 942           break;
 943         case Op_RegP:
 944 #ifdef _LP64
 945           lrg.set_num_regs(2);  // Size is 2 stack words
 946 #else
 947           lrg.set_num_regs(1);  // Size is 1 stack word
 948 #endif
 949           // Register pressure is tracked relative to the maximum values
 950           // suggested for that platform, INTPRESSURE and FLOATPRESSURE,
 951           // and relative to other types which compete for the same regs.
 952           //
 953           // The following table contains suggested values based on the
 954           // architectures as defined in each .ad file.
 955           // INTPRESSURE and FLOATPRESSURE may be tuned differently for
 956           // compile-speed or performance.
 957           // Note1:
 958           // SPARC and SPARCV9 reg_pressures are at 2 instead of 1
 959           // since .ad registers are defined as high and low halves.
 960           // These reg_pressure values remain compatible with the code
 961           // in is_high_pressure() which relates get_invalid_mask_size(),
 962           // Block::_reg_pressure and INTPRESSURE, FLOATPRESSURE.
 963           // Note2:
 964           // SPARC -d32 has 24 registers available for integral values,
 965           // but only 10 of these are safe for 64-bit longs.
 966           // Using set_reg_pressure(2) for both int and long means
 967           // the allocator will believe it can fit 26 longs into
 968           // registers.  Using 2 for longs and 1 for ints means the
 969           // allocator will attempt to put 52 integers into registers.
 970           // The settings below limit this problem to methods with
 971           // many long values which are being run on 32-bit SPARC.
 972           //
 973           // ------------------- reg_pressure --------------------
 974           // Each entry is reg_pressure_per_value,number_of_regs
 975           //         RegL  RegI  RegFlags   RegF RegD    INTPRESSURE  FLOATPRESSURE
 976           // IA32     2     1     1          1    1          6           6
 977           // SPARC    2     2     2          2    2         48 (24)     52 (26)
 978           // SPARCV9  2     2     2          2    2         48 (24)     52 (26)
 979           // AMD64    1     1     1          1    1         14          15
 980           // -----------------------------------------------------
 981           lrg.set_reg_pressure(1);  // normally one value per register
 982           if( n_type->isa_oop_ptr() ) {
 983             lrg._is_oop = 1;
 984           }
 985           break;
 986         case Op_RegL:           // Check for long or double
 987         case Op_RegD:
 988           lrg.set_num_regs(2);
 989           // Define platform specific register pressure
 990 #if defined(ARM32)
 991           lrg.set_reg_pressure(2);
 992 #elif defined(IA32)
 993           if( ireg == Op_RegL ) {
 994             lrg.set_reg_pressure(2);
 995           } else {
 996             lrg.set_reg_pressure(1);
 997           }
 998 #else
 999           lrg.set_reg_pressure(1);  // normally one value per register
1000 #endif
1001           // If this def of a double forces a mis-aligned double,
1002           // flag as '_fat_proj' - really flag as allowing misalignment
1003           // AND changes how we count interferences.  A mis-aligned
1004           // double can interfere with TWO aligned pairs, or effectively
1005           // FOUR registers!
1006           if (rm.is_misaligned_pair()) {
1007             lrg._fat_proj = 1;
1008             lrg._is_bound = 1;
1009           }
1010           break;
1011         case Op_RegVectMask:
1012           assert(Matcher::has_predicated_vectors(), "sanity");
1013           assert(RegMask::num_registers(Op_RegVectMask) == RegMask::SlotsPerRegVectMask, "sanity");
1014           lrg.set_num_regs(RegMask::SlotsPerRegVectMask);
1015           lrg.set_reg_pressure(1);
1016           break;
1017         case Op_RegF:
1018         case Op_RegI:
1019         case Op_RegN:
1020         case Op_RegFlags:
1021         case 0:                 // not an ideal register
1022           lrg.set_num_regs(1);
1023           lrg.set_reg_pressure(1);
1024           break;
1025         case Op_VecA:
1026           assert(Matcher::supports_scalable_vector(), "does not support scalable vector");
1027           assert(RegMask::num_registers(Op_VecA) == RegMask::SlotsPerVecA, "sanity");
1028           assert(lrgmask.is_aligned_sets(RegMask::SlotsPerVecA), "vector should be aligned");
1029           lrg.set_num_regs(RegMask::SlotsPerVecA);
1030           lrg.set_reg_pressure(1);
1031           break;
1032         case Op_VecS:
1033           assert(Matcher::vector_size_supported(T_BYTE,4), "sanity");
1034           assert(RegMask::num_registers(Op_VecS) == RegMask::SlotsPerVecS, "sanity");
1035           lrg.set_num_regs(RegMask::SlotsPerVecS);
1036           lrg.set_reg_pressure(1);
1037           break;
1038         case Op_VecD:
1039           assert(Matcher::vector_size_supported(T_FLOAT,RegMask::SlotsPerVecD), "sanity");
1040           assert(RegMask::num_registers(Op_VecD) == RegMask::SlotsPerVecD, "sanity");
1041           assert(lrgmask.is_aligned_sets(RegMask::SlotsPerVecD), "vector should be aligned");
1042           lrg.set_num_regs(RegMask::SlotsPerVecD);
1043           lrg.set_reg_pressure(1);
1044           break;
1045         case Op_VecX:
1046           assert(Matcher::vector_size_supported(T_FLOAT,RegMask::SlotsPerVecX), "sanity");
1047           assert(RegMask::num_registers(Op_VecX) == RegMask::SlotsPerVecX, "sanity");
1048           assert(lrgmask.is_aligned_sets(RegMask::SlotsPerVecX), "vector should be aligned");
1049           lrg.set_num_regs(RegMask::SlotsPerVecX);
1050           lrg.set_reg_pressure(1);
1051           break;
1052         case Op_VecY:
1053           assert(Matcher::vector_size_supported(T_FLOAT,RegMask::SlotsPerVecY), "sanity");
1054           assert(RegMask::num_registers(Op_VecY) == RegMask::SlotsPerVecY, "sanity");
1055           assert(lrgmask.is_aligned_sets(RegMask::SlotsPerVecY), "vector should be aligned");
1056           lrg.set_num_regs(RegMask::SlotsPerVecY);
1057           lrg.set_reg_pressure(1);
1058           break;
1059         case Op_VecZ:
1060           assert(Matcher::vector_size_supported(T_FLOAT,RegMask::SlotsPerVecZ), "sanity");
1061           assert(RegMask::num_registers(Op_VecZ) == RegMask::SlotsPerVecZ, "sanity");
1062           assert(lrgmask.is_aligned_sets(RegMask::SlotsPerVecZ), "vector should be aligned");
1063           lrg.set_num_regs(RegMask::SlotsPerVecZ);
1064           lrg.set_reg_pressure(1);
1065           break;
1066         default:
1067           ShouldNotReachHere();
1068         }
1069       }
1070 
1071       // Now do the same for inputs
1072       uint cnt = n->req();
1073       // Setup for CISC SPILLING
1074       uint inp = (uint)AdlcVMDeps::Not_cisc_spillable;
1075       if( UseCISCSpill && after_aggressive ) {
1076         inp = n->cisc_operand();
1077         if( inp != (uint)AdlcVMDeps::Not_cisc_spillable )
1078           // Convert operand number to edge index number
1079           inp = n->as_Mach()->operand_index(inp);
1080       }
1081 
1082       // Prepare register mask for each input
1083       for( uint k = input_edge_start; k < cnt; k++ ) {
1084         uint vreg = _lrg_map.live_range_id(n->in(k));
1085         if (!vreg) {
1086           continue;
1087         }
1088 
1089         // If this instruction is CISC Spillable, add the flags
1090         // bit to its appropriate input
1091         if( UseCISCSpill && after_aggressive && inp == k ) {
1092 #ifndef PRODUCT
1093           if( TraceCISCSpill ) {
1094             tty->print("  use_cisc_RegMask: ");
1095             n->dump();
1096           }
1097 #endif
1098           n->as_Mach()->use_cisc_RegMask();
1099         }
1100 
1101         if (is_machine_node && _scheduling_info_generated) {
1102           MachNode* cur_node = n->as_Mach();
1103           // this is cleaned up by register allocation
1104           if (k >= cur_node->num_opnds()) continue;
1105         }
1106 
1107         LRG &lrg = lrgs(vreg);
1108         // // Testing for floating point code shape
1109         // Node *test = n->in(k);
1110         // if( test->is_Mach() ) {
1111         //   MachNode *m = test->as_Mach();
1112         //   int  op = m->ideal_Opcode();
1113         //   if (n->is_Call() && (op == Op_AddF || op == Op_MulF) ) {
1114         //     int zzz = 1;
1115         //   }
1116         // }
1117 
1118         // Limit result register mask to acceptable registers.
1119         // Do not limit registers from uncommon uses before
1120         // AggressiveCoalesce.  This effectively pre-virtual-splits
1121         // around uncommon uses of common defs.
1122         const RegMask &rm = n->in_RegMask(k);
1123         if (!after_aggressive && _cfg.get_block_for_node(n->in(k))->_freq > 1000 * block->_freq) {
1124           // Since we are BEFORE aggressive coalesce, leave the register
1125           // mask untrimmed by the call.  This encourages more coalescing.
1126           // Later, AFTER aggressive, this live range will have to spill
1127           // but the spiller handles slow-path calls very nicely.
1128         } else {
1129           lrg.AND( rm );
1130         }
1131 
1132         // Check for bound register masks
1133         const RegMask &lrgmask = lrg.mask();
1134         uint kreg = n->in(k)->ideal_reg();
1135         bool is_vect = RegMask::is_vector(kreg);
1136         assert(n->in(k)->bottom_type()->isa_vect() == nullptr || is_vect ||
1137                kreg == Op_RegD || kreg == Op_RegL || kreg == Op_RegVectMask,
1138                "vector must be in vector registers");
1139         if (lrgmask.is_bound(kreg))
1140           lrg._is_bound = 1;
1141 
1142         // If this use of a double forces a mis-aligned double,
1143         // flag as '_fat_proj' - really flag as allowing misalignment
1144         // AND changes how we count interferences.  A mis-aligned
1145         // double can interfere with TWO aligned pairs, or effectively
1146         // FOUR registers!
1147 #ifdef ASSERT
1148         if (is_vect && !_scheduling_info_generated) {
1149           if (lrg.num_regs() != 0) {
1150             assert(lrgmask.is_aligned_sets(lrg.num_regs()), "vector should be aligned");
1151             assert(!lrg._fat_proj, "sanity");
1152             assert(RegMask::num_registers(kreg) == lrg.num_regs(), "sanity");
1153           } else {
1154             assert(n->is_Phi(), "not all inputs processed only if Phi");
1155           }
1156         }
1157 #endif
1158         if (!is_vect && lrg.num_regs() == 2 && !lrg._fat_proj && rm.is_misaligned_pair()) {
1159           lrg._fat_proj = 1;
1160           lrg._is_bound = 1;
1161         }
1162         // if the LRG is an unaligned pair, we will have to spill
1163         // so clear the LRG's register mask if it is not already spilled
1164         if (!is_vect && !n->is_SpillCopy() &&
1165             (lrg._def == nullptr || lrg.is_multidef() || !lrg._def->is_SpillCopy()) &&
1166             lrgmask.is_misaligned_pair()) {
1167           lrg.Clear();
1168         }
1169 
1170         // Check for maximum frequency value
1171         if (lrg._maxfreq < block->_freq) {
1172           lrg._maxfreq = block->_freq;
1173         }
1174 
1175       } // End for all allocated inputs
1176     } // end for all instructions
1177   } // end for all blocks
1178 
1179   // Final per-liverange setup
1180   for (uint i2 = 0; i2 < _lrg_map.max_lrg_id(); i2++) {
1181     LRG &lrg = lrgs(i2);
1182     assert(!lrg._is_vector || !lrg._fat_proj, "sanity");
1183     if (lrg.num_regs() > 1 && !lrg._fat_proj) {
1184       lrg.clear_to_sets();
1185     }
1186     lrg.compute_set_mask_size();
1187     if (lrg.not_free()) {      // Handle case where we lose from the start
1188       lrg.set_reg(OptoReg::Name(LRG::SPILL_REG));
1189       lrg._direct_conflict = 1;
1190     }
1191     lrg.set_degree(0);          // no neighbors in IFG yet
1192   }
1193 }
1194 
1195 // Set the was-lo-degree bit.  Conservative coalescing should not change the
1196 // colorability of the graph.  If any live range was of low-degree before
1197 // coalescing, it should Simplify.  This call sets the was-lo-degree bit.
1198 // The bit is checked in Simplify.
1199 void PhaseChaitin::set_was_low() {
1200 #ifdef ASSERT
1201   for (uint i = 1; i < _lrg_map.max_lrg_id(); i++) {
1202     int size = lrgs(i).num_regs();
1203     uint old_was_lo = lrgs(i)._was_lo;
1204     lrgs(i)._was_lo = 0;
1205     if( lrgs(i).lo_degree() ) {
1206       lrgs(i)._was_lo = 1;      // Trivially of low degree
1207     } else {                    // Else check the Brigg's assertion
1208       // Brigg's observation is that the lo-degree neighbors of a
1209       // hi-degree live range will not interfere with the color choices
1210       // of said hi-degree live range.  The Simplify reverse-stack-coloring
1211       // order takes care of the details.  Hence you do not have to count
1212       // low-degree neighbors when determining if this guy colors.
1213       int briggs_degree = 0;
1214       IndexSet *s = _ifg->neighbors(i);
1215       IndexSetIterator elements(s);
1216       uint lidx;
1217       while((lidx = elements.next()) != 0) {
1218         if( !lrgs(lidx).lo_degree() )
1219           briggs_degree += MAX2(size,lrgs(lidx).num_regs());
1220       }
1221       if( briggs_degree < lrgs(i).degrees_of_freedom() )
1222         lrgs(i)._was_lo = 1;    // Low degree via the briggs assertion
1223     }
1224     assert(old_was_lo <= lrgs(i)._was_lo, "_was_lo may not decrease");
1225   }
1226 #endif
1227 }
1228 
1229 // Compute cost/area ratio, in case we spill.  Build the lo-degree list.
1230 void PhaseChaitin::cache_lrg_info( ) {
1231   Compile::TracePhase tp(_t_chaitinCacheLRG);
1232 
1233   for (uint i = 1; i < _lrg_map.max_lrg_id(); i++) {
1234     LRG &lrg = lrgs(i);
1235 
1236     // Check for being of low degree: means we can be trivially colored.
1237     // Low degree, dead or must-spill guys just get to simplify right away
1238     if( lrg.lo_degree() ||
1239        !lrg.alive() ||
1240         lrg._must_spill ) {
1241       // Split low degree list into those guys that must get a
1242       // register and those that can go to register or stack.
1243       // The idea is LRGs that can go register or stack color first when
1244       // they have a good chance of getting a register.  The register-only
1245       // lo-degree live ranges always get a register.
1246       OptoReg::Name hi_reg = lrg.mask().find_last_elem();
1247       if( OptoReg::is_stack(hi_reg)) { // Can go to stack?
1248         lrg._next = _lo_stk_degree;
1249         _lo_stk_degree = i;
1250       } else {
1251         lrg._next = _lo_degree;
1252         _lo_degree = i;
1253       }
1254     } else {                    // Else high degree
1255       lrgs(_hi_degree)._prev = i;
1256       lrg._next = _hi_degree;
1257       lrg._prev = 0;
1258       _hi_degree = i;
1259     }
1260   }
1261 }
1262 
1263 // Simplify the IFG by removing LRGs of low degree.
1264 void PhaseChaitin::Simplify( ) {
1265   Compile::TracePhase tp(_t_chaitinSimplify);
1266 
1267   while( 1 ) {                  // Repeat till simplified it all
1268     // May want to explore simplifying lo_degree before _lo_stk_degree.
1269     // This might result in more spills coloring into registers during
1270     // Select().
1271     while( _lo_degree || _lo_stk_degree ) {
1272       // If possible, pull from lo_stk first
1273       uint lo;
1274       if( _lo_degree ) {
1275         lo = _lo_degree;
1276         _lo_degree = lrgs(lo)._next;
1277       } else {
1278         lo = _lo_stk_degree;
1279         _lo_stk_degree = lrgs(lo)._next;
1280       }
1281 
1282       // Put the simplified guy on the simplified list.
1283       lrgs(lo)._next = _simplified;
1284       _simplified = lo;
1285       // If this guy is "at risk" then mark his current neighbors
1286       if (lrgs(lo)._at_risk && !_ifg->neighbors(lo)->is_empty()) {
1287         IndexSetIterator elements(_ifg->neighbors(lo));
1288         uint datum;
1289         while ((datum = elements.next()) != 0) {
1290           lrgs(datum)._risk_bias = lo;
1291         }
1292       }
1293 
1294       // Yank this guy from the IFG.
1295       IndexSet *adj = _ifg->remove_node(lo);
1296       if (adj->is_empty()) {
1297         continue;
1298       }
1299 
1300       // If any neighbors' degrees fall below their number of
1301       // allowed registers, then put that neighbor on the low degree
1302       // list.  Note that 'degree' can only fall and 'numregs' is
1303       // unchanged by this action.  Thus the two are equal at most once,
1304       // so LRGs hit the lo-degree worklist at most once.
1305       IndexSetIterator elements(adj);
1306       uint neighbor;
1307       while ((neighbor = elements.next()) != 0) {
1308         LRG *n = &lrgs(neighbor);
1309 #ifdef ASSERT
1310         if (VerifyRegisterAllocator) {
1311           assert( _ifg->effective_degree(neighbor) == n->degree(), "" );
1312         }
1313 #endif
1314 
1315         // Check for just becoming of-low-degree just counting registers.
1316         // _must_spill live ranges are already on the low degree list.
1317         if (n->just_lo_degree() && !n->_must_spill) {
1318           assert(!_ifg->_yanked->test(neighbor), "Cannot move to lo degree twice");
1319           // Pull from hi-degree list
1320           uint prev = n->_prev;
1321           uint next = n->_next;
1322           if (prev) {
1323             lrgs(prev)._next = next;
1324           } else {
1325             _hi_degree = next;
1326           }
1327           lrgs(next)._prev = prev;
1328           n->_next = _lo_degree;
1329           _lo_degree = neighbor;
1330         }
1331       }
1332     } // End of while lo-degree/lo_stk_degree worklist not empty
1333 
1334     // Check for got everything: is hi-degree list empty?
1335     if (!_hi_degree) break;
1336 
1337     // Time to pick a potential spill guy
1338     uint lo_score = _hi_degree;
1339     double score = lrgs(lo_score).score();
1340     double area = lrgs(lo_score)._area;
1341     double cost = lrgs(lo_score)._cost;
1342     bool bound = lrgs(lo_score)._is_bound;
1343 
1344     // Find cheapest guy
1345     DEBUG_ONLY( int lo_no_simplify=0; );
1346     for (uint i = _hi_degree; i; i = lrgs(i)._next) {
1347       assert(!_ifg->_yanked->test(i), "");
1348       // It's just vaguely possible to move hi-degree to lo-degree without
1349       // going through a just-lo-degree stage: If you remove a double from
1350       // a float live range it's degree will drop by 2 and you can skip the
1351       // just-lo-degree stage.  It's very rare (shows up after 5000+ methods
1352       // in -Xcomp of Java2Demo).  So just choose this guy to simplify next.
1353       if( lrgs(i).lo_degree() ) {
1354         lo_score = i;
1355         break;
1356       }
1357       DEBUG_ONLY( if( lrgs(i)._was_lo ) lo_no_simplify=i; );
1358       double iscore = lrgs(i).score();
1359       double iarea = lrgs(i)._area;
1360       double icost = lrgs(i)._cost;
1361       bool ibound = lrgs(i)._is_bound;
1362 
1363       // Compare cost/area of i vs cost/area of lo_score.  Smaller cost/area
1364       // wins.  Ties happen because all live ranges in question have spilled
1365       // a few times before and the spill-score adds a huge number which
1366       // washes out the low order bits.  We are choosing the lesser of 2
1367       // evils; in this case pick largest area to spill.
1368       // Ties also happen when live ranges are defined and used only inside
1369       // one block. In which case their area is 0 and score set to max.
1370       // In such case choose bound live range over unbound to free registers
1371       // or with smaller cost to spill.
1372       if ( iscore < score ||
1373           (iscore == score && iarea > area && lrgs(lo_score)._was_spilled2) ||
1374           (iscore == score && iarea == area &&
1375            ( (ibound && !bound) || (ibound == bound && (icost < cost)) )) ) {
1376         lo_score = i;
1377         score = iscore;
1378         area = iarea;
1379         cost = icost;
1380         bound = ibound;
1381       }
1382     }
1383     LRG *lo_lrg = &lrgs(lo_score);
1384     // The live range we choose for spilling is either hi-degree, or very
1385     // rarely it can be low-degree.  If we choose a hi-degree live range
1386     // there better not be any lo-degree choices.
1387     assert( lo_lrg->lo_degree() || !lo_no_simplify, "Live range was lo-degree before coalesce; should simplify" );
1388 
1389     // Pull from hi-degree list
1390     uint prev = lo_lrg->_prev;
1391     uint next = lo_lrg->_next;
1392     if( prev ) lrgs(prev)._next = next;
1393     else _hi_degree = next;
1394     lrgs(next)._prev = prev;
1395     // Jam him on the lo-degree list, despite his high degree.
1396     // Maybe he'll get a color, and maybe he'll spill.
1397     // Only Select() will know.
1398     lrgs(lo_score)._at_risk = true;
1399     _lo_degree = lo_score;
1400     lo_lrg->_next = 0;
1401 
1402   } // End of while not simplified everything
1403 
1404 }
1405 
1406 // Is 'reg' register legal for 'lrg'?
1407 static bool is_legal_reg(LRG& lrg, OptoReg::Name reg) {
1408   if (lrg.mask().can_represent(reg) && lrg.mask().Member(reg)) {
1409     // RA uses OptoReg which represent the highest element of a registers set.
1410     // For example, vectorX (128bit) on x86 uses [XMM,XMMb,XMMc,XMMd] set
1411     // in which XMMd is used by RA to represent such vectors. A double value
1412     // uses [XMM,XMMb] pairs and XMMb is used by RA for it.
1413     // The register mask uses largest bits set of overlapping register sets.
1414     // On x86 with AVX it uses 8 bits for each XMM registers set.
1415     //
1416     // The 'lrg' already has cleared-to-set register mask (done in Select()
1417     // before calling choose_color()). Passing mask.Member(reg) check above
1418     // indicates that the size (num_regs) of 'reg' set is less or equal to
1419     // 'lrg' set size.
1420     // For set size 1 any register which is member of 'lrg' mask is legal.
1421     if (lrg.num_regs()==1)
1422       return true;
1423     // For larger sets only an aligned register with the same set size is legal.
1424     int mask = lrg.num_regs()-1;
1425     if ((reg&mask) == mask)
1426       return true;
1427   }
1428   return false;
1429 }
1430 
1431 static OptoReg::Name find_first_set(LRG& lrg, RegMask& mask) {
1432   int num_regs = lrg.num_regs();
1433   OptoReg::Name assigned = mask.find_first_set(lrg, num_regs);
1434 
1435   if (lrg.is_scalable()) {
1436     // a physical register is found
1437     if (OptoReg::is_reg(assigned)) {
1438       assert(!lrg.mask().is_offset(),
1439              "offset register masks can only contain stack slots");
1440       return assigned;
1441     }
1442 
1443     // find available stack slots for scalable register
1444     if (lrg._is_vector) {
1445       num_regs = lrg.scalable_reg_slots();
1446       // if actual scalable vector register is exactly SlotsPerVecA * 32 bits
1447       if (num_regs == RegMask::SlotsPerVecA) {
1448         return assigned;
1449       }
1450 
1451       // mask has been cleared out by clear_to_sets(SlotsPerVecA) before choose_color, but it
1452       // does not work for scalable size. We have to find adjacent scalable_reg_slots() bits
1453       // instead of SlotsPerVecA bits.
1454       assigned = mask.find_first_set(lrg, num_regs); // find highest valid reg
1455       while (OptoReg::is_valid(assigned)) {
1456         assert(mask.can_represent(assigned), "sanity");
1457         // Verify the found reg has scalable_reg_slots() bits set.
1458         if (mask.is_valid_reg(assigned, num_regs)) {
1459           return assigned;
1460         } else {
1461           // Remove more for each iteration
1462           mask.Remove(assigned - num_regs + 1); // Unmask the lowest reg
1463           mask.clear_to_sets(RegMask::SlotsPerVecA); // Align by SlotsPerVecA bits
1464           assigned = mask.find_first_set(lrg, num_regs);
1465         }
1466       }
1467       return OptoReg::Bad; // will cause chunk change, and retry next chunk
1468     } else if (lrg._is_predicate) {
1469       assert(num_regs == RegMask::SlotsPerRegVectMask, "scalable predicate register");
1470       num_regs = lrg.scalable_reg_slots();
1471       mask.clear_to_sets(num_regs);
1472       return mask.find_first_set(lrg, num_regs);
1473     }
1474   }
1475 
1476   return assigned;
1477 }
1478 
1479 // Choose a color using the biasing heuristic
1480 OptoReg::Name PhaseChaitin::bias_color(LRG& lrg) {
1481 
1482   // Check for "at_risk" LRG's
1483   uint risk_lrg = _lrg_map.find(lrg._risk_bias);
1484   if (risk_lrg != 0 && !_ifg->neighbors(risk_lrg)->is_empty()) {
1485     // Walk the colored neighbors of the "at_risk" candidate
1486     // Choose a color which is both legal and already taken by a neighbor
1487     // of the "at_risk" candidate in order to improve the chances of the
1488     // "at_risk" candidate of coloring
1489     IndexSetIterator elements(_ifg->neighbors(risk_lrg));
1490     uint datum;
1491     while ((datum = elements.next()) != 0) {
1492       OptoReg::Name reg = lrgs(datum).reg();
1493       // If this LRG's register is legal for us, choose it
1494       if (is_legal_reg(lrg, reg)) {
1495         return reg;
1496       }
1497     }
1498   }
1499 
1500   uint copy_lrg = _lrg_map.find(lrg._copy_bias);
1501   if (copy_lrg != 0) {
1502     // If he has a color,
1503     if(!_ifg->_yanked->test(copy_lrg)) {
1504       OptoReg::Name reg = lrgs(copy_lrg).reg();
1505       //  And it is legal for you,
1506       if (is_legal_reg(lrg, reg)) {
1507         return reg;
1508       }
1509     } else if (!lrg.mask().is_offset()) {
1510       // Choose a color which is legal for him
1511       ResourceMark rm(C->regmask_arena());
1512       RegMask tempmask(lrg.mask(), C->regmask_arena());
1513       tempmask.AND(lrgs(copy_lrg).mask());
1514       tempmask.clear_to_sets(lrg.num_regs());
1515       OptoReg::Name reg = find_first_set(lrg, tempmask);
1516       if (OptoReg::is_valid(reg))
1517         return reg;
1518     }
1519   }
1520 
1521   // If no bias info exists, just go with the register selection ordering
1522   if (lrg._is_vector || lrg.num_regs() == 2 || lrg.is_scalable()) {
1523     // Find an aligned set
1524     ResourceMark rm(C->regmask_arena());
1525     RegMask tempmask(lrg.mask(), C->regmask_arena());
1526     return find_first_set(lrg, tempmask);
1527   }
1528 
1529   // CNC - Fun hack.  Alternate 1st and 2nd selection.  Enables post-allocate
1530   // copy removal to remove many more copies, by preventing a just-assigned
1531   // register from being repeatedly assigned.
1532   OptoReg::Name reg = lrg.mask().find_first_elem();
1533   if( (++_alternate & 1) && OptoReg::is_valid(reg) ) {
1534     // This 'Remove; find; Insert' idiom is an expensive way to find the
1535     // SECOND element in the mask.
1536     lrg.Remove(reg);
1537     OptoReg::Name reg2 = lrg.mask().find_first_elem();
1538     lrg.Insert(reg);
1539     if (OptoReg::is_reg(reg2)) {
1540       reg = reg2;
1541     }
1542   }
1543   return reg;
1544 }
1545 
1546 // Choose a color in the current chunk
1547 OptoReg::Name PhaseChaitin::choose_color(LRG& lrg) {
1548   assert(C->in_preserve_stack_slots() == 0 || lrg.mask().is_offset() || lrg._is_bound || lrg.mask().is_bound1() || !lrg.mask().Member(OptoReg::Name(_matcher._old_SP - 1)), "must not allocate stack0 (inside preserve area)");
1549   assert(C->out_preserve_stack_slots() == 0 || lrg.mask().is_offset() || lrg._is_bound || lrg.mask().is_bound1() || !lrg.mask().Member(OptoReg::Name(_matcher._old_SP + 0)), "must not allocate stack0 (inside preserve area)");
1550 
1551   if( lrg.num_regs() == 1 ||    // Common Case
1552       !lrg._fat_proj )          // Aligned+adjacent pairs ok
1553     // Use a heuristic to "bias" the color choice
1554     return bias_color(lrg);
1555 
1556   assert(!lrg._is_vector, "should be not vector here" );
1557   assert( lrg.num_regs() >= 2, "dead live ranges do not color" );
1558 
1559   // Fat-proj case or misaligned double argument.
1560   assert(lrg.compute_mask_size() == lrg.num_regs() ||
1561          lrg.num_regs() == 2,"fat projs exactly color" );
1562   assert(!lrg.mask().is_offset(), "always color in 1st chunk");
1563   // Return the highest element in the set.
1564   return lrg.mask().find_last_elem();
1565 }
1566 
1567 // Select colors by re-inserting LRGs back into the IFG.  LRGs are re-inserted
1568 // in reverse order of removal.  As long as nothing of hi-degree was yanked,
1569 // everything going back is guaranteed a color.  Select that color.  If some
1570 // hi-degree LRG cannot get a color then we record that we must spill.
1571 uint PhaseChaitin::Select( ) {
1572   Compile::TracePhase tp(_t_chaitinSelect);
1573 
1574   uint spill_reg = LRG::SPILL_REG;
1575   _max_reg = OptoReg::Name(0);  // Past max register used
1576   while( _simplified ) {
1577     // Pull next LRG from the simplified list - in reverse order of removal
1578     uint lidx = _simplified;
1579     LRG *lrg = &lrgs(lidx);
1580     _simplified = lrg->_next;
1581 
1582 #ifndef PRODUCT
1583     if (trace_spilling()) {
1584       ttyLocker ttyl;
1585       tty->print_cr("L%d selecting degree %d degrees_of_freedom %d", lidx, lrg->degree(),
1586                     lrg->degrees_of_freedom());
1587       lrg->dump();
1588     }
1589 #endif
1590 
1591     // Re-insert into the IFG
1592     _ifg->re_insert(lidx);
1593     if( !lrg->alive() ) continue;
1594     // capture infinitestackedness flag before mask is hacked
1595     const int is_infinite_stack = lrg->mask().is_infinite_stack();
1596 
1597     // Yeah, yeah, yeah, I know, I know.  I can refactor this
1598     // to avoid the GOTO, although the refactored code will not
1599     // be much clearer.  We arrive here IFF we have a stack-based
1600     // live range that cannot color in the current chunk, and it
1601     // has to move into the next free stack chunk.
1602     retry_next_chunk:
1603 
1604     // Remove neighbor colors
1605     IndexSet *s = _ifg->neighbors(lidx);
1606 #ifndef PRODUCT
1607     ResourceMark rm(C->regmask_arena());
1608     RegMask orig_mask(lrg->mask(), C->regmask_arena());
1609 #endif
1610 
1611     if (!s->is_empty()) {
1612       IndexSetIterator elements(s);
1613       uint neighbor;
1614       while ((neighbor = elements.next()) != 0) {
1615         LRG &nlrg = lrgs(neighbor);
1616         OptoReg::Name nreg = nlrg.reg();
1617         // The neighbor might be a spill_reg. In this case, exclusion of its
1618         // color will be a no-op, since the spill_reg is in outer space. In
1619         // this case, do not exclude the corresponding mask. Later on, if lrg
1620         // runs out of possible colors in its chunk, a new chunk of color may
1621         // be tried, in which case examination of neighbors is started again,
1622         // at retry_next_chunk.
1623         if (nreg < LRG::SPILL_REG) {
1624 #ifndef PRODUCT
1625           uint size = lrg->mask().Size();
1626           ResourceMark rm(C->regmask_arena());
1627           RegMask trace_mask(lrg->mask(), C->regmask_arena());
1628 #endif
1629           lrg->SUBTRACT_inner(nlrg.mask());
1630 #ifndef PRODUCT
1631           if (trace_spilling() && lrg->mask().Size() != size) {
1632             ttyLocker ttyl;
1633             tty->print("L%d ", lidx);
1634             trace_mask.dump();
1635             tty->print(" intersected L%d ", neighbor);
1636             nlrg.mask().dump();
1637             tty->print(" removed ");
1638             trace_mask.SUBTRACT(lrg->mask());
1639             trace_mask.dump();
1640             tty->print(" leaving ");
1641             lrg->mask().dump();
1642             tty->cr();
1643           }
1644 #endif
1645         }
1646       }
1647     }
1648     //assert(is_infinite_stack == lrg->mask().is_infinite_stack(), "nbrs must not change InfiniteStackedness");
1649     // Aligned pairs need aligned masks
1650     assert(!lrg->_is_vector || !lrg->_fat_proj, "sanity");
1651     if (lrg->num_regs() > 1 && !lrg->_fat_proj) {
1652       lrg->clear_to_sets();
1653     }
1654 
1655     // Check if a color is available and if so pick the color
1656     OptoReg::Name reg = choose_color(*lrg);
1657 
1658     //---------------
1659     // If we fail to color and the infinite flag is set, we must trigger
1660     // a chunk-rollover event and continue searching for a color in the next set
1661     // of slots (which are all necessarily stack slots, as registers are only in
1662     // the initial chunk)
1663     if (!OptoReg::is_valid(reg) && is_infinite_stack) {
1664       // Bump register mask up to next stack chunk
1665       bool success = lrg->rollover();
1666       if (!success) {
1667         // We should never get here in practice. Bail out in product,
1668         // assert in debug.
1669         assert(false, "the next available stack slots should be within the "
1670                       "OptoRegPair range");
1671         C->record_method_not_compilable(
1672             "chunk-rollover outside of OptoRegPair range");
1673         return -1;
1674       }
1675       goto retry_next_chunk;
1676     }
1677 
1678     //---------------
1679     // Did we get a color?
1680     else if (OptoReg::is_valid(reg)) {
1681 #ifndef PRODUCT
1682       ResourceMark rm(C->regmask_arena());
1683       RegMask avail_rm(lrg->mask(), C->regmask_arena());
1684 #endif
1685 
1686       // Record selected register
1687       lrg->set_reg(reg);
1688 
1689       if (reg >= _max_reg) { // Compute max register limit
1690         _max_reg = OptoReg::add(reg, 1);
1691       }
1692 
1693       // If the live range is not bound, then we actually had some choices
1694       // to make.  In this case, the mask has more bits in it than the colors
1695       // chosen.  Restrict the mask to just what was picked.
1696       int n_regs = lrg->num_regs();
1697       assert(!lrg->_is_vector || !lrg->_fat_proj, "sanity");
1698       if (n_regs == 1 || !lrg->_fat_proj) {
1699         if (Matcher::supports_scalable_vector()) {
1700           assert(!lrg->_is_vector || n_regs <= RegMask::SlotsPerVecA, "sanity");
1701         } else {
1702           assert(!lrg->_is_vector || n_regs <= RegMask::SlotsPerVecZ, "sanity");
1703         }
1704         lrg->Clear();           // Clear the mask
1705         lrg->Insert(reg);       // Set regmask to match selected reg
1706         // For vectors and pairs, also insert the low bit of the pair
1707         // We always choose the high bit, then mask the low bits by register size
1708         if (lrg->is_scalable() && OptoReg::is_stack(lrg->reg())) { // stack
1709           n_regs = lrg->scalable_reg_slots();
1710         }
1711         for (int i = 1; i < n_regs; i++) {
1712           lrg->Insert(OptoReg::add(reg,-i));
1713         }
1714         lrg->set_mask_size(n_regs);
1715       } else {                  // Else fatproj
1716         // mask must be equal to fatproj bits, by definition
1717       }
1718 #ifndef PRODUCT
1719       if (trace_spilling()) {
1720         ttyLocker ttyl;
1721         tty->print("L%d selected ", lidx);
1722         lrg->mask().dump();
1723         tty->print(" from ");
1724         avail_rm.dump();
1725         tty->cr();
1726       }
1727 #endif
1728       // Note that reg is the highest-numbered register in the newly-bound mask.
1729     } // end color available case
1730 
1731     //---------------
1732     // Live range is live and no colors available
1733     else {
1734       assert( lrg->alive(), "" );
1735       assert( !lrg->_fat_proj || lrg->is_multidef() ||
1736               lrg->_def->outcnt() > 0, "fat_proj cannot spill");
1737       assert( !orig_mask.is_infinite_stack(), "infinite stack does not spill" );
1738 
1739       // Assign the special spillreg register
1740       lrg->set_reg(OptoReg::Name(spill_reg++));
1741       // Do not empty the regmask; leave mask_size lying around
1742       // for use during Spilling
1743 #ifndef PRODUCT
1744       if( trace_spilling() ) {
1745         ttyLocker ttyl;
1746         tty->print("L%d spilling with neighbors: ", lidx);
1747         s->dump();
1748         DEBUG_ONLY(tty->print(" original mask: "));
1749         DEBUG_ONLY(orig_mask.dump());
1750         dump_lrg(lidx);
1751       }
1752 #endif
1753     } // end spill case
1754 
1755   }
1756 
1757   return spill_reg-LRG::SPILL_REG;      // Return number of spills
1758 }
1759 
1760 // Set the 'spilled_once' or 'spilled_twice' flag on a node.
1761 void PhaseChaitin::set_was_spilled( Node *n ) {
1762   if( _spilled_once.test_set(n->_idx) )
1763     _spilled_twice.set(n->_idx);
1764 }
1765 
1766 // Convert Ideal spill instructions into proper FramePtr + offset Loads and
1767 // Stores.  Use-def chains are NOT preserved, but Node->LRG->reg maps are.
1768 void PhaseChaitin::fixup_spills() {
1769   // This function does only cisc spill work.
1770   if( !UseCISCSpill ) return;
1771 
1772   Compile::TracePhase tp(_t_fixupSpills);
1773 
1774   // Grab the Frame Pointer
1775   Node *fp = _cfg.get_root_block()->head()->in(1)->in(TypeFunc::FramePtr);
1776 
1777   // For all blocks
1778   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
1779     Block* block = _cfg.get_block(i);
1780 
1781     // For all instructions in block
1782     uint last_inst = block->end_idx();
1783     for (uint j = 1; j <= last_inst; j++) {
1784       Node* n = block->get_node(j);
1785 
1786       // Dead instruction???
1787       assert( n->outcnt() != 0 ||// Nothing dead after post alloc
1788               C->top() == n ||  // Or the random TOP node
1789               n->is_Proj(),     // Or a fat-proj kill node
1790               "No dead instructions after post-alloc" );
1791 
1792       int inp = n->cisc_operand();
1793       if( inp != AdlcVMDeps::Not_cisc_spillable ) {
1794         // Convert operand number to edge index number
1795         MachNode *mach = n->as_Mach();
1796         inp = mach->operand_index(inp);
1797         Node *src = n->in(inp);   // Value to load or store
1798         LRG &lrg_cisc = lrgs(_lrg_map.find_const(src));
1799         OptoReg::Name src_reg = lrg_cisc.reg();
1800         // Doubles record the HIGH register of an adjacent pair.
1801         src_reg = OptoReg::add(src_reg,1-lrg_cisc.num_regs());
1802         if( OptoReg::is_stack(src_reg) ) { // If input is on stack
1803           // This is a CISC Spill, get stack offset and construct new node
1804 #ifndef PRODUCT
1805           if( TraceCISCSpill ) {
1806             tty->print("    reg-instr:  ");
1807             n->dump();
1808           }
1809 #endif
1810           int stk_offset = reg2offset(src_reg);
1811           // Bailout if we might exceed node limit when spilling this instruction
1812           C->check_node_count(0, "out of nodes fixing spills");
1813           if (C->failing())  return;
1814           // Transform node
1815           MachNode *cisc = mach->cisc_version(stk_offset)->as_Mach();
1816           cisc->set_req(inp,fp);          // Base register is frame pointer
1817           if( cisc->oper_input_base() > 1 && mach->oper_input_base() <= 1 ) {
1818             assert( cisc->oper_input_base() == 2, "Only adding one edge");
1819             cisc->ins_req(1,src);         // Requires a memory edge
1820           } else {
1821             // There is no space reserved for a memory edge before the inputs for
1822             // instructions which have "stackSlotX" parameter instead of "memory".
1823             // For example, "MoveF2I_stack_reg". We always need a memory edge from
1824             // src to cisc, else we might schedule cisc before src, loading from a
1825             // spill location before storing the spill. On some platforms, we land
1826             // in this else case because mach->oper_input_base() > 1, i.e. we have
1827             // multiple inputs. In some rare cases there are even multiple memory
1828             // operands, before and after spilling.
1829             // (e.g. spilling "addFPR24_reg_mem" to "addFPR24_mem_cisc")
1830             // In either case, there is no space in the inputs for the memory edge
1831             // so we add an additional precedence / memory edge.
1832             cisc->add_prec(src);
1833           }
1834           block->map_node(cisc, j);          // Insert into basic block
1835           n->subsume_by(cisc, C); // Correct graph
1836           //
1837           ++_used_cisc_instructions;
1838 #ifndef PRODUCT
1839           if( TraceCISCSpill ) {
1840             tty->print("    cisc-instr: ");
1841             cisc->dump();
1842           }
1843 #endif
1844         } else {
1845 #ifndef PRODUCT
1846           if( TraceCISCSpill ) {
1847             tty->print("    using reg-instr: ");
1848             n->dump();
1849           }
1850 #endif
1851           ++_unused_cisc_instructions;    // input can be on stack
1852         }
1853       }
1854 
1855     } // End of for all instructions
1856 
1857   } // End of for all blocks
1858 }
1859 
1860 // Helper to stretch above; recursively discover the base Node for a
1861 // given derived Node.  Easy for AddP-related machine nodes, but needs
1862 // to be recursive for derived Phis.
1863 Node* PhaseChaitin::find_base_for_derived(Node** derived_base_map, Node* derived, uint& maxlrg) {
1864   // See if already computed; if so return it
1865   if (derived_base_map[derived->_idx]) {
1866     return derived_base_map[derived->_idx];
1867   }
1868 
1869 #ifdef ASSERT
1870   if (derived->is_Mach() && derived->as_Mach()->ideal_Opcode() == Op_VerifyVectorAlignment) {
1871     // Bypass the verification node
1872     Node* base = find_base_for_derived(derived_base_map, derived->in(1), maxlrg);
1873     derived_base_map[derived->_idx] = base;
1874     return base;
1875   }
1876 #endif
1877 
1878   // See if this happens to be a base.
1879   // NOTE: we use TypePtr instead of TypeOopPtr because we can have
1880   // pointers derived from null!  These are always along paths that
1881   // can't happen at run-time but the optimizer cannot deduce it so
1882   // we have to handle it gracefully.
1883   assert(!derived->bottom_type()->isa_narrowoop() ||
1884          derived->bottom_type()->make_ptr()->is_ptr()->offset() == 0, "sanity");
1885   const TypePtr *tj = derived->bottom_type()->isa_ptr();
1886   // If its an OOP with a non-zero offset, then it is derived.
1887   if (tj == nullptr || tj->offset() == 0) {
1888     derived_base_map[derived->_idx] = derived;
1889     return derived;
1890   }
1891   // Derived is null+offset?  Base is null!
1892   if( derived->is_Con() ) {
1893     Node *base = _matcher.mach_null();
1894     assert(base != nullptr, "sanity");
1895     if (base->in(0) == nullptr) {
1896       // Initialize it once and make it shared:
1897       // set control to _root and place it into Start block
1898       // (where top() node is placed).
1899       base->init_req(0, _cfg.get_root_node());
1900       Block *startb = _cfg.get_block_for_node(C->top());
1901       uint node_pos = startb->find_node(C->top());
1902       startb->insert_node(base, node_pos);
1903       _cfg.map_node_to_block(base, startb);
1904       assert(_lrg_map.live_range_id(base) == 0, "should not have LRG yet");
1905 
1906       // The loadConP0 might have projection nodes depending on architecture
1907       // Add the projection nodes to the CFG
1908       for (DUIterator_Fast imax, i = base->fast_outs(imax); i < imax; i++) {
1909         Node* use = base->fast_out(i);
1910         if (use->is_MachProj()) {
1911           startb->insert_node(use, ++node_pos);
1912           _cfg.map_node_to_block(use, startb);
1913           new_lrg(use, maxlrg++);
1914         }
1915       }
1916     }
1917     if (_lrg_map.live_range_id(base) == 0) {
1918       new_lrg(base, maxlrg++);
1919     }
1920     assert(base->in(0) == _cfg.get_root_node() && _cfg.get_block_for_node(base) == _cfg.get_block_for_node(C->top()), "base null should be shared");
1921     derived_base_map[derived->_idx] = base;
1922     return base;
1923   }
1924 
1925   // Check for AddP-related opcodes
1926   if (!derived->is_Phi()) {
1927     assert(derived->as_Mach()->ideal_Opcode() == Op_AddP, "but is: %s", derived->Name());
1928     Node *base = derived->in(AddPNode::Base);
1929     derived_base_map[derived->_idx] = base;
1930     return base;
1931   }
1932 
1933   // Recursively find bases for Phis.
1934   // First check to see if we can avoid a base Phi here.
1935   Node *base = find_base_for_derived( derived_base_map, derived->in(1),maxlrg);
1936   uint i;
1937   for( i = 2; i < derived->req(); i++ )
1938     if( base != find_base_for_derived( derived_base_map,derived->in(i),maxlrg))
1939       break;
1940   // Went to the end without finding any different bases?
1941   if( i == derived->req() ) {   // No need for a base Phi here
1942     derived_base_map[derived->_idx] = base;
1943     return base;
1944   }
1945 
1946   // Now we see we need a base-Phi here to merge the bases
1947   const Type *t = base->bottom_type();
1948   base = new PhiNode( derived->in(0), t );
1949   for( i = 1; i < derived->req(); i++ ) {
1950     base->init_req(i, find_base_for_derived(derived_base_map, derived->in(i), maxlrg));
1951     t = t->meet(base->in(i)->bottom_type());
1952   }
1953   base->as_Phi()->set_type(t);
1954 
1955   // Search the current block for an existing base-Phi
1956   Block *b = _cfg.get_block_for_node(derived);
1957   for( i = 1; i <= b->end_idx(); i++ ) {// Search for matching Phi
1958     Node *phi = b->get_node(i);
1959     if( !phi->is_Phi() ) {      // Found end of Phis with no match?
1960       b->insert_node(base,  i); // Must insert created Phi here as base
1961       _cfg.map_node_to_block(base, b);
1962       new_lrg(base,maxlrg++);
1963       break;
1964     }
1965     // See if Phi matches.
1966     uint j;
1967     for( j = 1; j < base->req(); j++ )
1968       if( phi->in(j) != base->in(j) &&
1969           !(phi->in(j)->is_Con() && base->in(j)->is_Con()) ) // allow different nulls
1970         break;
1971     if( j == base->req() ) {    // All inputs match?
1972       base = phi;               // Then use existing 'phi' and drop 'base'
1973       break;
1974     }
1975   }
1976 
1977 
1978   // Cache info for later passes
1979   derived_base_map[derived->_idx] = base;
1980   return base;
1981 }
1982 
1983 // At each Safepoint, insert extra debug edges for each pair of derived value/
1984 // base pointer that is live across the Safepoint for oopmap building.  The
1985 // edge pairs get added in after sfpt->jvmtail()->oopoff(), but are in the
1986 // required edge set.
1987 bool PhaseChaitin::stretch_base_pointer_live_ranges(ResourceArea *a) {
1988   int must_recompute_live = false;
1989   uint maxlrg = _lrg_map.max_lrg_id();
1990   Node **derived_base_map = (Node**)a->Amalloc(sizeof(Node*)*C->unique());
1991   memset( derived_base_map, 0, sizeof(Node*)*C->unique() );
1992 
1993   // For all blocks in RPO do...
1994   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
1995     Block* block = _cfg.get_block(i);
1996     // Note use of deep-copy constructor.  I cannot hammer the original
1997     // liveout bits, because they are needed by the following coalesce pass.
1998     IndexSet liveout(_live->live(block));
1999 
2000     for (uint j = block->end_idx() + 1; j > 1; j--) {
2001       Node* n = block->get_node(j - 1);
2002 
2003       // Pre-split compares of loop-phis.  Loop-phis form a cycle we would
2004       // like to see in the same register.  Compare uses the loop-phi and so
2005       // extends its live range BUT cannot be part of the cycle.  If this
2006       // extended live range overlaps with the update of the loop-phi value
2007       // we need both alive at the same time -- which requires at least 1
2008       // copy.  But because Intel has only 2-address registers we end up with
2009       // at least 2 copies, one before the loop-phi update instruction and
2010       // one after.  Instead we split the input to the compare just after the
2011       // phi.
2012       if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CmpI ) {
2013         Node *phi = n->in(1);
2014         if( phi->is_Phi() && phi->as_Phi()->region()->is_Loop() ) {
2015           Block *phi_block = _cfg.get_block_for_node(phi);
2016           if (_cfg.get_block_for_node(phi_block->pred(2)) == block) {
2017             const RegMask *mask = C->matcher()->idealreg2spillmask[Op_RegI];
2018             Node *spill = new MachSpillCopyNode(MachSpillCopyNode::LoopPhiInput, phi, *mask, *mask);
2019             insert_proj( phi_block, 1, spill, maxlrg++ );
2020             n->set_req(1,spill);
2021             must_recompute_live = true;
2022           }
2023         }
2024       }
2025 
2026       // Get value being defined
2027       uint lidx = _lrg_map.live_range_id(n);
2028       // Ignore the occasional brand-new live range
2029       if (lidx && lidx < _lrg_map.max_lrg_id()) {
2030         // Remove from live-out set
2031         liveout.remove(lidx);
2032 
2033         // Copies do not define a new value and so do not interfere.
2034         // Remove the copies source from the liveout set before interfering.
2035         uint idx = n->is_Copy();
2036         if (idx) {
2037           liveout.remove(_lrg_map.live_range_id(n->in(idx)));
2038         }
2039       }
2040 
2041       // Found a safepoint?
2042       JVMState *jvms = n->jvms();
2043       if (jvms && !liveout.is_empty()) {
2044         // Now scan for a live derived pointer
2045         IndexSetIterator elements(&liveout);
2046         uint neighbor;
2047         while ((neighbor = elements.next()) != 0) {
2048           // Find reaching DEF for base and derived values
2049           // This works because we are still in SSA during this call.
2050           Node *derived = lrgs(neighbor)._def;
2051           const TypePtr *tj = derived->bottom_type()->isa_ptr();
2052           assert(!derived->bottom_type()->isa_narrowoop() ||
2053                  derived->bottom_type()->make_ptr()->is_ptr()->offset() == 0, "sanity");
2054           // If its an OOP with a non-zero offset, then it is derived.
2055           if (tj && tj->offset() != 0 && tj->isa_oop_ptr()) {
2056             Node *base = find_base_for_derived(derived_base_map, derived, maxlrg);
2057             assert(base->_idx < _lrg_map.size(), "");
2058             // Add reaching DEFs of derived pointer and base pointer as a
2059             // pair of inputs
2060             n->add_req(derived);
2061             n->add_req(base);
2062 
2063             // See if the base pointer is already live to this point.
2064             // Since I'm working on the SSA form, live-ness amounts to
2065             // reaching def's.  So if I find the base's live range then
2066             // I know the base's def reaches here.
2067             if ((_lrg_map.live_range_id(base) >= _lrg_map.max_lrg_id() || // (Brand new base (hence not live) or
2068                  !liveout.member(_lrg_map.live_range_id(base))) && // not live) AND
2069                  (_lrg_map.live_range_id(base) > 0) && // not a constant
2070                  _cfg.get_block_for_node(base) != block) { // base not def'd in blk)
2071               // Base pointer is not currently live.  Since I stretched
2072               // the base pointer to here and it crosses basic-block
2073               // boundaries, the global live info is now incorrect.
2074               // Recompute live.
2075               must_recompute_live = true;
2076             } // End of if base pointer is not live to debug info
2077           }
2078         } // End of scan all live data for derived ptrs crossing GC point
2079       } // End of if found a GC point
2080 
2081       // Make all inputs live
2082       if (!n->is_Phi()) {      // Phi function uses come from prior block
2083         for (uint k = 1; k < n->req(); k++) {
2084           uint lidx = _lrg_map.live_range_id(n->in(k));
2085           if (lidx < _lrg_map.max_lrg_id()) {
2086             liveout.insert(lidx);
2087           }
2088         }
2089       }
2090 
2091     } // End of forall instructions in block
2092     liveout.clear();  // Free the memory used by liveout.
2093 
2094   } // End of forall blocks
2095   _lrg_map.set_max_lrg_id(maxlrg);
2096 
2097   // If I created a new live range I need to recompute live
2098   if (maxlrg != _ifg->_maxlrg) {
2099     must_recompute_live = true;
2100   }
2101 
2102   return must_recompute_live != 0;
2103 }
2104 
2105 // Extend the node to LRG mapping
2106 
2107 void PhaseChaitin::add_reference(const Node *node, const Node *old_node) {
2108   _lrg_map.extend(node->_idx, _lrg_map.live_range_id(old_node));
2109 }
2110 
2111 #ifndef PRODUCT
2112 void PhaseChaitin::dump(const Node* n) const {
2113   uint r = (n->_idx < _lrg_map.size()) ? _lrg_map.find_const(n) : 0;
2114   tty->print("L%d",r);
2115   if (r && n->Opcode() != Op_Phi) {
2116     if( _node_regs ) {          // Got a post-allocation copy of allocation?
2117       tty->print("[");
2118       OptoReg::Name second = get_reg_second(n);
2119       if( OptoReg::is_valid(second) ) {
2120         if( OptoReg::is_reg(second) )
2121           tty->print("%s:",Matcher::regName[second]);
2122         else
2123           tty->print("%s+%d:",OptoReg::regname(OptoReg::c_frame_pointer), reg2offset_unchecked(second));
2124       }
2125       OptoReg::Name first = get_reg_first(n);
2126       if( OptoReg::is_reg(first) )
2127         tty->print("%s]",Matcher::regName[first]);
2128       else
2129          tty->print("%s+%d]",OptoReg::regname(OptoReg::c_frame_pointer), reg2offset_unchecked(first));
2130     } else
2131     n->out_RegMask().dump();
2132   }
2133   tty->print("/N%d\t",n->_idx);
2134   tty->print("%s === ", n->Name());
2135   uint k;
2136   for (k = 0; k < n->req(); k++) {
2137     Node *m = n->in(k);
2138     if (!m) {
2139       tty->print("_ ");
2140     }
2141     else {
2142       uint r = (m->_idx < _lrg_map.size()) ? _lrg_map.find_const(m) : 0;
2143       tty->print("L%d",r);
2144       // Data MultiNode's can have projections with no real registers.
2145       // Don't die while dumping them.
2146       int op = n->Opcode();
2147       if( r && op != Op_Phi && op != Op_Proj && op != Op_SCMemProj) {
2148         if( _node_regs ) {
2149           tty->print("[");
2150           OptoReg::Name second = get_reg_second(n->in(k));
2151           if( OptoReg::is_valid(second) ) {
2152             if( OptoReg::is_reg(second) )
2153               tty->print("%s:",Matcher::regName[second]);
2154             else
2155               tty->print("%s+%d:",OptoReg::regname(OptoReg::c_frame_pointer),
2156                          reg2offset_unchecked(second));
2157           }
2158           OptoReg::Name first = get_reg_first(n->in(k));
2159           if( OptoReg::is_reg(first) )
2160             tty->print("%s]",Matcher::regName[first]);
2161           else
2162             tty->print("%s+%d]",OptoReg::regname(OptoReg::c_frame_pointer),
2163                        reg2offset_unchecked(first));
2164         } else
2165           n->in_RegMask(k).dump();
2166       }
2167       tty->print("/N%d ",m->_idx);
2168     }
2169   }
2170   if( k < n->len() && n->in(k) ) tty->print("| ");
2171   for( ; k < n->len(); k++ ) {
2172     Node *m = n->in(k);
2173     if(!m) {
2174       break;
2175     }
2176     uint r = (m->_idx < _lrg_map.size()) ? _lrg_map.find_const(m) : 0;
2177     tty->print("L%d",r);
2178     tty->print("/N%d ",m->_idx);
2179   }
2180   if( n->is_Mach() ) n->as_Mach()->dump_spec(tty);
2181   else n->dump_spec(tty);
2182   if( _spilled_once.test(n->_idx ) ) {
2183     tty->print(" Spill_1");
2184     if( _spilled_twice.test(n->_idx ) )
2185       tty->print(" Spill_2");
2186   }
2187   tty->print("\n");
2188 }
2189 
2190 void PhaseChaitin::dump(const Block* b) const {
2191   b->dump_head(&_cfg);
2192 
2193   // For all instructions
2194   for( uint j = 0; j < b->number_of_nodes(); j++ )
2195     dump(b->get_node(j));
2196   // Print live-out info at end of block
2197   if( _live ) {
2198     tty->print("Liveout: ");
2199     IndexSet *live = _live->live(b);
2200     IndexSetIterator elements(live);
2201     tty->print("{");
2202     uint i;
2203     while ((i = elements.next()) != 0) {
2204       tty->print("L%d ", _lrg_map.find_const(i));
2205     }
2206     tty->print_cr("}");
2207   }
2208   tty->print("\n");
2209 }
2210 
2211 void PhaseChaitin::dump() const {
2212   tty->print( "--- Chaitin -- argsize: %d  framesize: %d ---\n",
2213               _matcher._new_SP, _framesize );
2214 
2215   // For all blocks
2216   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
2217     dump(_cfg.get_block(i));
2218   }
2219   // End of per-block dump
2220   tty->print("\n");
2221 
2222   if (!_ifg) {
2223     tty->print("(No IFG.)\n");
2224     return;
2225   }
2226 
2227   // Dump LRG array
2228   tty->print("--- Live RanGe Array ---\n");
2229   for (uint i2 = 1; i2 < _lrg_map.max_lrg_id(); i2++) {
2230     tty->print("L%d: ",i2);
2231     if (i2 < _ifg->_maxlrg) {
2232       lrgs(i2).dump();
2233     }
2234     else {
2235       tty->print_cr("new LRG");
2236     }
2237   }
2238   tty->cr();
2239 
2240   // Dump lo-degree list
2241   tty->print("Lo degree: ");
2242   for(uint i3 = _lo_degree; i3; i3 = lrgs(i3)._next )
2243     tty->print("L%d ",i3);
2244   tty->cr();
2245 
2246   // Dump lo-stk-degree list
2247   tty->print("Lo stk degree: ");
2248   for(uint i4 = _lo_stk_degree; i4; i4 = lrgs(i4)._next )
2249     tty->print("L%d ",i4);
2250   tty->cr();
2251 
2252   // Dump lo-degree list
2253   tty->print("Hi degree: ");
2254   for(uint i5 = _hi_degree; i5; i5 = lrgs(i5)._next )
2255     tty->print("L%d ",i5);
2256   tty->cr();
2257 }
2258 
2259 void PhaseChaitin::dump_degree_lists() const {
2260   // Dump lo-degree list
2261   tty->print("Lo degree: ");
2262   for( uint i = _lo_degree; i; i = lrgs(i)._next )
2263     tty->print("L%d ",i);
2264   tty->cr();
2265 
2266   // Dump lo-stk-degree list
2267   tty->print("Lo stk degree: ");
2268   for(uint i2 = _lo_stk_degree; i2; i2 = lrgs(i2)._next )
2269     tty->print("L%d ",i2);
2270   tty->cr();
2271 
2272   // Dump lo-degree list
2273   tty->print("Hi degree: ");
2274   for(uint i3 = _hi_degree; i3; i3 = lrgs(i3)._next )
2275     tty->print("L%d ",i3);
2276   tty->cr();
2277 }
2278 
2279 void PhaseChaitin::dump_simplified() const {
2280   tty->print("Simplified: ");
2281   for( uint i = _simplified; i; i = lrgs(i)._next )
2282     tty->print("L%d ",i);
2283   tty->cr();
2284 }
2285 
2286 static char *print_reg(OptoReg::Name reg, const PhaseChaitin* pc, char* buf, size_t buf_size) {
2287   if ((int)reg < 0)
2288     os::snprintf_checked(buf, buf_size, "<OptoReg::%d>", (int)reg);
2289   else if (OptoReg::is_reg(reg))
2290     strcpy(buf, Matcher::regName[reg]);
2291   else
2292     os::snprintf_checked(buf, buf_size, "%s + #%d",OptoReg::regname(OptoReg::c_frame_pointer),
2293             pc->reg2offset(reg));
2294   return buf+strlen(buf);
2295 }
2296 
2297 // Dump a register name into a buffer.  Be intelligent if we get called
2298 // before allocation is complete.
2299 char *PhaseChaitin::dump_register(const Node* n, char* buf, size_t buf_size) const {
2300   if( _node_regs ) {
2301     // Post allocation, use direct mappings, no LRG info available
2302     print_reg( get_reg_first(n), this, buf, buf_size);
2303   } else {
2304     uint lidx = _lrg_map.find_const(n); // Grab LRG number
2305     if( !_ifg ) {
2306       os::snprintf_checked(buf, buf_size, "L%d",lidx);  // No register binding yet
2307     } else if( !lidx ) {        // Special, not allocated value
2308       strcpy(buf,"Special");
2309     } else {
2310       if (lrgs(lidx)._is_vector) {
2311         if (lrgs(lidx).mask().is_bound_set(lrgs(lidx).num_regs()))
2312           print_reg( lrgs(lidx).reg(), this, buf, buf_size); // a bound machine register
2313         else
2314           os::snprintf_checked(buf, buf_size, "L%d",lidx); // No register binding yet
2315       } else if( (lrgs(lidx).num_regs() == 1)
2316                  ? lrgs(lidx).mask().is_bound1()
2317                  : lrgs(lidx).mask().is_bound_pair() ) {
2318         // Hah!  We have a bound machine register
2319         print_reg( lrgs(lidx).reg(), this, buf, buf_size);
2320       } else {
2321         os::snprintf_checked(buf, buf_size, "L%d",lidx); // No register binding yet
2322       }
2323     }
2324   }
2325   return buf+strlen(buf);
2326 }
2327 
2328 void PhaseChaitin::dump_for_spill_split_recycle() const {
2329   if( WizardMode && (PrintCompilation || PrintOpto) ) {
2330     // Display which live ranges need to be split and the allocator's state
2331     tty->print_cr("Graph-Coloring Iteration %d will split the following live ranges", _trip_cnt);
2332     for (uint bidx = 1; bidx < _lrg_map.max_lrg_id(); bidx++) {
2333       if( lrgs(bidx).alive() && lrgs(bidx).reg() >= LRG::SPILL_REG ) {
2334         tty->print("L%d: ", bidx);
2335         lrgs(bidx).dump();
2336       }
2337     }
2338     tty->cr();
2339     dump();
2340   }
2341 }
2342 
2343 void PhaseChaitin::dump_frame() const {
2344   const char *fp = OptoReg::regname(OptoReg::c_frame_pointer);
2345   const TypeTuple *domain = C->tf()->domain_cc();
2346   const int        argcnt = domain->cnt() - TypeFunc::Parms;
2347 
2348   // Incoming arguments in registers dump
2349   for( int k = 0; k < argcnt; k++ ) {
2350     OptoReg::Name parmreg = _matcher._parm_regs[k].first();
2351     if( OptoReg::is_reg(parmreg))  {
2352       const char *reg_name = OptoReg::regname(parmreg);
2353       tty->print("#r%3.3d %s", parmreg, reg_name);
2354       parmreg = _matcher._parm_regs[k].second();
2355       if( OptoReg::is_reg(parmreg))  {
2356         tty->print(":%s", OptoReg::regname(parmreg));
2357       }
2358       tty->print("   : parm %d: ", k);
2359       domain->field_at(k + TypeFunc::Parms)->dump();
2360       tty->cr();
2361     }
2362   }
2363 
2364   // Check for un-owned padding above incoming args
2365   OptoReg::Name reg = _matcher._new_SP;
2366   if( reg > _matcher._in_arg_limit ) {
2367     reg = OptoReg::add(reg, -1);
2368     tty->print_cr("#r%3.3d %s+%2d: pad0, owned by CALLER", reg, fp, reg2offset_unchecked(reg));
2369   }
2370 
2371   // Incoming argument area dump
2372   OptoReg::Name begin_in_arg = OptoReg::add(_matcher._old_SP,C->out_preserve_stack_slots());
2373   while( reg > begin_in_arg ) {
2374     reg = OptoReg::add(reg, -1);
2375     tty->print("#r%3.3d %s+%2d: ",reg,fp,reg2offset_unchecked(reg));
2376     int j;
2377     for( j = 0; j < argcnt; j++) {
2378       if( _matcher._parm_regs[j].first() == reg ||
2379           _matcher._parm_regs[j].second() == reg ) {
2380         tty->print("parm %d: ",j);
2381         domain->field_at(j + TypeFunc::Parms)->dump();
2382         tty->cr();
2383         break;
2384       }
2385     }
2386     if( j >= argcnt )
2387       tty->print_cr("HOLE, owned by SELF");
2388   }
2389 
2390   // Old outgoing preserve area
2391   while( reg > _matcher._old_SP ) {
2392     reg = OptoReg::add(reg, -1);
2393     tty->print_cr("#r%3.3d %s+%2d: old out preserve",reg,fp,reg2offset_unchecked(reg));
2394   }
2395 
2396   // Old SP
2397   tty->print_cr("# -- Old %s -- Framesize: %d --",fp,
2398     reg2offset_unchecked(OptoReg::add(_matcher._old_SP,-1)) - reg2offset_unchecked(_matcher._new_SP)+jintSize);
2399 
2400   // Preserve area dump
2401   int fixed_slots = C->fixed_slots();
2402   OptoReg::Name begin_in_preserve = OptoReg::add(_matcher._old_SP, -(int)C->in_preserve_stack_slots());
2403   OptoReg::Name return_addr = _matcher.return_addr();
2404 
2405   reg = OptoReg::add(reg, -1);
2406   while (OptoReg::is_stack(reg)) {
2407     tty->print("#r%3.3d %s+%2d: ",reg,fp,reg2offset_unchecked(reg));
2408     if (return_addr == reg) {
2409       tty->print_cr("return address");
2410     } else if (reg >= begin_in_preserve) {
2411       // Preserved slots are present on x86
2412       if (return_addr == OptoReg::add(reg, VMRegImpl::slots_per_word))
2413         tty->print_cr("saved fp register");
2414       else if (return_addr == OptoReg::add(reg, 2*VMRegImpl::slots_per_word) &&
2415                VerifyStackAtCalls)
2416         tty->print_cr("0xBADB100D   +VerifyStackAtCalls");
2417       else
2418         tty->print_cr("in_preserve");
2419     } else if ((int)OptoReg::reg2stack(reg) < fixed_slots) {
2420       tty->print_cr("Fixed slot %d", OptoReg::reg2stack(reg));
2421     } else {
2422       tty->print_cr("pad2, stack alignment");
2423     }
2424     reg = OptoReg::add(reg, -1);
2425   }
2426 
2427   // Spill area dump
2428   reg = OptoReg::add(_matcher._new_SP, _framesize );
2429   while( reg > _matcher._out_arg_limit ) {
2430     reg = OptoReg::add(reg, -1);
2431     tty->print_cr("#r%3.3d %s+%2d: spill",reg,fp,reg2offset_unchecked(reg));
2432   }
2433 
2434   // Outgoing argument area dump
2435   while( reg > OptoReg::add(_matcher._new_SP, C->out_preserve_stack_slots()) ) {
2436     reg = OptoReg::add(reg, -1);
2437     tty->print_cr("#r%3.3d %s+%2d: outgoing argument",reg,fp,reg2offset_unchecked(reg));
2438   }
2439 
2440   // Outgoing new preserve area
2441   while( reg > _matcher._new_SP ) {
2442     reg = OptoReg::add(reg, -1);
2443     tty->print_cr("#r%3.3d %s+%2d: new out preserve",reg,fp,reg2offset_unchecked(reg));
2444   }
2445   tty->print_cr("#");
2446 }
2447 
2448 void PhaseChaitin::dump_bb(uint pre_order) const {
2449   tty->print_cr("---dump of B%d---",pre_order);
2450   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
2451     Block* block = _cfg.get_block(i);
2452     if (block->_pre_order == pre_order) {
2453       dump(block);
2454     }
2455   }
2456 }
2457 
2458 void PhaseChaitin::dump_lrg(uint lidx, bool defs_only) const {
2459   tty->print_cr("---dump of L%d---",lidx);
2460 
2461   if (_ifg) {
2462     if (lidx >= _lrg_map.max_lrg_id()) {
2463       tty->print("Attempt to print live range index beyond max live range.\n");
2464       return;
2465     }
2466     tty->print("L%d: ",lidx);
2467     if (lidx < _ifg->_maxlrg) {
2468       lrgs(lidx).dump();
2469     } else {
2470       tty->print_cr("new LRG");
2471     }
2472   }
2473   if( _ifg && lidx < _ifg->_maxlrg) {
2474     tty->print("Neighbors: %d - ", _ifg->neighbor_cnt(lidx));
2475     _ifg->neighbors(lidx)->dump();
2476     tty->cr();
2477   }
2478   // For all blocks
2479   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
2480     Block* block = _cfg.get_block(i);
2481     int dump_once = 0;
2482 
2483     // For all instructions
2484     for( uint j = 0; j < block->number_of_nodes(); j++ ) {
2485       Node *n = block->get_node(j);
2486       if (_lrg_map.find_const(n) == lidx) {
2487         if (!dump_once++) {
2488           tty->cr();
2489           block->dump_head(&_cfg);
2490         }
2491         dump(n);
2492         continue;
2493       }
2494       if (!defs_only) {
2495         uint cnt = n->req();
2496         for( uint k = 1; k < cnt; k++ ) {
2497           Node *m = n->in(k);
2498           if (!m)  {
2499             continue;  // be robust in the dumper
2500           }
2501           if (_lrg_map.find_const(m) == lidx) {
2502             if (!dump_once++) {
2503               tty->cr();
2504               block->dump_head(&_cfg);
2505             }
2506             dump(n);
2507           }
2508         }
2509       }
2510     }
2511   } // End of per-block dump
2512   tty->cr();
2513 }
2514 #endif // not PRODUCT
2515 
2516 #ifdef ASSERT
2517 // Verify that base pointers and derived pointers are still sane.
2518 void PhaseChaitin::verify_base_ptrs(ResourceArea* a) const {
2519   Unique_Node_List worklist(a);
2520   for (uint i = 0; i < _cfg.number_of_blocks(); i++) {
2521     Block* block = _cfg.get_block(i);
2522     for (uint j = block->end_idx() + 1; j > 1; j--) {
2523       Node* n = block->get_node(j-1);
2524       if (n->is_Phi()) {
2525         break;
2526       }
2527       // Found a safepoint?
2528       if (n->is_MachSafePoint()) {
2529         MachSafePointNode* sfpt = n->as_MachSafePoint();
2530         JVMState* jvms = sfpt->jvms();
2531         if (jvms != nullptr) {
2532           // Now scan for a live derived pointer
2533           if (jvms->oopoff() < sfpt->req()) {
2534             // Check each derived/base pair
2535             for (uint idx = jvms->oopoff(); idx < sfpt->req(); idx++) {
2536               Node* check = sfpt->in(idx);
2537               bool is_derived = ((idx - jvms->oopoff()) & 1) == 0;
2538               // search upwards through spills and spill phis for AddP
2539               worklist.clear();
2540               worklist.push(check);
2541               uint k = 0;
2542               while (k < worklist.size()) {
2543                 check = worklist.at(k);
2544                 assert(check, "Bad base or derived pointer");
2545                 // See PhaseChaitin::find_base_for_derived() for all cases.
2546                 int isc = check->is_Copy();
2547                 if (isc) {
2548                   worklist.push(check->in(isc));
2549                 } else if (check->is_Phi()) {
2550                   for (uint m = 1; m < check->req(); m++) {
2551                     worklist.push(check->in(m));
2552                   }
2553                 } else if (check->is_Con()) {
2554                   if (is_derived && check->bottom_type()->is_ptr()->offset() != 0) {
2555                     // Derived is null+non-zero offset, base must be null.
2556                     assert(check->bottom_type()->is_ptr()->ptr() == TypePtr::Null, "Bad derived pointer");
2557                   } else {
2558                     assert(check->bottom_type()->is_ptr()->offset() == 0, "Bad base pointer");
2559                     // Base either ConP(nullptr) or loadConP
2560                     if (check->is_Mach()) {
2561                       assert(check->as_Mach()->ideal_Opcode() == Op_ConP, "Bad base pointer");
2562                     } else {
2563                       assert(check->Opcode() == Op_ConP &&
2564                              check->bottom_type()->is_ptr()->ptr() == TypePtr::Null, "Bad base pointer");
2565                     }
2566                   }
2567                 } else if (check->bottom_type()->is_ptr()->offset() == 0) {
2568                   if (check->is_Proj() || (check->is_Mach() &&
2569                      (check->as_Mach()->ideal_Opcode() == Op_CreateEx ||
2570                       check->as_Mach()->ideal_Opcode() == Op_ThreadLocal ||
2571                       check->as_Mach()->ideal_Opcode() == Op_CMoveP ||
2572                       check->as_Mach()->ideal_Opcode() == Op_CheckCastPP ||
2573 #ifdef _LP64
2574                       (UseCompressedOops && check->as_Mach()->ideal_Opcode() == Op_CastPP) ||
2575                       (UseCompressedOops && check->as_Mach()->ideal_Opcode() == Op_DecodeN) ||
2576                       (UseCompressedClassPointers && check->as_Mach()->ideal_Opcode() == Op_DecodeNKlass) ||
2577 #endif // _LP64
2578                       check->as_Mach()->ideal_Opcode() == Op_LoadP ||
2579                       check->as_Mach()->ideal_Opcode() == Op_LoadKlass))) {
2580                     // Valid nodes
2581                   } else {
2582                     check->dump();
2583                     assert(false, "Bad base or derived pointer");
2584                   }
2585                 } else {
2586                   assert(is_derived, "Bad base pointer");
2587                   assert(check->is_Mach() && check->as_Mach()->ideal_Opcode() == Op_AddP, "Bad derived pointer");
2588                 }
2589                 k++;
2590                 assert(k < 100000, "Derived pointer checking in infinite loop");
2591               } // End while
2592             }
2593           } // End of check for derived pointers
2594         } // End of Kcheck for debug info
2595       } // End of if found a safepoint
2596     } // End of forall instructions in block
2597   } // End of forall blocks
2598 }
2599 
2600 // Verify that graphs and base pointers are still sane.
2601 void PhaseChaitin::verify(ResourceArea* a, bool verify_ifg) const {
2602   if (VerifyRegisterAllocator) {
2603     _cfg.verify();
2604     if (C->failing()) {
2605       return;
2606     }
2607     verify_base_ptrs(a);
2608     if (verify_ifg) {
2609       _ifg->verify(this);
2610     }
2611   }
2612 }
2613 #endif // ASSERT
2614 
2615 int PhaseChaitin::_final_loads  = 0;
2616 int PhaseChaitin::_final_stores = 0;
2617 int PhaseChaitin::_final_memoves= 0;
2618 int PhaseChaitin::_final_copies = 0;
2619 double PhaseChaitin::_final_load_cost  = 0;
2620 double PhaseChaitin::_final_store_cost = 0;
2621 double PhaseChaitin::_final_memove_cost= 0;
2622 double PhaseChaitin::_final_copy_cost  = 0;
2623 int PhaseChaitin::_conserv_coalesce = 0;
2624 int PhaseChaitin::_conserv_coalesce_pair = 0;
2625 int PhaseChaitin::_conserv_coalesce_trie = 0;
2626 int PhaseChaitin::_conserv_coalesce_quad = 0;
2627 int PhaseChaitin::_post_alloc = 0;
2628 int PhaseChaitin::_lost_opp_pp_coalesce = 0;
2629 int PhaseChaitin::_lost_opp_cflow_coalesce = 0;
2630 int PhaseChaitin::_used_cisc_instructions   = 0;
2631 int PhaseChaitin::_unused_cisc_instructions = 0;
2632 int PhaseChaitin::_allocator_attempts       = 0;
2633 int PhaseChaitin::_allocator_successes      = 0;
2634 
2635 #ifndef PRODUCT
2636 uint PhaseChaitin::_high_pressure           = 0;
2637 uint PhaseChaitin::_low_pressure            = 0;
2638 
2639 void PhaseChaitin::print_chaitin_statistics() {
2640   tty->print_cr("Inserted %d spill loads, %d spill stores, %d mem-mem moves and %d copies.", _final_loads, _final_stores, _final_memoves, _final_copies);
2641   tty->print_cr("Total load cost= %6.0f, store cost = %6.0f, mem-mem cost = %5.2f, copy cost = %5.0f.", _final_load_cost, _final_store_cost, _final_memove_cost, _final_copy_cost);
2642   tty->print_cr("Adjusted spill cost = %7.0f.",
2643                 _final_load_cost*4.0 + _final_store_cost  * 2.0 +
2644                 _final_copy_cost*1.0 + _final_memove_cost*12.0);
2645   tty->print("Conservatively coalesced %d copies, %d pairs",
2646                 _conserv_coalesce, _conserv_coalesce_pair);
2647   if( _conserv_coalesce_trie || _conserv_coalesce_quad )
2648     tty->print(", %d tries, %d quads", _conserv_coalesce_trie, _conserv_coalesce_quad);
2649   tty->print_cr(", %d post alloc.", _post_alloc);
2650   if( _lost_opp_pp_coalesce || _lost_opp_cflow_coalesce )
2651     tty->print_cr("Lost coalesce opportunity, %d private-private, and %d cflow interfered.",
2652                   _lost_opp_pp_coalesce, _lost_opp_cflow_coalesce );
2653   if( _used_cisc_instructions || _unused_cisc_instructions )
2654     tty->print_cr("Used cisc instruction  %d,  remained in register %d",
2655                    _used_cisc_instructions, _unused_cisc_instructions);
2656   if( _allocator_successes != 0 )
2657     tty->print_cr("Average allocation trips %f", (float)_allocator_attempts/(float)_allocator_successes);
2658   tty->print_cr("High Pressure Blocks = %d, Low Pressure Blocks = %d", _high_pressure, _low_pressure);
2659 }
2660 #endif // not PRODUCT