1 /*
   2  * Copyright (c) 1997, 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 #ifndef SHARE_OPTO_CHAITIN_HPP
  26 #define SHARE_OPTO_CHAITIN_HPP
  27 
  28 #include "code/vmreg.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "opto/connode.hpp"
  31 #include "opto/live.hpp"
  32 #include "opto/machnode.hpp"
  33 #include "opto/matcher.hpp"
  34 #include "opto/phase.hpp"
  35 #include "opto/regalloc.hpp"
  36 #include "opto/regmask.hpp"
  37 
  38 class Matcher;
  39 class PhaseCFG;
  40 class PhaseLive;
  41 class PhaseRegAlloc;
  42 class PhaseChaitin;
  43 
  44 #define OPTO_DEBUG_SPLIT_FREQ  BLOCK_FREQUENCY(0.001)
  45 #define OPTO_LRG_HIGH_FREQ     BLOCK_FREQUENCY(0.25)
  46 
  47 //------------------------------LRG--------------------------------------------
  48 // Live-RanGe structure.
  49 class LRG : public ResourceObj {
  50   friend class VMStructs;
  51 public:
  52   static const uint AllStack_size = 0xFFFFF; // This mask size is used to tell that the mask of this LRG supports stack positions
  53   enum { SPILL_REG=29999 };     // Register number of a spilled LRG
  54 
  55   double _cost;                 // 2 for loads/1 for stores times block freq
  56   double _area;                 // Sum of all simultaneously live values
  57   double score() const;         // Compute score from cost and area
  58   double _maxfreq;              // Maximum frequency of any def or use
  59 
  60   Node *_def;                   // Check for multi-def live ranges
  61 #ifndef PRODUCT
  62   GrowableArray<Node*>* _defs;
  63 #endif
  64 
  65   uint _risk_bias;              // Index of LRG which we want to avoid color
  66   uint _copy_bias;              // Index of LRG which we want to share color
  67 
  68   uint _next;                   // Index of next LRG in linked list
  69   uint _prev;                   // Index of prev LRG in linked list
  70 private:
  71   uint _reg;                    // Chosen register; undefined if mask is plural
  72 public:
  73   // Return chosen register for this LRG.  Error if the LRG is not bound to
  74   // a single register.
  75   OptoReg::Name reg() const { return OptoReg::Name(_reg); }
  76   void set_reg( OptoReg::Name r ) { _reg = r; }
  77 
  78 private:
  79   uint _eff_degree;             // Effective degree: Sum of neighbors _num_regs
  80 public:
  81   int degree() const { assert( _degree_valid , "" ); return _eff_degree; }
  82   // Degree starts not valid and any change to the IFG neighbor
  83   // set makes it not valid.
  84   void set_degree( uint degree ) {
  85     _eff_degree = degree;
  86     debug_only(_degree_valid = 1;)
  87     assert(!_mask.is_AllStack() || (_mask.is_AllStack() && lo_degree()), "_eff_degree can't be bigger than AllStack_size - _num_regs if the mask supports stack registers");
  88   }
  89   // Made a change that hammered degree
  90   void invalid_degree() { debug_only(_degree_valid=0;) }
  91   // Incrementally modify degree.  If it was correct, it should remain correct
  92   void inc_degree( uint mod ) {
  93     _eff_degree += mod;
  94     assert(!_mask.is_AllStack() || (_mask.is_AllStack() && lo_degree()), "_eff_degree can't be bigger than AllStack_size - _num_regs if the mask supports stack registers");
  95   }
  96   // Compute the degree between 2 live ranges
  97   int compute_degree( LRG &l ) const;
  98   bool mask_is_nonempty_and_up() const {
  99     return mask().is_UP() && mask_size();
 100   }
 101   bool is_float_or_vector() const {
 102     return _is_float || _is_vector;
 103   }
 104 
 105 private:
 106   RegMask _mask;                // Allowed registers for this LRG
 107   uint _mask_size;              // cache of _mask.Size();
 108 public:
 109   int compute_mask_size() const { return _mask.is_AllStack() ? AllStack_size : _mask.Size(); }
 110   void set_mask_size( int size ) {
 111     assert((size == (int)AllStack_size) || (size == (int)_mask.Size()), "");
 112     _mask_size = size;
 113 #ifdef ASSERT
 114     _msize_valid=1;
 115     if (_is_vector) {
 116       assert(!_fat_proj, "sanity");
 117       if (!(_is_scalable && OptoReg::is_stack(_reg))) {
 118         assert(_mask.is_aligned_sets(_num_regs), "mask is not aligned, adjacent sets");
 119       }
 120     } else if (_num_regs == 2 && !_fat_proj) {
 121       assert(_mask.is_aligned_pairs(), "mask is not aligned, adjacent pairs");
 122     }
 123 #endif
 124   }
 125   void compute_set_mask_size() { set_mask_size(compute_mask_size()); }
 126   int mask_size() const { assert( _msize_valid, "mask size not valid" );
 127                           return _mask_size; }
 128   // Get the last mask size computed, even if it does not match the
 129   // count of bits in the current mask.
 130   int get_invalid_mask_size() const { return _mask_size; }
 131   const RegMask &mask() const { return _mask; }
 132   void set_mask( const RegMask &rm ) { _mask = rm; debug_only(_msize_valid=0;)}
 133   void AND( const RegMask &rm ) { _mask.AND(rm); debug_only(_msize_valid=0;)}
 134   void SUBTRACT( const RegMask &rm ) { _mask.SUBTRACT(rm); debug_only(_msize_valid=0;)}
 135   void Clear()   { _mask.Clear()  ; debug_only(_msize_valid=1); _mask_size = 0; }
 136   void Set_All() { _mask.Set_All(); debug_only(_msize_valid=1); _mask_size = RegMask::CHUNK_SIZE; }
 137 
 138   void Insert( OptoReg::Name reg ) { _mask.Insert(reg);  debug_only(_msize_valid=0;) }
 139   void Remove( OptoReg::Name reg ) { _mask.Remove(reg);  debug_only(_msize_valid=0;) }
 140   void clear_to_sets()  { _mask.clear_to_sets(_num_regs); debug_only(_msize_valid=0;) }
 141 
 142 private:
 143   // Number of registers this live range uses when it colors
 144   uint16_t _num_regs;           // 2 for Longs and Doubles, 1 for all else
 145                                 // except _num_regs is kill count for fat_proj
 146 
 147   // For scalable register, num_regs may not be the actual physical register size.
 148   // We need to get the actual physical length of scalable register when scalable
 149   // register is spilled. The size of one slot is 32-bit.
 150   uint _scalable_reg_slots;     // Actual scalable register length of slots.
 151                                 // Meaningful only when _is_scalable is true.
 152 public:
 153   int num_regs() const { return _num_regs; }
 154   void set_num_regs( int reg ) { assert( _num_regs == reg || !_num_regs, "" ); _num_regs = reg; }
 155 
 156   uint scalable_reg_slots() { return _scalable_reg_slots; }
 157   void set_scalable_reg_slots(uint slots) {
 158     assert(_is_scalable, "scalable register");
 159     assert(slots > 0, "slots of scalable register is not valid");
 160     _scalable_reg_slots = slots;
 161   }
 162 
 163   bool is_scalable() {
 164 #ifdef ASSERT
 165     if (_is_scalable) {
 166       // Should only be a vector for now, but it could also be a RegVMask in future.
 167       assert(_is_vector && (_num_regs == RegMask::SlotsPerVecA), "unexpected scalable reg");
 168     }
 169 #endif
 170     return _is_scalable;
 171   }
 172 
 173 private:
 174   // Number of physical registers this live range uses when it colors
 175   // Architecture and register-set dependent
 176   uint16_t _reg_pressure;
 177 public:
 178   void set_reg_pressure(int i)  { _reg_pressure = i; }
 179   int      reg_pressure() const { return _reg_pressure; }
 180 
 181   // How much 'wiggle room' does this live range have?
 182   // How many color choices can it make (scaled by _num_regs)?
 183   int degrees_of_freedom() const { return mask_size() - _num_regs; }
 184   // Bound LRGs have ZERO degrees of freedom.  We also count
 185   // must_spill as bound.
 186   bool is_bound  () const { return _is_bound; }
 187   // Negative degrees-of-freedom; even with no neighbors this
 188   // live range must spill.
 189   bool not_free() const { return degrees_of_freedom() <  0; }
 190   // Is this live range of "low-degree"?  Trivially colorable?
 191   bool lo_degree () const { return degree() <= degrees_of_freedom(); }
 192   // Is this live range just barely "low-degree"?  Trivially colorable?
 193   bool just_lo_degree () const { return degree() == degrees_of_freedom(); }
 194 
 195   uint   _is_oop:1,             // Live-range holds an oop
 196          _is_float:1,           // True if in float registers
 197          _is_vector:1,          // True if in vector registers
 198          _is_scalable:1,        // True if register size is scalable
 199                                 //      e.g. Arm SVE vector/predicate registers.
 200          _was_spilled1:1,       // True if prior spilling on def
 201          _was_spilled2:1,       // True if twice prior spilling on def
 202          _is_bound:1,           // live range starts life with no
 203                                 // degrees of freedom.
 204          _direct_conflict:1,    // True if def and use registers in conflict
 205          _must_spill:1,         // live range has lost all degrees of freedom
 206     // If _fat_proj is set, live range does NOT require aligned, adjacent
 207     // registers and has NO interferences.
 208     // If _fat_proj is clear, live range requires num_regs() to be a power of
 209     // 2, and it requires registers to form an aligned, adjacent set.
 210          _fat_proj:1,           //
 211          _was_lo:1,             // Was lo-degree prior to coalesce
 212          _msize_valid:1,        // _mask_size cache valid
 213          _degree_valid:1,       // _degree cache valid
 214          _has_copy:1,           // Adjacent to some copy instruction
 215          _at_risk:1;            // Simplify says this guy is at risk to spill
 216 
 217 
 218   // Alive if non-zero, dead if zero
 219   bool alive() const { return _def != NULL; }
 220   bool is_multidef() const { return _def == NodeSentinel; }
 221   bool is_singledef() const { return _def != NodeSentinel; }
 222 
 223 #ifndef PRODUCT
 224   void dump( ) const;
 225 #endif
 226 };
 227 
 228 //------------------------------IFG--------------------------------------------
 229 //                         InterFerence Graph
 230 // An undirected graph implementation.  Created with a fixed number of
 231 // vertices.  Edges can be added & tested.  Vertices can be removed, then
 232 // added back later with all edges intact.  Can add edges between one vertex
 233 // and a list of other vertices.  Can union vertices (and their edges)
 234 // together.  The IFG needs to be really really fast, and also fairly
 235 // abstract!  It needs abstraction so I can fiddle with the implementation to
 236 // get even more speed.
 237 class PhaseIFG : public Phase {
 238   friend class VMStructs;
 239   // Current implementation: a triangular adjacency list.
 240 
 241   // Array of adjacency-lists, indexed by live-range number
 242   IndexSet *_adjs;
 243 
 244   // Assertion bit for proper use of Squaring
 245   bool _is_square;
 246 
 247   // Live range structure goes here
 248   LRG *_lrgs;                   // Array of LRG structures
 249 
 250 public:
 251   // Largest live-range number
 252   uint _maxlrg;
 253 
 254   Arena *_arena;
 255 
 256   // Keep track of inserted and deleted Nodes
 257   VectorSet *_yanked;
 258 
 259   PhaseIFG( Arena *arena );
 260   void init( uint maxlrg );
 261 
 262   // Add edge between a and b.  Returns true if actually addded.
 263   int add_edge( uint a, uint b );
 264 
 265   // Test for edge existance
 266   int test_edge( uint a, uint b ) const;
 267 
 268   // Square-up matrix for faster Union
 269   void SquareUp();
 270 
 271   // Return number of LRG neighbors
 272   uint neighbor_cnt( uint a ) const { return _adjs[a].count(); }
 273   // Union edges of b into a on Squared-up matrix
 274   void Union( uint a, uint b );
 275   // Test for edge in Squared-up matrix
 276   int test_edge_sq( uint a, uint b ) const;
 277   // Yank a Node and all connected edges from the IFG.  Be prepared to
 278   // re-insert the yanked Node in reverse order of yanking.  Return a
 279   // list of neighbors (edges) yanked.
 280   IndexSet *remove_node( uint a );
 281   // Reinsert a yanked Node
 282   void re_insert( uint a );
 283   // Return set of neighbors
 284   IndexSet *neighbors( uint a ) const { return &_adjs[a]; }
 285 
 286 #ifndef PRODUCT
 287   // Dump the IFG
 288   void dump() const;
 289   void stats() const;
 290   void verify( const PhaseChaitin * ) const;
 291 #endif
 292 
 293   //--------------- Live Range Accessors
 294   LRG &lrgs(uint idx) const { assert(idx < _maxlrg, "oob"); return _lrgs[idx]; }
 295 
 296   // Compute and set effective degree.  Might be folded into SquareUp().
 297   void Compute_Effective_Degree();
 298 
 299   // Compute effective degree as the sum of neighbors' _sizes.
 300   int effective_degree( uint lidx ) const;
 301 };
 302 
 303 // The LiveRangeMap class is responsible for storing node to live range id mapping.
 304 // Each node is mapped to a live range id (a virtual register). Nodes that are
 305 // not considered for register allocation are given live range id 0.
 306 class LiveRangeMap {
 307 
 308 private:
 309 
 310   uint _max_lrg_id;
 311 
 312   // Union-find map.  Declared as a short for speed.
 313   // Indexed by live-range number, it returns the compacted live-range number
 314   LRG_List _uf_map;
 315 
 316   // Map from Nodes to live ranges
 317   LRG_List _names;
 318 
 319   // Straight out of Tarjan's union-find algorithm
 320   uint find_compress(const Node *node) {
 321     uint lrg_id = find_compress(_names.at(node->_idx));
 322     _names.at_put(node->_idx, lrg_id);
 323     return lrg_id;
 324   }
 325 
 326   uint find_compress(uint lrg);
 327 
 328 public:
 329 
 330   const LRG_List& names() {
 331     return _names;
 332   }
 333 
 334   uint max_lrg_id() const {
 335     return _max_lrg_id;
 336   }
 337 
 338   void set_max_lrg_id(uint max_lrg_id) {
 339     _max_lrg_id = max_lrg_id;
 340   }
 341 
 342   uint size() const {
 343     return _names.length();
 344   }
 345 
 346   uint live_range_id(uint idx) const {
 347     return _names.at(idx);
 348   }
 349 
 350   uint live_range_id(const Node *node) const {
 351     return _names.at(node->_idx);
 352   }
 353 
 354   uint uf_live_range_id(uint lrg_id) const {
 355     return _uf_map.at(lrg_id);
 356   }
 357 
 358   void map(uint idx, uint lrg_id) {
 359     _names.at_put(idx, lrg_id);
 360   }
 361 
 362   void uf_map(uint dst_lrg_id, uint src_lrg_id) {
 363     _uf_map.at_put(dst_lrg_id, src_lrg_id);
 364   }
 365 
 366   void extend(uint idx, uint lrg_id) {
 367     _names.at_put_grow(idx, lrg_id);
 368   }
 369 
 370   void uf_extend(uint dst_lrg_id, uint src_lrg_id) {
 371     _uf_map.at_put_grow(dst_lrg_id, src_lrg_id);
 372   }
 373 
 374   LiveRangeMap(Arena* arena, uint unique)
 375   :  _max_lrg_id(0)
 376   , _uf_map(arena, unique, unique, 0)
 377   , _names(arena, unique, unique, 0) {}
 378 
 379   uint find_id( const Node *n ) {
 380     uint retval = live_range_id(n);
 381     assert(retval == find(n),"Invalid node to lidx mapping");
 382     return retval;
 383   }
 384 
 385   // Reset the Union-Find map to identity
 386   void reset_uf_map(uint max_lrg_id);
 387 
 388   // Make all Nodes map directly to their final live range; no need for
 389   // the Union-Find mapping after this call.
 390   void compress_uf_map_for_nodes();
 391 
 392   uint find(uint lidx) {
 393     uint uf_lidx = _uf_map.at(lidx);
 394     return (uf_lidx == lidx) ? uf_lidx : find_compress(lidx);
 395   }
 396 
 397   // Convert a Node into a Live Range Index - a lidx
 398   uint find(const Node *node) {
 399     uint lidx = live_range_id(node);
 400     uint uf_lidx = _uf_map.at(lidx);
 401     return (uf_lidx == lidx) ? uf_lidx : find_compress(node);
 402   }
 403 
 404   // Like Find above, but no path compress, so bad asymptotic behavior
 405   uint find_const(uint lrg) const;
 406 
 407   // Like Find above, but no path compress, so bad asymptotic behavior
 408   uint find_const(const Node *node) const {
 409     if(node->_idx >= (uint)_names.length()) {
 410       return 0; // not mapped, usual for debug dump
 411     }
 412     return find_const(_names.at(node->_idx));
 413   }
 414 };
 415 
 416 //------------------------------Chaitin----------------------------------------
 417 // Briggs-Chaitin style allocation, mostly.
 418 class PhaseChaitin : public PhaseRegAlloc {
 419   friend class VMStructs;
 420 
 421   int _trip_cnt;
 422   int _alternate;
 423 
 424   PhaseLive *_live;             // Liveness, used in the interference graph
 425   PhaseIFG *_ifg;               // Interference graph (for original chunk)
 426   VectorSet _spilled_once;      // Nodes that have been spilled
 427   VectorSet _spilled_twice;     // Nodes that have been spilled twice
 428 
 429   // Combine the Live Range Indices for these 2 Nodes into a single live
 430   // range.  Future requests for any Node in either live range will
 431   // return the live range index for the combined live range.
 432   void Union( const Node *src, const Node *dst );
 433 
 434   void new_lrg( const Node *x, uint lrg );
 435 
 436   // Compact live ranges, removing unused ones.  Return new maxlrg.
 437   void compact();
 438 
 439   uint _lo_degree;              // Head of lo-degree LRGs list
 440   uint _lo_stk_degree;          // Head of lo-stk-degree LRGs list
 441   uint _hi_degree;              // Head of hi-degree LRGs list
 442   uint _simplified;             // Linked list head of simplified LRGs
 443 
 444   // Helper functions for Split()
 445   uint split_DEF(Node *def, Block *b, int loc, uint max, Node **Reachblock, Node **debug_defs, GrowableArray<uint> splits, int slidx );
 446   uint split_USE(MachSpillCopyNode::SpillType spill_type, Node *def, Block *b, Node *use, uint useidx, uint max, bool def_down, bool cisc_sp, GrowableArray<uint> splits, int slidx );
 447 
 448   //------------------------------clone_projs------------------------------------
 449   // After cloning some rematerialized instruction, clone any MachProj's that
 450   // follow it.  Example: Intel zero is XOR, kills flags.  Sparc FP constants
 451   // use G3 as an address temp.
 452   int clone_projs(Block* b, uint idx, Node* orig, Node* copy, uint& max_lrg_id);
 453 
 454   int clone_projs(Block* b, uint idx, Node* orig, Node* copy, LiveRangeMap& lrg_map) {
 455     uint max_lrg_id = lrg_map.max_lrg_id();
 456     int found_projs = clone_projs(b, idx, orig, copy, max_lrg_id);
 457     if (found_projs > 0) {
 458       // max_lrg_id is updated during call above
 459       lrg_map.set_max_lrg_id(max_lrg_id);
 460     }
 461     return found_projs;
 462   }
 463 
 464   Node *split_Rematerialize(Node *def, Block *b, uint insidx, uint &maxlrg, GrowableArray<uint> splits,
 465                             int slidx, uint *lrg2reach, Node **Reachblock, bool walkThru);
 466   // True if lidx is used before any real register is def'd in the block
 467   bool prompt_use( Block *b, uint lidx );
 468   Node *get_spillcopy_wide(MachSpillCopyNode::SpillType spill_type, Node *def, Node *use, uint uidx );
 469   // Insert the spill at chosen location.  Skip over any intervening Proj's or
 470   // Phis.  Skip over a CatchNode and projs, inserting in the fall-through block
 471   // instead.  Update high-pressure indices.  Create a new live range.
 472   void insert_proj( Block *b, uint i, Node *spill, uint maxlrg );
 473 
 474   bool is_high_pressure( Block *b, LRG *lrg, uint insidx );
 475 
 476   uint _oldphi;                 // Node index which separates pre-allocation nodes
 477 
 478   Block **_blks;                // Array of blocks sorted by frequency for coalescing
 479 
 480   float _high_frequency_lrg;    // Frequency at which LRG will be spilled for debug info
 481 
 482 #ifndef PRODUCT
 483   bool _trace_spilling;
 484 #endif
 485 
 486 public:
 487   PhaseChaitin(uint unique, PhaseCFG &cfg, Matcher &matcher, bool track_liveout_pressure);
 488   ~PhaseChaitin() {}
 489 
 490   LiveRangeMap _lrg_map;
 491 
 492   LRG &lrgs(uint idx) const { return _ifg->lrgs(idx); }
 493 
 494   // Do all the real work of allocate
 495   void Register_Allocate();
 496 
 497   float high_frequency_lrg() const { return _high_frequency_lrg; }
 498 
 499   // Used when scheduling info generated, not in general register allocation
 500   bool _scheduling_info_generated;
 501 
 502   void set_ifg(PhaseIFG &ifg) { _ifg = &ifg;  }
 503   void set_live(PhaseLive &live) { _live = &live; }
 504   PhaseLive* get_live() { return _live; }
 505 
 506   // Populate the live range maps with ssa info for scheduling
 507   void mark_ssa();
 508 
 509 #ifndef PRODUCT
 510   bool trace_spilling() const { return _trace_spilling; }
 511 #endif
 512 
 513 private:
 514   // De-SSA the world.  Assign registers to Nodes.  Use the same register for
 515   // all inputs to a PhiNode, effectively coalescing live ranges.  Insert
 516   // copies as needed.
 517   void de_ssa();
 518 
 519   // Add edge between reg and everything in the vector.
 520   // Use the RegMask information to trim the set of interferences.  Return the
 521   // count of edges added.
 522   void interfere_with_live(uint lid, IndexSet* liveout);
 523 #ifdef ASSERT
 524   // Count register pressure for asserts
 525   uint count_int_pressure(IndexSet* liveout);
 526   uint count_float_pressure(IndexSet* liveout);
 527 #endif
 528 
 529   // Build the interference graph using virtual registers only.
 530   // Used for aggressive coalescing.
 531   void build_ifg_virtual( );
 532 
 533   // used when computing the register pressure for each block in the CFG. This
 534   // is done during IFG creation.
 535   class Pressure {
 536       // keeps track of the register pressure at the current
 537       // instruction (used when stepping backwards in the block)
 538       uint _current_pressure;
 539 
 540       // keeps track of the instruction index of the first low to high register pressure
 541       // transition (starting from the top) in the block
 542       // if high_pressure_index == 0 then the whole block is high pressure
 543       // if high_pressure_index = b.end_idx() + 1 then the whole block is low pressure
 544       uint _high_pressure_index;
 545 
 546       // stores the highest pressure we find
 547       uint _final_pressure;
 548 
 549       // number of live ranges that constitute high register pressure
 550       uint _high_pressure_limit;
 551 
 552       // initial pressure observed
 553       uint _start_pressure;
 554 
 555     public:
 556 
 557       // lower the register pressure and look for a low to high pressure
 558       // transition
 559       void lower(LRG& lrg, uint& location) {
 560         _current_pressure -= lrg.reg_pressure();
 561         if (_current_pressure == _high_pressure_limit) {
 562           _high_pressure_index = location;
 563         }
 564       }
 565 
 566       // raise the pressure and store the pressure if it's the biggest
 567       // pressure so far
 568       void raise(LRG &lrg) {
 569         _current_pressure += lrg.reg_pressure();
 570         if (_current_pressure > _final_pressure) {
 571           _final_pressure = _current_pressure;
 572         }
 573       }
 574 
 575       void init(int limit) {
 576         _current_pressure = 0;
 577         _high_pressure_index = 0;
 578         _final_pressure = 0;
 579         _high_pressure_limit = limit;
 580         _start_pressure = 0;
 581       }
 582 
 583       uint high_pressure_index() const {
 584         return _high_pressure_index;
 585       }
 586 
 587       uint final_pressure() const {
 588         return _final_pressure;
 589       }
 590 
 591       uint start_pressure() const {
 592         return _start_pressure;
 593       }
 594 
 595       uint current_pressure() const {
 596         return _current_pressure;
 597       }
 598 
 599       uint high_pressure_limit() const {
 600         return _high_pressure_limit;
 601       }
 602 
 603       void lower_high_pressure_index() {
 604         _high_pressure_index--;
 605       }
 606 
 607       void set_high_pressure_index_to_block_start() {
 608         _high_pressure_index = 0;
 609       }
 610 
 611       void set_start_pressure(int value) {
 612         _start_pressure = value;
 613         _final_pressure = value;
 614       }
 615 
 616       void set_current_pressure(int value) {
 617         _current_pressure = value;
 618       }
 619 
 620       void check_pressure_at_fatproj(uint fatproj_location, RegMask& fatproj_mask) {
 621         // this pressure is only valid at this instruction, i.e. we don't need to lower
 622         // the register pressure since the fat proj was never live before (going backwards)
 623         uint new_pressure = current_pressure() + fatproj_mask.Size();
 624         if (new_pressure > final_pressure()) {
 625           _final_pressure = new_pressure;
 626         }
 627 
 628         // if we were at a low pressure and now and the fat proj is at high pressure, record the fat proj location
 629         // as coming from a low to high (to low again)
 630         if (current_pressure() <= high_pressure_limit() && new_pressure > high_pressure_limit()) {
 631           _high_pressure_index = fatproj_location;
 632         }
 633       }
 634 
 635       Pressure(uint high_pressure_index, uint high_pressure_limit)
 636         : _current_pressure(0)
 637         , _high_pressure_index(high_pressure_index)
 638         , _final_pressure(0)
 639         , _high_pressure_limit(high_pressure_limit)
 640         , _start_pressure(0) {}
 641   };
 642 
 643   void check_for_high_pressure_transition_at_fatproj(uint& block_reg_pressure, uint location, LRG& lrg, Pressure& pressure, const int op_regtype);
 644   void add_input_to_liveout(Block* b, Node* n, IndexSet* liveout, double cost, Pressure& int_pressure, Pressure& float_pressure);
 645   void compute_initial_block_pressure(Block* b, IndexSet* liveout, Pressure& int_pressure, Pressure& float_pressure, double cost);
 646   bool remove_node_if_not_used(Block* b, uint location, Node* n, uint lid, IndexSet* liveout);
 647   void assign_high_score_to_immediate_copies(Block* b, Node* n, LRG& lrg, uint next_inst, uint last_inst);
 648   void remove_interference_from_copy(Block* b, uint location, uint lid_copy, IndexSet* liveout, double cost, Pressure& int_pressure, Pressure& float_pressure);
 649   void remove_bound_register_from_interfering_live_ranges(LRG& lrg, IndexSet* liveout, uint& must_spill);
 650   void check_for_high_pressure_block(Pressure& pressure);
 651   void adjust_high_pressure_index(Block* b, uint& hrp_index, Pressure& pressure);
 652 
 653   // Build the interference graph using physical registers when available.
 654   // That is, if 2 live ranges are simultaneously alive but in their
 655   // acceptable register sets do not overlap, then they do not interfere.
 656   uint build_ifg_physical( ResourceArea *a );
 657 
 658 public:
 659   // Gather LiveRanGe information, including register masks and base pointer/
 660   // derived pointer relationships.
 661   void gather_lrg_masks( bool mod_cisc_masks );
 662 
 663   // user visible pressure variables for scheduling
 664   Pressure _sched_int_pressure;
 665   Pressure _sched_float_pressure;
 666   Pressure _scratch_int_pressure;
 667   Pressure _scratch_float_pressure;
 668 
 669   // Pressure functions for user context
 670   void lower_pressure(Block* b, uint location, LRG& lrg, IndexSet* liveout, Pressure& int_pressure, Pressure& float_pressure);
 671   void raise_pressure(Block* b, LRG& lrg, Pressure& int_pressure, Pressure& float_pressure);
 672   void compute_entry_block_pressure(Block* b);
 673   void compute_exit_block_pressure(Block* b);
 674   void print_pressure_info(Pressure& pressure, const char *str);
 675 
 676 private:
 677   // Force the bases of derived pointers to be alive at GC points.
 678   bool stretch_base_pointer_live_ranges( ResourceArea *a );
 679   // Helper to stretch above; recursively discover the base Node for
 680   // a given derived Node.  Easy for AddP-related machine nodes, but
 681   // needs to be recursive for derived Phis.
 682   Node *find_base_for_derived( Node **derived_base_map, Node *derived, uint &maxlrg );
 683 
 684   // Set the was-lo-degree bit.  Conservative coalescing should not change the
 685   // colorability of the graph.  If any live range was of low-degree before
 686   // coalescing, it should Simplify.  This call sets the was-lo-degree bit.
 687   void set_was_low();
 688 
 689   // Init LRG caching of degree, numregs.  Init lo_degree list.
 690   void cache_lrg_info( );
 691 
 692   // Simplify the IFG by removing LRGs of low degree
 693   void Simplify();
 694 
 695   // Select colors by re-inserting edges into the IFG.
 696   // Return TRUE if any spills occurred.
 697   uint Select( );
 698   // Helper function for select which allows biased coloring
 699   OptoReg::Name choose_color( LRG &lrg, int chunk );
 700   // Helper function which implements biasing heuristic
 701   OptoReg::Name bias_color( LRG &lrg, int chunk );
 702 
 703   // Split uncolorable live ranges
 704   // Return new number of live ranges
 705   uint Split(uint maxlrg, ResourceArea* split_arena);
 706 
 707   // Set the 'spilled_once' or 'spilled_twice' flag on a node.
 708   void set_was_spilled( Node *n );
 709 
 710   // Convert ideal spill-nodes into machine loads & stores
 711   // Set C->failing when fixup spills could not complete, node limit exceeded.
 712   void fixup_spills();
 713 
 714   // Post-Allocation peephole copy removal
 715   void post_allocate_copy_removal();
 716   Node *skip_copies( Node *c );
 717   // Replace the old node with the current live version of that value
 718   // and yank the old value if it's dead.
 719   int replace_and_yank_if_dead( Node *old, OptoReg::Name nreg,
 720       Block *current_block, Node_List& value, Node_List& regnd ) {
 721     Node* v = regnd[nreg];
 722     assert(v->outcnt() != 0, "no dead values");
 723     old->replace_by(v);
 724     return yank_if_dead(old, current_block, &value, &regnd);
 725   }
 726 
 727   int yank_if_dead( Node *old, Block *current_block, Node_List *value, Node_List *regnd ) {
 728     return yank_if_dead_recurse(old, old, current_block, value, regnd);
 729   }
 730   int yank_if_dead_recurse(Node *old, Node *orig_old, Block *current_block,
 731       Node_List *value, Node_List *regnd);
 732   int yank( Node *old, Block *current_block, Node_List *value, Node_List *regnd );
 733   int elide_copy( Node *n, int k, Block *current_block, Node_List &value, Node_List &regnd, bool can_change_regs );
 734   int use_prior_register( Node *copy, uint idx, Node *def, Block *current_block, Node_List &value, Node_List &regnd );
 735   bool may_be_copy_of_callee( Node *def ) const;
 736 
 737   // If nreg already contains the same constant as val then eliminate it
 738   bool eliminate_copy_of_constant(Node* val, Node* n,
 739       Block *current_block, Node_List& value, Node_List &regnd,
 740       OptoReg::Name nreg, OptoReg::Name nreg2);
 741   // Extend the node to LRG mapping
 742   void add_reference( const Node *node, const Node *old_node);
 743 
 744   // Record the first use of a def in the block for a register.
 745   class RegDefUse {
 746     Node* _def;
 747     Node* _first_use;
 748   public:
 749     RegDefUse() : _def(NULL), _first_use(NULL) { }
 750     Node* def() const       { return _def;       }
 751     Node* first_use() const { return _first_use; }
 752 
 753     void update(Node* def, Node* use) {
 754       if (_def != def) {
 755         _def = def;
 756         _first_use = use;
 757       }
 758     }
 759     void clear() {
 760       _def = NULL;
 761       _first_use = NULL;
 762     }
 763   };
 764   typedef GrowableArray<RegDefUse> RegToDefUseMap;
 765   int possibly_merge_multidef(Node *n, uint k, Block *block, RegToDefUseMap& reg2defuse);
 766 
 767   // Merge nodes that are a part of a multidef lrg and produce the same value within a block.
 768   void merge_multidefs();
 769 
 770 private:
 771 
 772   static int _final_loads, _final_stores, _final_copies, _final_memoves;
 773   static double _final_load_cost, _final_store_cost, _final_copy_cost, _final_memove_cost;
 774   static int _conserv_coalesce, _conserv_coalesce_pair;
 775   static int _conserv_coalesce_trie, _conserv_coalesce_quad;
 776   static int _post_alloc;
 777   static int _lost_opp_pp_coalesce, _lost_opp_cflow_coalesce;
 778   static int _used_cisc_instructions, _unused_cisc_instructions;
 779   static int _allocator_attempts, _allocator_successes;
 780 
 781 #ifdef ASSERT
 782   // Verify that base pointers and derived pointers are still sane
 783   void verify_base_ptrs(ResourceArea* a) const;
 784   void verify(ResourceArea* a, bool verify_ifg = false) const;
 785 #endif // ASSERT
 786 
 787 #ifndef PRODUCT
 788   static uint _high_pressure, _low_pressure;
 789 
 790   void dump() const;
 791   void dump(const Node* n) const;
 792   void dump(const Block* b) const;
 793   void dump_degree_lists() const;
 794   void dump_simplified() const;
 795   void dump_lrg(uint lidx, bool defs_only) const;
 796   void dump_lrg(uint lidx) const {
 797     // dump defs and uses by default
 798     dump_lrg(lidx, false);
 799   }
 800   void dump_bb(uint pre_order) const;
 801   void dump_for_spill_split_recycle() const;
 802 
 803 public:
 804   void dump_frame() const;
 805   char *dump_register(const Node* n, char* buf) const;
 806 private:
 807   static void print_chaitin_statistics();
 808 #endif // not PRODUCT
 809   friend class PhaseCoalesce;
 810   friend class PhaseAggressiveCoalesce;
 811   friend class PhaseConservativeCoalesce;
 812 };
 813 
 814 #endif // SHARE_OPTO_CHAITIN_HPP