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