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