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