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