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