Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-aarch32-jdk8u
Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/opto/gcm.cpp
83404 views
1
/*
2
* Copyright (c) 1997, 2018, 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 "libadt/vectset.hpp"
27
#include "memory/allocation.inline.hpp"
28
#include "opto/block.hpp"
29
#include "opto/c2compiler.hpp"
30
#include "opto/callnode.hpp"
31
#include "opto/cfgnode.hpp"
32
#include "opto/machnode.hpp"
33
#include "opto/opcodes.hpp"
34
#include "opto/phaseX.hpp"
35
#include "opto/rootnode.hpp"
36
#include "opto/runtime.hpp"
37
#include "runtime/deoptimization.hpp"
38
#if defined AD_MD_HPP
39
# include AD_MD_HPP
40
#elif defined TARGET_ARCH_MODEL_x86_32
41
# include "adfiles/ad_x86_32.hpp"
42
#elif defined TARGET_ARCH_MODEL_x86_64
43
# include "adfiles/ad_x86_64.hpp"
44
#elif defined TARGET_ARCH_MODEL_aarch64
45
# include "adfiles/ad_aarch64.hpp"
46
#elif defined TARGET_ARCH_MODEL_sparc
47
# include "adfiles/ad_sparc.hpp"
48
#elif defined TARGET_ARCH_MODEL_zero
49
# include "adfiles/ad_zero.hpp"
50
#elif defined TARGET_ARCH_MODEL_ppc_64
51
# include "adfiles/ad_ppc_64.hpp"
52
#elif defined TARGET_ARCH_MODEL_aarch32
53
# include "adfiles/ad_aarch32.hpp"
54
#endif
55
56
57
// Portions of code courtesy of Clifford Click
58
59
// Optimization - Graph Style
60
61
// To avoid float value underflow
62
#define MIN_BLOCK_FREQUENCY 1.e-35f
63
64
//----------------------------schedule_node_into_block-------------------------
65
// Insert node n into block b. Look for projections of n and make sure they
66
// are in b also.
67
void PhaseCFG::schedule_node_into_block( Node *n, Block *b ) {
68
// Set basic block of n, Add n to b,
69
map_node_to_block(n, b);
70
b->add_inst(n);
71
72
// After Matching, nearly any old Node may have projections trailing it.
73
// These are usually machine-dependent flags. In any case, they might
74
// float to another block below this one. Move them up.
75
for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
76
Node* use = n->fast_out(i);
77
if (use->is_Proj()) {
78
Block* buse = get_block_for_node(use);
79
if (buse != b) { // In wrong block?
80
if (buse != NULL) {
81
buse->find_remove(use); // Remove from wrong block
82
}
83
map_node_to_block(use, b);
84
b->add_inst(use);
85
}
86
}
87
}
88
}
89
90
//----------------------------replace_block_proj_ctrl-------------------------
91
// Nodes that have is_block_proj() nodes as their control need to use
92
// the appropriate Region for their actual block as their control since
93
// the projection will be in a predecessor block.
94
void PhaseCFG::replace_block_proj_ctrl( Node *n ) {
95
const Node *in0 = n->in(0);
96
assert(in0 != NULL, "Only control-dependent");
97
const Node *p = in0->is_block_proj();
98
if (p != NULL && p != n) { // Control from a block projection?
99
assert(!n->pinned() || n->is_MachConstantBase(), "only pinned MachConstantBase node is expected here");
100
// Find trailing Region
101
Block *pb = get_block_for_node(in0); // Block-projection already has basic block
102
uint j = 0;
103
if (pb->_num_succs != 1) { // More then 1 successor?
104
// Search for successor
105
uint max = pb->number_of_nodes();
106
assert( max > 1, "" );
107
uint start = max - pb->_num_succs;
108
// Find which output path belongs to projection
109
for (j = start; j < max; j++) {
110
if( pb->get_node(j) == in0 )
111
break;
112
}
113
assert( j < max, "must find" );
114
// Change control to match head of successor basic block
115
j -= start;
116
}
117
n->set_req(0, pb->_succs[j]->head());
118
}
119
}
120
121
122
//------------------------------schedule_pinned_nodes--------------------------
123
// Set the basic block for Nodes pinned into blocks
124
void PhaseCFG::schedule_pinned_nodes(VectorSet &visited) {
125
// Allocate node stack of size C->live_nodes()+8 to avoid frequent realloc
126
GrowableArray <Node *> spstack(C->live_nodes() + 8);
127
spstack.push(_root);
128
while (spstack.is_nonempty()) {
129
Node* node = spstack.pop();
130
if (!visited.test_set(node->_idx)) { // Test node and flag it as visited
131
if (node->pinned() && !has_block(node)) { // Pinned? Nail it down!
132
assert(node->in(0), "pinned Node must have Control");
133
// Before setting block replace block_proj control edge
134
replace_block_proj_ctrl(node);
135
Node* input = node->in(0);
136
while (!input->is_block_start()) {
137
input = input->in(0);
138
}
139
Block* block = get_block_for_node(input); // Basic block of controlling input
140
schedule_node_into_block(node, block);
141
}
142
143
// process all inputs that are non NULL
144
for (int i = node->req() - 1; i >= 0; --i) {
145
if (node->in(i) != NULL) {
146
spstack.push(node->in(i));
147
}
148
}
149
}
150
}
151
}
152
153
#ifdef ASSERT
154
// Assert that new input b2 is dominated by all previous inputs.
155
// Check this by by seeing that it is dominated by b1, the deepest
156
// input observed until b2.
157
static void assert_dom(Block* b1, Block* b2, Node* n, const PhaseCFG* cfg) {
158
if (b1 == NULL) return;
159
assert(b1->_dom_depth < b2->_dom_depth, "sanity");
160
Block* tmp = b2;
161
while (tmp != b1 && tmp != NULL) {
162
tmp = tmp->_idom;
163
}
164
if (tmp != b1) {
165
// Detected an unschedulable graph. Print some nice stuff and die.
166
tty->print_cr("!!! Unschedulable graph !!!");
167
for (uint j=0; j<n->len(); j++) { // For all inputs
168
Node* inn = n->in(j); // Get input
169
if (inn == NULL) continue; // Ignore NULL, missing inputs
170
Block* inb = cfg->get_block_for_node(inn);
171
tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order,
172
inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth);
173
inn->dump();
174
}
175
tty->print("Failing node: ");
176
n->dump();
177
assert(false, "unscheduable graph");
178
}
179
}
180
#endif
181
182
static Block* find_deepest_input(Node* n, const PhaseCFG* cfg) {
183
// Find the last input dominated by all other inputs.
184
Block* deepb = NULL; // Deepest block so far
185
int deepb_dom_depth = 0;
186
for (uint k = 0; k < n->len(); k++) { // For all inputs
187
Node* inn = n->in(k); // Get input
188
if (inn == NULL) continue; // Ignore NULL, missing inputs
189
Block* inb = cfg->get_block_for_node(inn);
190
assert(inb != NULL, "must already have scheduled this input");
191
if (deepb_dom_depth < (int) inb->_dom_depth) {
192
// The new inb must be dominated by the previous deepb.
193
// The various inputs must be linearly ordered in the dom
194
// tree, or else there will not be a unique deepest block.
195
DEBUG_ONLY(assert_dom(deepb, inb, n, cfg));
196
deepb = inb; // Save deepest block
197
deepb_dom_depth = deepb->_dom_depth;
198
}
199
}
200
assert(deepb != NULL, "must be at least one input to n");
201
return deepb;
202
}
203
204
205
//------------------------------schedule_early---------------------------------
206
// Find the earliest Block any instruction can be placed in. Some instructions
207
// are pinned into Blocks. Unpinned instructions can appear in last block in
208
// which all their inputs occur.
209
bool PhaseCFG::schedule_early(VectorSet &visited, Node_List &roots) {
210
// Allocate stack with enough space to avoid frequent realloc
211
Node_Stack nstack(roots.Size() + 8);
212
// _root will be processed among C->top() inputs
213
roots.push(C->top());
214
visited.set(C->top()->_idx);
215
216
while (roots.size() != 0) {
217
// Use local variables nstack_top_n & nstack_top_i to cache values
218
// on stack's top.
219
Node* parent_node = roots.pop();
220
uint input_index = 0;
221
222
while (true) {
223
if (input_index == 0) {
224
// Fixup some control. Constants without control get attached
225
// to root and nodes that use is_block_proj() nodes should be attached
226
// to the region that starts their block.
227
const Node* control_input = parent_node->in(0);
228
if (control_input != NULL) {
229
replace_block_proj_ctrl(parent_node);
230
} else {
231
// Is a constant with NO inputs?
232
if (parent_node->req() == 1) {
233
parent_node->set_req(0, _root);
234
}
235
}
236
}
237
238
// First, visit all inputs and force them to get a block. If an
239
// input is already in a block we quit following inputs (to avoid
240
// cycles). Instead we put that Node on a worklist to be handled
241
// later (since IT'S inputs may not have a block yet).
242
243
// Assume all n's inputs will be processed
244
bool done = true;
245
246
while (input_index < parent_node->len()) {
247
Node* in = parent_node->in(input_index++);
248
if (in == NULL) {
249
continue;
250
}
251
252
int is_visited = visited.test_set(in->_idx);
253
if (!has_block(in)) {
254
if (is_visited) {
255
assert(false, "graph should be schedulable");
256
return false;
257
}
258
// Save parent node and next input's index.
259
nstack.push(parent_node, input_index);
260
// Process current input now.
261
parent_node = in;
262
input_index = 0;
263
// Not all n's inputs processed.
264
done = false;
265
break;
266
} else if (!is_visited) {
267
// Visit this guy later, using worklist
268
roots.push(in);
269
}
270
}
271
272
if (done) {
273
// All of n's inputs have been processed, complete post-processing.
274
275
// Some instructions are pinned into a block. These include Region,
276
// Phi, Start, Return, and other control-dependent instructions and
277
// any projections which depend on them.
278
if (!parent_node->pinned()) {
279
// Set earliest legal block.
280
Block* earliest_block = find_deepest_input(parent_node, this);
281
map_node_to_block(parent_node, earliest_block);
282
} else {
283
assert(get_block_for_node(parent_node) == get_block_for_node(parent_node->in(0)), "Pinned Node should be at the same block as its control edge");
284
}
285
286
if (nstack.is_empty()) {
287
// Finished all nodes on stack.
288
// Process next node on the worklist 'roots'.
289
break;
290
}
291
// Get saved parent node and next input's index.
292
parent_node = nstack.node();
293
input_index = nstack.index();
294
nstack.pop();
295
}
296
}
297
}
298
return true;
299
}
300
301
//------------------------------dom_lca----------------------------------------
302
// Find least common ancestor in dominator tree
303
// LCA is a current notion of LCA, to be raised above 'this'.
304
// As a convenient boundary condition, return 'this' if LCA is NULL.
305
// Find the LCA of those two nodes.
306
Block* Block::dom_lca(Block* LCA) {
307
if (LCA == NULL || LCA == this) return this;
308
309
Block* anc = this;
310
while (anc->_dom_depth > LCA->_dom_depth)
311
anc = anc->_idom; // Walk up till anc is as high as LCA
312
313
while (LCA->_dom_depth > anc->_dom_depth)
314
LCA = LCA->_idom; // Walk up till LCA is as high as anc
315
316
while (LCA != anc) { // Walk both up till they are the same
317
LCA = LCA->_idom;
318
anc = anc->_idom;
319
}
320
321
return LCA;
322
}
323
324
//--------------------------raise_LCA_above_use--------------------------------
325
// We are placing a definition, and have been given a def->use edge.
326
// The definition must dominate the use, so move the LCA upward in the
327
// dominator tree to dominate the use. If the use is a phi, adjust
328
// the LCA only with the phi input paths which actually use this def.
329
static Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, const PhaseCFG* cfg) {
330
Block* buse = cfg->get_block_for_node(use);
331
if (buse == NULL) return LCA; // Unused killing Projs have no use block
332
if (!use->is_Phi()) return buse->dom_lca(LCA);
333
uint pmax = use->req(); // Number of Phi inputs
334
// Why does not this loop just break after finding the matching input to
335
// the Phi? Well...it's like this. I do not have true def-use/use-def
336
// chains. Means I cannot distinguish, from the def-use direction, which
337
// of many use-defs lead from the same use to the same def. That is, this
338
// Phi might have several uses of the same def. Each use appears in a
339
// different predecessor block. But when I enter here, I cannot distinguish
340
// which use-def edge I should find the predecessor block for. So I find
341
// them all. Means I do a little extra work if a Phi uses the same value
342
// more than once.
343
for (uint j=1; j<pmax; j++) { // For all inputs
344
if (use->in(j) == def) { // Found matching input?
345
Block* pred = cfg->get_block_for_node(buse->pred(j));
346
LCA = pred->dom_lca(LCA);
347
}
348
}
349
return LCA;
350
}
351
352
//----------------------------raise_LCA_above_marks----------------------------
353
// Return a new LCA that dominates LCA and any of its marked predecessors.
354
// Search all my parents up to 'early' (exclusive), looking for predecessors
355
// which are marked with the given index. Return the LCA (in the dom tree)
356
// of all marked blocks. If there are none marked, return the original
357
// LCA.
358
static Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark, Block* early, const PhaseCFG* cfg) {
359
Block_List worklist;
360
worklist.push(LCA);
361
while (worklist.size() > 0) {
362
Block* mid = worklist.pop();
363
if (mid == early) continue; // stop searching here
364
365
// Test and set the visited bit.
366
if (mid->raise_LCA_visited() == mark) continue; // already visited
367
368
// Don't process the current LCA, otherwise the search may terminate early
369
if (mid != LCA && mid->raise_LCA_mark() == mark) {
370
// Raise the LCA.
371
LCA = mid->dom_lca(LCA);
372
if (LCA == early) break; // stop searching everywhere
373
assert(early->dominates(LCA), "early is high enough");
374
// Resume searching at that point, skipping intermediate levels.
375
worklist.push(LCA);
376
if (LCA == mid)
377
continue; // Don't mark as visited to avoid early termination.
378
} else {
379
// Keep searching through this block's predecessors.
380
for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) {
381
Block* mid_parent = cfg->get_block_for_node(mid->pred(j));
382
worklist.push(mid_parent);
383
}
384
}
385
mid->set_raise_LCA_visited(mark);
386
}
387
return LCA;
388
}
389
390
//--------------------------memory_early_block--------------------------------
391
// This is a variation of find_deepest_input, the heart of schedule_early.
392
// Find the "early" block for a load, if we considered only memory and
393
// address inputs, that is, if other data inputs were ignored.
394
//
395
// Because a subset of edges are considered, the resulting block will
396
// be earlier (at a shallower dom_depth) than the true schedule_early
397
// point of the node. We compute this earlier block as a more permissive
398
// site for anti-dependency insertion, but only if subsume_loads is enabled.
399
static Block* memory_early_block(Node* load, Block* early, const PhaseCFG* cfg) {
400
Node* base;
401
Node* index;
402
Node* store = load->in(MemNode::Memory);
403
load->as_Mach()->memory_inputs(base, index);
404
405
assert(base != NodeSentinel && index != NodeSentinel,
406
"unexpected base/index inputs");
407
408
Node* mem_inputs[4];
409
int mem_inputs_length = 0;
410
if (base != NULL) mem_inputs[mem_inputs_length++] = base;
411
if (index != NULL) mem_inputs[mem_inputs_length++] = index;
412
if (store != NULL) mem_inputs[mem_inputs_length++] = store;
413
414
// In the comparision below, add one to account for the control input,
415
// which may be null, but always takes up a spot in the in array.
416
if (mem_inputs_length + 1 < (int) load->req()) {
417
// This "load" has more inputs than just the memory, base and index inputs.
418
// For purposes of checking anti-dependences, we need to start
419
// from the early block of only the address portion of the instruction,
420
// and ignore other blocks that may have factored into the wider
421
// schedule_early calculation.
422
if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0);
423
424
Block* deepb = NULL; // Deepest block so far
425
int deepb_dom_depth = 0;
426
for (int i = 0; i < mem_inputs_length; i++) {
427
Block* inb = cfg->get_block_for_node(mem_inputs[i]);
428
if (deepb_dom_depth < (int) inb->_dom_depth) {
429
// The new inb must be dominated by the previous deepb.
430
// The various inputs must be linearly ordered in the dom
431
// tree, or else there will not be a unique deepest block.
432
DEBUG_ONLY(assert_dom(deepb, inb, load, cfg));
433
deepb = inb; // Save deepest block
434
deepb_dom_depth = deepb->_dom_depth;
435
}
436
}
437
early = deepb;
438
}
439
440
return early;
441
}
442
443
//--------------------------insert_anti_dependences---------------------------
444
// A load may need to witness memory that nearby stores can overwrite.
445
// For each nearby store, either insert an "anti-dependence" edge
446
// from the load to the store, or else move LCA upward to force the
447
// load to (eventually) be scheduled in a block above the store.
448
//
449
// Do not add edges to stores on distinct control-flow paths;
450
// only add edges to stores which might interfere.
451
//
452
// Return the (updated) LCA. There will not be any possibly interfering
453
// store between the load's "early block" and the updated LCA.
454
// Any stores in the updated LCA will have new precedence edges
455
// back to the load. The caller is expected to schedule the load
456
// in the LCA, in which case the precedence edges will make LCM
457
// preserve anti-dependences. The caller may also hoist the load
458
// above the LCA, if it is not the early block.
459
Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) {
460
assert(load->needs_anti_dependence_check(), "must be a load of some sort");
461
assert(LCA != NULL, "");
462
DEBUG_ONLY(Block* LCA_orig = LCA);
463
464
// Compute the alias index. Loads and stores with different alias indices
465
// do not need anti-dependence edges.
466
uint load_alias_idx = C->get_alias_index(load->adr_type());
467
#ifdef ASSERT
468
if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 &&
469
(PrintOpto || VerifyAliases ||
470
PrintMiscellaneous && (WizardMode || Verbose))) {
471
// Load nodes should not consume all of memory.
472
// Reporting a bottom type indicates a bug in adlc.
473
// If some particular type of node validly consumes all of memory,
474
// sharpen the preceding "if" to exclude it, so we can catch bugs here.
475
tty->print_cr("*** Possible Anti-Dependence Bug: Load consumes all of memory.");
476
load->dump(2);
477
if (VerifyAliases) assert(load_alias_idx != Compile::AliasIdxBot, "");
478
}
479
#endif
480
assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrComp),
481
"String compare is only known 'load' that does not conflict with any stores");
482
assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrEquals),
483
"String equals is a 'load' that does not conflict with any stores");
484
assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrIndexOf),
485
"String indexOf is a 'load' that does not conflict with any stores");
486
assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_AryEq),
487
"Arrays equals is a 'load' that do not conflict with any stores");
488
489
if (!C->alias_type(load_alias_idx)->is_rewritable()) {
490
// It is impossible to spoil this load by putting stores before it,
491
// because we know that the stores will never update the value
492
// which 'load' must witness.
493
return LCA;
494
}
495
496
node_idx_t load_index = load->_idx;
497
498
// Note the earliest legal placement of 'load', as determined by
499
// by the unique point in the dom tree where all memory effects
500
// and other inputs are first available. (Computed by schedule_early.)
501
// For normal loads, 'early' is the shallowest place (dom graph wise)
502
// to look for anti-deps between this load and any store.
503
Block* early = get_block_for_node(load);
504
505
// If we are subsuming loads, compute an "early" block that only considers
506
// memory or address inputs. This block may be different than the
507
// schedule_early block in that it could be at an even shallower depth in the
508
// dominator tree, and allow for a broader discovery of anti-dependences.
509
if (C->subsume_loads()) {
510
early = memory_early_block(load, early, this);
511
}
512
513
ResourceArea *area = Thread::current()->resource_area();
514
Node_List worklist_mem(area); // prior memory state to store
515
Node_List worklist_store(area); // possible-def to explore
516
Node_List worklist_visited(area); // visited mergemem nodes
517
Node_List non_early_stores(area); // all relevant stores outside of early
518
bool must_raise_LCA = false;
519
520
#ifdef TRACK_PHI_INPUTS
521
// %%% This extra checking fails because MergeMem nodes are not GVNed.
522
// Provide "phi_inputs" to check if every input to a PhiNode is from the
523
// original memory state. This indicates a PhiNode for which should not
524
// prevent the load from sinking. For such a block, set_raise_LCA_mark
525
// may be overly conservative.
526
// Mechanism: count inputs seen for each Phi encountered in worklist_store.
527
DEBUG_ONLY(GrowableArray<uint> phi_inputs(area, C->unique(),0,0));
528
#endif
529
530
// 'load' uses some memory state; look for users of the same state.
531
// Recurse through MergeMem nodes to the stores that use them.
532
533
// Each of these stores is a possible definition of memory
534
// that 'load' needs to use. We need to force 'load'
535
// to occur before each such store. When the store is in
536
// the same block as 'load', we insert an anti-dependence
537
// edge load->store.
538
539
// The relevant stores "nearby" the load consist of a tree rooted
540
// at initial_mem, with internal nodes of type MergeMem.
541
// Therefore, the branches visited by the worklist are of this form:
542
// initial_mem -> (MergeMem ->)* store
543
// The anti-dependence constraints apply only to the fringe of this tree.
544
545
Node* initial_mem = load->in(MemNode::Memory);
546
worklist_store.push(initial_mem);
547
worklist_visited.push(initial_mem);
548
worklist_mem.push(NULL);
549
while (worklist_store.size() > 0) {
550
// Examine a nearby store to see if it might interfere with our load.
551
Node* mem = worklist_mem.pop();
552
Node* store = worklist_store.pop();
553
uint op = store->Opcode();
554
555
// MergeMems do not directly have anti-deps.
556
// Treat them as internal nodes in a forward tree of memory states,
557
// the leaves of which are each a 'possible-def'.
558
if (store == initial_mem // root (exclusive) of tree we are searching
559
|| op == Op_MergeMem // internal node of tree we are searching
560
) {
561
mem = store; // It's not a possibly interfering store.
562
if (store == initial_mem)
563
initial_mem = NULL; // only process initial memory once
564
565
for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
566
store = mem->fast_out(i);
567
if (store->is_MergeMem()) {
568
// Be sure we don't get into combinatorial problems.
569
// (Allow phis to be repeated; they can merge two relevant states.)
570
uint j = worklist_visited.size();
571
for (; j > 0; j--) {
572
if (worklist_visited.at(j-1) == store) break;
573
}
574
if (j > 0) continue; // already on work list; do not repeat
575
worklist_visited.push(store);
576
}
577
worklist_mem.push(mem);
578
worklist_store.push(store);
579
}
580
continue;
581
}
582
583
if (op == Op_MachProj || op == Op_Catch) continue;
584
if (store->needs_anti_dependence_check()) continue; // not really a store
585
586
// Compute the alias index. Loads and stores with different alias
587
// indices do not need anti-dependence edges. Wide MemBar's are
588
// anti-dependent on everything (except immutable memories).
589
const TypePtr* adr_type = store->adr_type();
590
if (!C->can_alias(adr_type, load_alias_idx)) continue;
591
592
// Most slow-path runtime calls do NOT modify Java memory, but
593
// they can block and so write Raw memory.
594
if (store->is_Mach()) {
595
MachNode* mstore = store->as_Mach();
596
if (load_alias_idx != Compile::AliasIdxRaw) {
597
// Check for call into the runtime using the Java calling
598
// convention (and from there into a wrapper); it has no
599
// _method. Can't do this optimization for Native calls because
600
// they CAN write to Java memory.
601
if (mstore->ideal_Opcode() == Op_CallStaticJava) {
602
assert(mstore->is_MachSafePoint(), "");
603
MachSafePointNode* ms = (MachSafePointNode*) mstore;
604
assert(ms->is_MachCallJava(), "");
605
MachCallJavaNode* mcj = (MachCallJavaNode*) ms;
606
if (mcj->_method == NULL) {
607
// These runtime calls do not write to Java visible memory
608
// (other than Raw) and so do not require anti-dependence edges.
609
continue;
610
}
611
}
612
// Same for SafePoints: they read/write Raw but only read otherwise.
613
// This is basically a workaround for SafePoints only defining control
614
// instead of control + memory.
615
if (mstore->ideal_Opcode() == Op_SafePoint)
616
continue;
617
} else {
618
// Some raw memory, such as the load of "top" at an allocation,
619
// can be control dependent on the previous safepoint. See
620
// comments in GraphKit::allocate_heap() about control input.
621
// Inserting an anti-dep between such a safepoint and a use
622
// creates a cycle, and will cause a subsequent failure in
623
// local scheduling. (BugId 4919904)
624
// (%%% How can a control input be a safepoint and not a projection??)
625
if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore)
626
continue;
627
}
628
}
629
630
// Identify a block that the current load must be above,
631
// or else observe that 'store' is all the way up in the
632
// earliest legal block for 'load'. In the latter case,
633
// immediately insert an anti-dependence edge.
634
Block* store_block = get_block_for_node(store);
635
assert(store_block != NULL, "unused killing projections skipped above");
636
637
if (store->is_Phi()) {
638
// 'load' uses memory which is one (or more) of the Phi's inputs.
639
// It must be scheduled not before the Phi, but rather before
640
// each of the relevant Phi inputs.
641
//
642
// Instead of finding the LCA of all inputs to a Phi that match 'mem',
643
// we mark each corresponding predecessor block and do a combined
644
// hoisting operation later (raise_LCA_above_marks).
645
//
646
// Do not assert(store_block != early, "Phi merging memory after access")
647
// PhiNode may be at start of block 'early' with backedge to 'early'
648
DEBUG_ONLY(bool found_match = false);
649
for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) {
650
if (store->in(j) == mem) { // Found matching input?
651
DEBUG_ONLY(found_match = true);
652
Block* pred_block = get_block_for_node(store_block->pred(j));
653
if (pred_block != early) {
654
// If any predecessor of the Phi matches the load's "early block",
655
// we do not need a precedence edge between the Phi and 'load'
656
// since the load will be forced into a block preceding the Phi.
657
pred_block->set_raise_LCA_mark(load_index);
658
assert(!LCA_orig->dominates(pred_block) ||
659
early->dominates(pred_block), "early is high enough");
660
must_raise_LCA = true;
661
} else {
662
// anti-dependent upon PHI pinned below 'early', no edge needed
663
LCA = early; // but can not schedule below 'early'
664
}
665
}
666
}
667
assert(found_match, "no worklist bug");
668
#ifdef TRACK_PHI_INPUTS
669
#ifdef ASSERT
670
// This assert asks about correct handling of PhiNodes, which may not
671
// have all input edges directly from 'mem'. See BugId 4621264
672
int num_mem_inputs = phi_inputs.at_grow(store->_idx,0) + 1;
673
// Increment by exactly one even if there are multiple copies of 'mem'
674
// coming into the phi, because we will run this block several times
675
// if there are several copies of 'mem'. (That's how DU iterators work.)
676
phi_inputs.at_put(store->_idx, num_mem_inputs);
677
assert(PhiNode::Input + num_mem_inputs < store->req(),
678
"Expect at least one phi input will not be from original memory state");
679
#endif //ASSERT
680
#endif //TRACK_PHI_INPUTS
681
} else if (store_block != early) {
682
// 'store' is between the current LCA and earliest possible block.
683
// Label its block, and decide later on how to raise the LCA
684
// to include the effect on LCA of this store.
685
// If this store's block gets chosen as the raised LCA, we
686
// will find him on the non_early_stores list and stick him
687
// with a precedence edge.
688
// (But, don't bother if LCA is already raised all the way.)
689
if (LCA != early) {
690
store_block->set_raise_LCA_mark(load_index);
691
must_raise_LCA = true;
692
non_early_stores.push(store);
693
}
694
} else {
695
// Found a possibly-interfering store in the load's 'early' block.
696
// This means 'load' cannot sink at all in the dominator tree.
697
// Add an anti-dep edge, and squeeze 'load' into the highest block.
698
assert(store != load->in(0), "dependence cycle found");
699
if (verify) {
700
assert(store->find_edge(load) != -1, "missing precedence edge");
701
} else {
702
store->add_prec(load);
703
}
704
LCA = early;
705
// This turns off the process of gathering non_early_stores.
706
}
707
}
708
// (Worklist is now empty; all nearby stores have been visited.)
709
710
// Finished if 'load' must be scheduled in its 'early' block.
711
// If we found any stores there, they have already been given
712
// precedence edges.
713
if (LCA == early) return LCA;
714
715
// We get here only if there are no possibly-interfering stores
716
// in the load's 'early' block. Move LCA up above all predecessors
717
// which contain stores we have noted.
718
//
719
// The raised LCA block can be a home to such interfering stores,
720
// but its predecessors must not contain any such stores.
721
//
722
// The raised LCA will be a lower bound for placing the load,
723
// preventing the load from sinking past any block containing
724
// a store that may invalidate the memory state required by 'load'.
725
if (must_raise_LCA)
726
LCA = raise_LCA_above_marks(LCA, load->_idx, early, this);
727
if (LCA == early) return LCA;
728
729
// Insert anti-dependence edges from 'load' to each store
730
// in the non-early LCA block.
731
// Mine the non_early_stores list for such stores.
732
if (LCA->raise_LCA_mark() == load_index) {
733
while (non_early_stores.size() > 0) {
734
Node* store = non_early_stores.pop();
735
Block* store_block = get_block_for_node(store);
736
if (store_block == LCA) {
737
// add anti_dependence from store to load in its own block
738
assert(store != load->in(0), "dependence cycle found");
739
if (verify) {
740
assert(store->find_edge(load) != -1, "missing precedence edge");
741
} else {
742
store->add_prec(load);
743
}
744
} else {
745
assert(store_block->raise_LCA_mark() == load_index, "block was marked");
746
// Any other stores we found must be either inside the new LCA
747
// or else outside the original LCA. In the latter case, they
748
// did not interfere with any use of 'load'.
749
assert(LCA->dominates(store_block)
750
|| !LCA_orig->dominates(store_block), "no stray stores");
751
}
752
}
753
}
754
755
// Return the highest block containing stores; any stores
756
// within that block have been given anti-dependence edges.
757
return LCA;
758
}
759
760
// This class is used to iterate backwards over the nodes in the graph.
761
762
class Node_Backward_Iterator {
763
764
private:
765
Node_Backward_Iterator();
766
767
public:
768
// Constructor for the iterator
769
Node_Backward_Iterator(Node *root, VectorSet &visited, Node_List &stack, PhaseCFG &cfg);
770
771
// Postincrement operator to iterate over the nodes
772
Node *next();
773
774
private:
775
VectorSet &_visited;
776
Node_List &_stack;
777
PhaseCFG &_cfg;
778
};
779
780
// Constructor for the Node_Backward_Iterator
781
Node_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_List &stack, PhaseCFG &cfg)
782
: _visited(visited), _stack(stack), _cfg(cfg) {
783
// The stack should contain exactly the root
784
stack.clear();
785
stack.push(root);
786
787
// Clear the visited bits
788
visited.Clear();
789
}
790
791
// Iterator for the Node_Backward_Iterator
792
Node *Node_Backward_Iterator::next() {
793
794
// If the _stack is empty, then just return NULL: finished.
795
if ( !_stack.size() )
796
return NULL;
797
798
// '_stack' is emulating a real _stack. The 'visit-all-users' loop has been
799
// made stateless, so I do not need to record the index 'i' on my _stack.
800
// Instead I visit all users each time, scanning for unvisited users.
801
// I visit unvisited not-anti-dependence users first, then anti-dependent
802
// children next.
803
Node *self = _stack.pop();
804
805
// I cycle here when I am entering a deeper level of recursion.
806
// The key variable 'self' was set prior to jumping here.
807
while( 1 ) {
808
809
_visited.set(self->_idx);
810
811
// Now schedule all uses as late as possible.
812
const Node* src = self->is_Proj() ? self->in(0) : self;
813
uint src_rpo = _cfg.get_block_for_node(src)->_rpo;
814
815
// Schedule all nodes in a post-order visit
816
Node *unvisited = NULL; // Unvisited anti-dependent Node, if any
817
818
// Scan for unvisited nodes
819
for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
820
// For all uses, schedule late
821
Node* n = self->fast_out(i); // Use
822
823
// Skip already visited children
824
if ( _visited.test(n->_idx) )
825
continue;
826
827
// do not traverse backward control edges
828
Node *use = n->is_Proj() ? n->in(0) : n;
829
uint use_rpo = _cfg.get_block_for_node(use)->_rpo;
830
831
if ( use_rpo < src_rpo )
832
continue;
833
834
// Phi nodes always precede uses in a basic block
835
if ( use_rpo == src_rpo && use->is_Phi() )
836
continue;
837
838
unvisited = n; // Found unvisited
839
840
// Check for possible-anti-dependent
841
if( !n->needs_anti_dependence_check() )
842
break; // Not visited, not anti-dep; schedule it NOW
843
}
844
845
// Did I find an unvisited not-anti-dependent Node?
846
if ( !unvisited )
847
break; // All done with children; post-visit 'self'
848
849
// Visit the unvisited Node. Contains the obvious push to
850
// indicate I'm entering a deeper level of recursion. I push the
851
// old state onto the _stack and set a new state and loop (recurse).
852
_stack.push(self);
853
self = unvisited;
854
} // End recursion loop
855
856
return self;
857
}
858
859
//------------------------------ComputeLatenciesBackwards----------------------
860
// Compute the latency of all the instructions.
861
void PhaseCFG::compute_latencies_backwards(VectorSet &visited, Node_List &stack) {
862
#ifndef PRODUCT
863
if (trace_opto_pipelining())
864
tty->print("\n#---- ComputeLatenciesBackwards ----\n");
865
#endif
866
867
Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
868
Node *n;
869
870
// Walk over all the nodes from last to first
871
while (n = iter.next()) {
872
// Set the latency for the definitions of this instruction
873
partial_latency_of_defs(n);
874
}
875
} // end ComputeLatenciesBackwards
876
877
//------------------------------partial_latency_of_defs------------------------
878
// Compute the latency impact of this node on all defs. This computes
879
// a number that increases as we approach the beginning of the routine.
880
void PhaseCFG::partial_latency_of_defs(Node *n) {
881
// Set the latency for this instruction
882
#ifndef PRODUCT
883
if (trace_opto_pipelining()) {
884
tty->print("# latency_to_inputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
885
dump();
886
}
887
#endif
888
889
if (n->is_Proj()) {
890
n = n->in(0);
891
}
892
893
if (n->is_Root()) {
894
return;
895
}
896
897
uint nlen = n->len();
898
uint use_latency = get_latency_for_node(n);
899
uint use_pre_order = get_block_for_node(n)->_pre_order;
900
901
for (uint j = 0; j < nlen; j++) {
902
Node *def = n->in(j);
903
904
if (!def || def == n) {
905
continue;
906
}
907
908
// Walk backwards thru projections
909
if (def->is_Proj()) {
910
def = def->in(0);
911
}
912
913
#ifndef PRODUCT
914
if (trace_opto_pipelining()) {
915
tty->print("# in(%2d): ", j);
916
def->dump();
917
}
918
#endif
919
920
// If the defining block is not known, assume it is ok
921
Block *def_block = get_block_for_node(def);
922
uint def_pre_order = def_block ? def_block->_pre_order : 0;
923
924
if ((use_pre_order < def_pre_order) || (use_pre_order == def_pre_order && n->is_Phi())) {
925
continue;
926
}
927
928
uint delta_latency = n->latency(j);
929
uint current_latency = delta_latency + use_latency;
930
931
if (get_latency_for_node(def) < current_latency) {
932
set_latency_for_node(def, current_latency);
933
}
934
935
#ifndef PRODUCT
936
if (trace_opto_pipelining()) {
937
tty->print_cr("# %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d", use_latency, j, delta_latency, current_latency, def->_idx, get_latency_for_node(def));
938
}
939
#endif
940
}
941
}
942
943
//------------------------------latency_from_use-------------------------------
944
// Compute the latency of a specific use
945
int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) {
946
// If self-reference, return no latency
947
if (use == n || use->is_Root()) {
948
return 0;
949
}
950
951
uint def_pre_order = get_block_for_node(def)->_pre_order;
952
uint latency = 0;
953
954
// If the use is not a projection, then it is simple...
955
if (!use->is_Proj()) {
956
#ifndef PRODUCT
957
if (trace_opto_pipelining()) {
958
tty->print("# out(): ");
959
use->dump();
960
}
961
#endif
962
963
uint use_pre_order = get_block_for_node(use)->_pre_order;
964
965
if (use_pre_order < def_pre_order)
966
return 0;
967
968
if (use_pre_order == def_pre_order && use->is_Phi())
969
return 0;
970
971
uint nlen = use->len();
972
uint nl = get_latency_for_node(use);
973
974
for ( uint j=0; j<nlen; j++ ) {
975
if (use->in(j) == n) {
976
// Change this if we want local latencies
977
uint ul = use->latency(j);
978
uint l = ul + nl;
979
if (latency < l) latency = l;
980
#ifndef PRODUCT
981
if (trace_opto_pipelining()) {
982
tty->print_cr("# %d + edge_latency(%d) == %d -> %d, latency = %d",
983
nl, j, ul, l, latency);
984
}
985
#endif
986
}
987
}
988
} else {
989
// This is a projection, just grab the latency of the use(s)
990
for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {
991
uint l = latency_from_use(use, def, use->fast_out(j));
992
if (latency < l) latency = l;
993
}
994
}
995
996
return latency;
997
}
998
999
//------------------------------latency_from_uses------------------------------
1000
// Compute the latency of this instruction relative to all of it's uses.
1001
// This computes a number that increases as we approach the beginning of the
1002
// routine.
1003
void PhaseCFG::latency_from_uses(Node *n) {
1004
// Set the latency for this instruction
1005
#ifndef PRODUCT
1006
if (trace_opto_pipelining()) {
1007
tty->print("# latency_from_outputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
1008
dump();
1009
}
1010
#endif
1011
uint latency=0;
1012
const Node *def = n->is_Proj() ? n->in(0): n;
1013
1014
for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1015
uint l = latency_from_use(n, def, n->fast_out(i));
1016
1017
if (latency < l) latency = l;
1018
}
1019
1020
set_latency_for_node(n, latency);
1021
}
1022
1023
//------------------------------hoist_to_cheaper_block-------------------------
1024
// Pick a block for node self, between early and LCA, that is a cheaper
1025
// alternative to LCA.
1026
Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) {
1027
const double delta = 1+PROB_UNLIKELY_MAG(4);
1028
Block* least = LCA;
1029
double least_freq = least->_freq;
1030
uint target = get_latency_for_node(self);
1031
uint start_latency = get_latency_for_node(LCA->head());
1032
uint end_latency = get_latency_for_node(LCA->get_node(LCA->end_idx()));
1033
bool in_latency = (target <= start_latency);
1034
const Block* root_block = get_block_for_node(_root);
1035
1036
// Turn off latency scheduling if scheduling is just plain off
1037
if (!C->do_scheduling())
1038
in_latency = true;
1039
1040
// Do not hoist (to cover latency) instructions which target a
1041
// single register. Hoisting stretches the live range of the
1042
// single register and may force spilling.
1043
MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1044
if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty())
1045
in_latency = true;
1046
1047
#ifndef PRODUCT
1048
if (trace_opto_pipelining()) {
1049
tty->print("# Find cheaper block for latency %d: ", get_latency_for_node(self));
1050
self->dump();
1051
tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1052
LCA->_pre_order,
1053
LCA->head()->_idx,
1054
start_latency,
1055
LCA->get_node(LCA->end_idx())->_idx,
1056
end_latency,
1057
least_freq);
1058
}
1059
#endif
1060
1061
int cand_cnt = 0; // number of candidates tried
1062
1063
// Walk up the dominator tree from LCA (Lowest common ancestor) to
1064
// the earliest legal location. Capture the least execution frequency.
1065
while (LCA != early) {
1066
LCA = LCA->_idom; // Follow up the dominator tree
1067
1068
if (LCA == NULL) {
1069
// Bailout without retry
1070
assert(false, "graph should be schedulable");
1071
C->record_method_not_compilable("late schedule failed: LCA == NULL");
1072
return least;
1073
}
1074
1075
// Don't hoist machine instructions to the root basic block
1076
if (mach && LCA == root_block)
1077
break;
1078
1079
uint start_lat = get_latency_for_node(LCA->head());
1080
uint end_idx = LCA->end_idx();
1081
uint end_lat = get_latency_for_node(LCA->get_node(end_idx));
1082
double LCA_freq = LCA->_freq;
1083
#ifndef PRODUCT
1084
if (trace_opto_pipelining()) {
1085
tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1086
LCA->_pre_order, LCA->head()->_idx, start_lat, end_idx, end_lat, LCA_freq);
1087
}
1088
#endif
1089
cand_cnt++;
1090
if (LCA_freq < least_freq || // Better Frequency
1091
(StressGCM && Compile::randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode
1092
(!StressGCM && // Otherwise, choose with latency
1093
!in_latency && // No block containing latency
1094
LCA_freq < least_freq * delta && // No worse frequency
1095
target >= end_lat && // within latency range
1096
!self->is_iteratively_computed() ) // But don't hoist IV increments
1097
// because they may end up above other uses of their phi forcing
1098
// their result register to be different from their input.
1099
) {
1100
least = LCA; // Found cheaper block
1101
least_freq = LCA_freq;
1102
start_latency = start_lat;
1103
end_latency = end_lat;
1104
if (target <= start_lat)
1105
in_latency = true;
1106
}
1107
}
1108
1109
#ifndef PRODUCT
1110
if (trace_opto_pipelining()) {
1111
tty->print_cr("# Choose block B%d with start latency=%d and freq=%g",
1112
least->_pre_order, start_latency, least_freq);
1113
}
1114
#endif
1115
1116
// See if the latency needs to be updated
1117
if (target < end_latency) {
1118
#ifndef PRODUCT
1119
if (trace_opto_pipelining()) {
1120
tty->print_cr("# Change latency for [%4d] from %d to %d", self->_idx, target, end_latency);
1121
}
1122
#endif
1123
set_latency_for_node(self, end_latency);
1124
partial_latency_of_defs(self);
1125
}
1126
1127
return least;
1128
}
1129
1130
1131
//------------------------------schedule_late-----------------------------------
1132
// Now schedule all codes as LATE as possible. This is the LCA in the
1133
// dominator tree of all USES of a value. Pick the block with the least
1134
// loop nesting depth that is lowest in the dominator tree.
1135
extern const char must_clone[];
1136
void PhaseCFG::schedule_late(VectorSet &visited, Node_List &stack) {
1137
#ifndef PRODUCT
1138
if (trace_opto_pipelining())
1139
tty->print("\n#---- schedule_late ----\n");
1140
#endif
1141
1142
Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
1143
Node *self;
1144
1145
// Walk over all the nodes from last to first
1146
while (self = iter.next()) {
1147
Block* early = get_block_for_node(self); // Earliest legal placement
1148
1149
if (self->is_top()) {
1150
// Top node goes in bb #2 with other constants.
1151
// It must be special-cased, because it has no out edges.
1152
early->add_inst(self);
1153
continue;
1154
}
1155
1156
// No uses, just terminate
1157
if (self->outcnt() == 0) {
1158
assert(self->is_MachProj(), "sanity");
1159
continue; // Must be a dead machine projection
1160
}
1161
1162
// If node is pinned in the block, then no scheduling can be done.
1163
if( self->pinned() ) // Pinned in block?
1164
continue;
1165
1166
MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1167
if (mach) {
1168
switch (mach->ideal_Opcode()) {
1169
case Op_CreateEx:
1170
// Don't move exception creation
1171
early->add_inst(self);
1172
continue;
1173
break;
1174
case Op_CheckCastPP:
1175
// Don't move CheckCastPP nodes away from their input, if the input
1176
// is a rawptr (5071820).
1177
Node *def = self->in(1);
1178
if (def != NULL && def->bottom_type()->base() == Type::RawPtr) {
1179
early->add_inst(self);
1180
#ifdef ASSERT
1181
_raw_oops.push(def);
1182
#endif
1183
continue;
1184
}
1185
break;
1186
}
1187
}
1188
1189
// Gather LCA of all uses
1190
Block *LCA = NULL;
1191
{
1192
for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
1193
// For all uses, find LCA
1194
Node* use = self->fast_out(i);
1195
LCA = raise_LCA_above_use(LCA, use, self, this);
1196
}
1197
} // (Hide defs of imax, i from rest of block.)
1198
1199
// Place temps in the block of their use. This isn't a
1200
// requirement for correctness but it reduces useless
1201
// interference between temps and other nodes.
1202
if (mach != NULL && mach->is_MachTemp()) {
1203
map_node_to_block(self, LCA);
1204
LCA->add_inst(self);
1205
continue;
1206
}
1207
1208
// Check if 'self' could be anti-dependent on memory
1209
if (self->needs_anti_dependence_check()) {
1210
// Hoist LCA above possible-defs and insert anti-dependences to
1211
// defs in new LCA block.
1212
LCA = insert_anti_dependences(LCA, self);
1213
}
1214
1215
if (early->_dom_depth > LCA->_dom_depth) {
1216
// Somehow the LCA has moved above the earliest legal point.
1217
// (One way this can happen is via memory_early_block.)
1218
if (C->subsume_loads() == true && !C->failing()) {
1219
// Retry with subsume_loads == false
1220
// If this is the first failure, the sentinel string will "stick"
1221
// to the Compile object, and the C2Compiler will see it and retry.
1222
C->record_failure(C2Compiler::retry_no_subsuming_loads());
1223
} else {
1224
// Bailout without retry when (early->_dom_depth > LCA->_dom_depth)
1225
assert(false, "graph should be schedulable");
1226
C->record_method_not_compilable("late schedule failed: incorrect graph");
1227
}
1228
return;
1229
}
1230
1231
// If there is no opportunity to hoist, then we're done.
1232
// In stress mode, try to hoist even the single operations.
1233
bool try_to_hoist = StressGCM || (LCA != early);
1234
1235
// Must clone guys stay next to use; no hoisting allowed.
1236
// Also cannot hoist guys that alter memory or are otherwise not
1237
// allocatable (hoisting can make a value live longer, leading to
1238
// anti and output dependency problems which are normally resolved
1239
// by the register allocator giving everyone a different register).
1240
if (mach != NULL && must_clone[mach->ideal_Opcode()])
1241
try_to_hoist = false;
1242
1243
Block* late = NULL;
1244
if (try_to_hoist) {
1245
// Now find the block with the least execution frequency.
1246
// Start at the latest schedule and work up to the earliest schedule
1247
// in the dominator tree. Thus the Node will dominate all its uses.
1248
late = hoist_to_cheaper_block(LCA, early, self);
1249
} else {
1250
// Just use the LCA of the uses.
1251
late = LCA;
1252
}
1253
1254
// Put the node into target block
1255
schedule_node_into_block(self, late);
1256
1257
#ifdef ASSERT
1258
if (self->needs_anti_dependence_check()) {
1259
// since precedence edges are only inserted when we're sure they
1260
// are needed make sure that after placement in a block we don't
1261
// need any new precedence edges.
1262
verify_anti_dependences(late, self);
1263
}
1264
#endif
1265
} // Loop until all nodes have been visited
1266
1267
} // end ScheduleLate
1268
1269
//------------------------------GlobalCodeMotion-------------------------------
1270
void PhaseCFG::global_code_motion() {
1271
ResourceMark rm;
1272
1273
#ifndef PRODUCT
1274
if (trace_opto_pipelining()) {
1275
tty->print("\n---- Start GlobalCodeMotion ----\n");
1276
}
1277
#endif
1278
1279
// Initialize the node to block mapping for things on the proj_list
1280
for (uint i = 0; i < _matcher.number_of_projections(); i++) {
1281
unmap_node_from_block(_matcher.get_projection(i));
1282
}
1283
1284
// Set the basic block for Nodes pinned into blocks
1285
Arena* arena = Thread::current()->resource_area();
1286
VectorSet visited(arena);
1287
schedule_pinned_nodes(visited);
1288
1289
// Find the earliest Block any instruction can be placed in. Some
1290
// instructions are pinned into Blocks. Unpinned instructions can
1291
// appear in last block in which all their inputs occur.
1292
visited.Clear();
1293
Node_List stack(arena);
1294
// Pre-grow the list
1295
stack.map((C->live_nodes() >> 1) + 16, NULL);
1296
if (!schedule_early(visited, stack)) {
1297
// Bailout without retry
1298
C->record_method_not_compilable("early schedule failed");
1299
return;
1300
}
1301
1302
// Build Def-Use edges.
1303
// Compute the latency information (via backwards walk) for all the
1304
// instructions in the graph
1305
_node_latency = new GrowableArray<uint>(); // resource_area allocation
1306
1307
if (C->do_scheduling()) {
1308
compute_latencies_backwards(visited, stack);
1309
}
1310
1311
// Now schedule all codes as LATE as possible. This is the LCA in the
1312
// dominator tree of all USES of a value. Pick the block with the least
1313
// loop nesting depth that is lowest in the dominator tree.
1314
// ( visited.Clear() called in schedule_late()->Node_Backward_Iterator() )
1315
schedule_late(visited, stack);
1316
if (C->failing()) {
1317
return;
1318
}
1319
1320
#ifndef PRODUCT
1321
if (trace_opto_pipelining()) {
1322
tty->print("\n---- Detect implicit null checks ----\n");
1323
}
1324
#endif
1325
1326
// Detect implicit-null-check opportunities. Basically, find NULL checks
1327
// with suitable memory ops nearby. Use the memory op to do the NULL check.
1328
// I can generate a memory op if there is not one nearby.
1329
if (C->is_method_compilation()) {
1330
// By reversing the loop direction we get a very minor gain on mpegaudio.
1331
// Feel free to revert to a forward loop for clarity.
1332
// for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) {
1333
for (int i = _matcher._null_check_tests.size() - 2; i >= 0; i -= 2) {
1334
Node* proj = _matcher._null_check_tests[i];
1335
Node* val = _matcher._null_check_tests[i + 1];
1336
Block* block = get_block_for_node(proj);
1337
implicit_null_check(block, proj, val, C->allowed_deopt_reasons());
1338
// The implicit_null_check will only perform the transformation
1339
// if the null branch is truly uncommon, *and* it leads to an
1340
// uncommon trap. Combined with the too_many_traps guards
1341
// above, this prevents SEGV storms reported in 6366351,
1342
// by recompiling offending methods without this optimization.
1343
}
1344
}
1345
1346
#ifndef PRODUCT
1347
if (trace_opto_pipelining()) {
1348
tty->print("\n---- Start Local Scheduling ----\n");
1349
}
1350
#endif
1351
1352
// Schedule locally. Right now a simple topological sort.
1353
// Later, do a real latency aware scheduler.
1354
GrowableArray<int> ready_cnt(C->unique(), C->unique(), -1);
1355
visited.Clear();
1356
for (uint i = 0; i < number_of_blocks(); i++) {
1357
Block* block = get_block(i);
1358
if (!schedule_local(block, ready_cnt, visited)) {
1359
if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
1360
C->record_method_not_compilable("local schedule failed");
1361
}
1362
return;
1363
}
1364
}
1365
1366
// If we inserted any instructions between a Call and his CatchNode,
1367
// clone the instructions on all paths below the Catch.
1368
for (uint i = 0; i < number_of_blocks(); i++) {
1369
Block* block = get_block(i);
1370
call_catch_cleanup(block);
1371
}
1372
1373
#ifndef PRODUCT
1374
if (trace_opto_pipelining()) {
1375
tty->print("\n---- After GlobalCodeMotion ----\n");
1376
for (uint i = 0; i < number_of_blocks(); i++) {
1377
Block* block = get_block(i);
1378
block->dump();
1379
}
1380
}
1381
#endif
1382
// Dead.
1383
_node_latency = (GrowableArray<uint> *)((intptr_t)0xdeadbeef);
1384
}
1385
1386
bool PhaseCFG::do_global_code_motion() {
1387
1388
build_dominator_tree();
1389
if (C->failing()) {
1390
return false;
1391
}
1392
1393
NOT_PRODUCT( C->verify_graph_edges(); )
1394
1395
estimate_block_frequency();
1396
1397
global_code_motion();
1398
1399
if (C->failing()) {
1400
return false;
1401
}
1402
1403
return true;
1404
}
1405
1406
//------------------------------Estimate_Block_Frequency-----------------------
1407
// Estimate block frequencies based on IfNode probabilities.
1408
void PhaseCFG::estimate_block_frequency() {
1409
1410
// Force conditional branches leading to uncommon traps to be unlikely,
1411
// not because we get to the uncommon_trap with less relative frequency,
1412
// but because an uncommon_trap typically causes a deopt, so we only get
1413
// there once.
1414
if (C->do_freq_based_layout()) {
1415
Block_List worklist;
1416
Block* root_blk = get_block(0);
1417
for (uint i = 1; i < root_blk->num_preds(); i++) {
1418
Block *pb = get_block_for_node(root_blk->pred(i));
1419
if (pb->has_uncommon_code()) {
1420
worklist.push(pb);
1421
}
1422
}
1423
while (worklist.size() > 0) {
1424
Block* uct = worklist.pop();
1425
if (uct == get_root_block()) {
1426
continue;
1427
}
1428
for (uint i = 1; i < uct->num_preds(); i++) {
1429
Block *pb = get_block_for_node(uct->pred(i));
1430
if (pb->_num_succs == 1) {
1431
worklist.push(pb);
1432
} else if (pb->num_fall_throughs() == 2) {
1433
pb->update_uncommon_branch(uct);
1434
}
1435
}
1436
}
1437
}
1438
1439
// Create the loop tree and calculate loop depth.
1440
_root_loop = create_loop_tree();
1441
_root_loop->compute_loop_depth(0);
1442
1443
// Compute block frequency of each block, relative to a single loop entry.
1444
_root_loop->compute_freq();
1445
1446
// Adjust all frequencies to be relative to a single method entry
1447
_root_loop->_freq = 1.0;
1448
_root_loop->scale_freq();
1449
1450
// Save outmost loop frequency for LRG frequency threshold
1451
_outer_loop_frequency = _root_loop->outer_loop_freq();
1452
1453
// force paths ending at uncommon traps to be infrequent
1454
if (!C->do_freq_based_layout()) {
1455
Block_List worklist;
1456
Block* root_blk = get_block(0);
1457
for (uint i = 1; i < root_blk->num_preds(); i++) {
1458
Block *pb = get_block_for_node(root_blk->pred(i));
1459
if (pb->has_uncommon_code()) {
1460
worklist.push(pb);
1461
}
1462
}
1463
while (worklist.size() > 0) {
1464
Block* uct = worklist.pop();
1465
uct->_freq = PROB_MIN;
1466
for (uint i = 1; i < uct->num_preds(); i++) {
1467
Block *pb = get_block_for_node(uct->pred(i));
1468
if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) {
1469
worklist.push(pb);
1470
}
1471
}
1472
}
1473
}
1474
1475
#ifdef ASSERT
1476
for (uint i = 0; i < number_of_blocks(); i++) {
1477
Block* b = get_block(i);
1478
assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");
1479
}
1480
#endif
1481
1482
#ifndef PRODUCT
1483
if (PrintCFGBlockFreq) {
1484
tty->print_cr("CFG Block Frequencies");
1485
_root_loop->dump_tree();
1486
if (Verbose) {
1487
tty->print_cr("PhaseCFG dump");
1488
dump();
1489
tty->print_cr("Node dump");
1490
_root->dump(99999);
1491
}
1492
}
1493
#endif
1494
}
1495
1496
//----------------------------create_loop_tree--------------------------------
1497
// Create a loop tree from the CFG
1498
CFGLoop* PhaseCFG::create_loop_tree() {
1499
1500
#ifdef ASSERT
1501
assert(get_block(0) == get_root_block(), "first block should be root block");
1502
for (uint i = 0; i < number_of_blocks(); i++) {
1503
Block* block = get_block(i);
1504
// Check that _loop field are clear...we could clear them if not.
1505
assert(block->_loop == NULL, "clear _loop expected");
1506
// Sanity check that the RPO numbering is reflected in the _blocks array.
1507
// It doesn't have to be for the loop tree to be built, but if it is not,
1508
// then the blocks have been reordered since dom graph building...which
1509
// may question the RPO numbering
1510
assert(block->_rpo == i, "unexpected reverse post order number");
1511
}
1512
#endif
1513
1514
int idct = 0;
1515
CFGLoop* root_loop = new CFGLoop(idct++);
1516
1517
Block_List worklist;
1518
1519
// Assign blocks to loops
1520
for(uint i = number_of_blocks() - 1; i > 0; i-- ) { // skip Root block
1521
Block* block = get_block(i);
1522
1523
if (block->head()->is_Loop()) {
1524
Block* loop_head = block;
1525
assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1526
Node* tail_n = loop_head->pred(LoopNode::LoopBackControl);
1527
Block* tail = get_block_for_node(tail_n);
1528
1529
// Defensively filter out Loop nodes for non-single-entry loops.
1530
// For all reasonable loops, the head occurs before the tail in RPO.
1531
if (i <= tail->_rpo) {
1532
1533
// The tail and (recursive) predecessors of the tail
1534
// are made members of a new loop.
1535
1536
assert(worklist.size() == 0, "nonempty worklist");
1537
CFGLoop* nloop = new CFGLoop(idct++);
1538
assert(loop_head->_loop == NULL, "just checking");
1539
loop_head->_loop = nloop;
1540
// Add to nloop so push_pred() will skip over inner loops
1541
nloop->add_member(loop_head);
1542
nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, this);
1543
1544
while (worklist.size() > 0) {
1545
Block* member = worklist.pop();
1546
if (member != loop_head) {
1547
for (uint j = 1; j < member->num_preds(); j++) {
1548
nloop->push_pred(member, j, worklist, this);
1549
}
1550
}
1551
}
1552
}
1553
}
1554
}
1555
1556
// Create a member list for each loop consisting
1557
// of both blocks and (immediate child) loops.
1558
for (uint i = 0; i < number_of_blocks(); i++) {
1559
Block* block = get_block(i);
1560
CFGLoop* lp = block->_loop;
1561
if (lp == NULL) {
1562
// Not assigned to a loop. Add it to the method's pseudo loop.
1563
block->_loop = root_loop;
1564
lp = root_loop;
1565
}
1566
if (lp == root_loop || block != lp->head()) { // loop heads are already members
1567
lp->add_member(block);
1568
}
1569
if (lp != root_loop) {
1570
if (lp->parent() == NULL) {
1571
// Not a nested loop. Make it a child of the method's pseudo loop.
1572
root_loop->add_nested_loop(lp);
1573
}
1574
if (block == lp->head()) {
1575
// Add nested loop to member list of parent loop.
1576
lp->parent()->add_member(lp);
1577
}
1578
}
1579
}
1580
1581
return root_loop;
1582
}
1583
1584
//------------------------------push_pred--------------------------------------
1585
void CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg) {
1586
Node* pred_n = blk->pred(i);
1587
Block* pred = cfg->get_block_for_node(pred_n);
1588
CFGLoop *pred_loop = pred->_loop;
1589
if (pred_loop == NULL) {
1590
// Filter out blocks for non-single-entry loops.
1591
// For all reasonable loops, the head occurs before the tail in RPO.
1592
if (pred->_rpo > head()->_rpo) {
1593
pred->_loop = this;
1594
worklist.push(pred);
1595
}
1596
} else if (pred_loop != this) {
1597
// Nested loop.
1598
while (pred_loop->_parent != NULL && pred_loop->_parent != this) {
1599
pred_loop = pred_loop->_parent;
1600
}
1601
// Make pred's loop be a child
1602
if (pred_loop->_parent == NULL) {
1603
add_nested_loop(pred_loop);
1604
// Continue with loop entry predecessor.
1605
Block* pred_head = pred_loop->head();
1606
assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1607
assert(pred_head != head(), "loop head in only one loop");
1608
push_pred(pred_head, LoopNode::EntryControl, worklist, cfg);
1609
} else {
1610
assert(pred_loop->_parent == this && _parent == NULL, "just checking");
1611
}
1612
}
1613
}
1614
1615
//------------------------------add_nested_loop--------------------------------
1616
// Make cl a child of the current loop in the loop tree.
1617
void CFGLoop::add_nested_loop(CFGLoop* cl) {
1618
assert(_parent == NULL, "no parent yet");
1619
assert(cl != this, "not my own parent");
1620
cl->_parent = this;
1621
CFGLoop* ch = _child;
1622
if (ch == NULL) {
1623
_child = cl;
1624
} else {
1625
while (ch->_sibling != NULL) { ch = ch->_sibling; }
1626
ch->_sibling = cl;
1627
}
1628
}
1629
1630
//------------------------------compute_loop_depth-----------------------------
1631
// Store the loop depth in each CFGLoop object.
1632
// Recursively walk the children to do the same for them.
1633
void CFGLoop::compute_loop_depth(int depth) {
1634
_depth = depth;
1635
CFGLoop* ch = _child;
1636
while (ch != NULL) {
1637
ch->compute_loop_depth(depth + 1);
1638
ch = ch->_sibling;
1639
}
1640
}
1641
1642
//------------------------------compute_freq-----------------------------------
1643
// Compute the frequency of each block and loop, relative to a single entry
1644
// into the dominating loop head.
1645
void CFGLoop::compute_freq() {
1646
// Bottom up traversal of loop tree (visit inner loops first.)
1647
// Set loop head frequency to 1.0, then transitively
1648
// compute frequency for all successors in the loop,
1649
// as well as for each exit edge. Inner loops are
1650
// treated as single blocks with loop exit targets
1651
// as the successor blocks.
1652
1653
// Nested loops first
1654
CFGLoop* ch = _child;
1655
while (ch != NULL) {
1656
ch->compute_freq();
1657
ch = ch->_sibling;
1658
}
1659
assert (_members.length() > 0, "no empty loops");
1660
Block* hd = head();
1661
hd->_freq = 1.0f;
1662
for (int i = 0; i < _members.length(); i++) {
1663
CFGElement* s = _members.at(i);
1664
float freq = s->_freq;
1665
if (s->is_block()) {
1666
Block* b = s->as_Block();
1667
for (uint j = 0; j < b->_num_succs; j++) {
1668
Block* sb = b->_succs[j];
1669
update_succ_freq(sb, freq * b->succ_prob(j));
1670
}
1671
} else {
1672
CFGLoop* lp = s->as_CFGLoop();
1673
assert(lp->_parent == this, "immediate child");
1674
for (int k = 0; k < lp->_exits.length(); k++) {
1675
Block* eb = lp->_exits.at(k).get_target();
1676
float prob = lp->_exits.at(k).get_prob();
1677
update_succ_freq(eb, freq * prob);
1678
}
1679
}
1680
}
1681
1682
// For all loops other than the outer, "method" loop,
1683
// sum and normalize the exit probability. The "method" loop
1684
// should keep the initial exit probability of 1, so that
1685
// inner blocks do not get erroneously scaled.
1686
if (_depth != 0) {
1687
// Total the exit probabilities for this loop.
1688
float exits_sum = 0.0f;
1689
for (int i = 0; i < _exits.length(); i++) {
1690
exits_sum += _exits.at(i).get_prob();
1691
}
1692
1693
// Normalize the exit probabilities. Until now, the
1694
// probabilities estimate the possibility of exit per
1695
// a single loop iteration; afterward, they estimate
1696
// the probability of exit per loop entry.
1697
for (int i = 0; i < _exits.length(); i++) {
1698
Block* et = _exits.at(i).get_target();
1699
float new_prob = 0.0f;
1700
if (_exits.at(i).get_prob() > 0.0f) {
1701
new_prob = _exits.at(i).get_prob() / exits_sum;
1702
}
1703
BlockProbPair bpp(et, new_prob);
1704
_exits.at_put(i, bpp);
1705
}
1706
1707
// Save the total, but guard against unreasonable probability,
1708
// as the value is used to estimate the loop trip count.
1709
// An infinite trip count would blur relative block
1710
// frequencies.
1711
if (exits_sum > 1.0f) exits_sum = 1.0;
1712
if (exits_sum < PROB_MIN) exits_sum = PROB_MIN;
1713
_exit_prob = exits_sum;
1714
}
1715
}
1716
1717
//------------------------------succ_prob-------------------------------------
1718
// Determine the probability of reaching successor 'i' from the receiver block.
1719
float Block::succ_prob(uint i) {
1720
int eidx = end_idx();
1721
Node *n = get_node(eidx); // Get ending Node
1722
1723
int op = n->Opcode();
1724
if (n->is_Mach()) {
1725
if (n->is_MachNullCheck()) {
1726
// Can only reach here if called after lcm. The original Op_If is gone,
1727
// so we attempt to infer the probability from one or both of the
1728
// successor blocks.
1729
assert(_num_succs == 2, "expecting 2 successors of a null check");
1730
// If either successor has only one predecessor, then the
1731
// probability estimate can be derived using the
1732
// relative frequency of the successor and this block.
1733
if (_succs[i]->num_preds() == 2) {
1734
return _succs[i]->_freq / _freq;
1735
} else if (_succs[1-i]->num_preds() == 2) {
1736
return 1 - (_succs[1-i]->_freq / _freq);
1737
} else {
1738
// Estimate using both successor frequencies
1739
float freq = _succs[i]->_freq;
1740
return freq / (freq + _succs[1-i]->_freq);
1741
}
1742
}
1743
op = n->as_Mach()->ideal_Opcode();
1744
}
1745
1746
1747
// Switch on branch type
1748
switch( op ) {
1749
case Op_CountedLoopEnd:
1750
case Op_If: {
1751
assert (i < 2, "just checking");
1752
// Conditionals pass on only part of their frequency
1753
float prob = n->as_MachIf()->_prob;
1754
assert(prob >= 0.0 && prob <= 1.0, "out of range probability");
1755
// If succ[i] is the FALSE branch, invert path info
1756
if( get_node(i + eidx + 1)->Opcode() == Op_IfFalse ) {
1757
return 1.0f - prob; // not taken
1758
} else {
1759
return prob; // taken
1760
}
1761
}
1762
1763
case Op_Jump:
1764
// Divide the frequency between all successors evenly
1765
return 1.0f/_num_succs;
1766
1767
case Op_Catch: {
1768
const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1769
if (ci->_con == CatchProjNode::fall_through_index) {
1770
// Fall-thru path gets the lion's share.
1771
return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs;
1772
} else {
1773
// Presume exceptional paths are equally unlikely
1774
return PROB_UNLIKELY_MAG(5);
1775
}
1776
}
1777
1778
case Op_Root:
1779
case Op_Goto:
1780
// Pass frequency straight thru to target
1781
return 1.0f;
1782
1783
case Op_NeverBranch:
1784
return 0.0f;
1785
1786
case Op_TailCall:
1787
case Op_TailJump:
1788
case Op_Return:
1789
case Op_Halt:
1790
case Op_Rethrow:
1791
// Do not push out freq to root block
1792
return 0.0f;
1793
1794
default:
1795
ShouldNotReachHere();
1796
}
1797
1798
return 0.0f;
1799
}
1800
1801
//------------------------------num_fall_throughs-----------------------------
1802
// Return the number of fall-through candidates for a block
1803
int Block::num_fall_throughs() {
1804
int eidx = end_idx();
1805
Node *n = get_node(eidx); // Get ending Node
1806
1807
int op = n->Opcode();
1808
if (n->is_Mach()) {
1809
if (n->is_MachNullCheck()) {
1810
// In theory, either side can fall-thru, for simplicity sake,
1811
// let's say only the false branch can now.
1812
return 1;
1813
}
1814
op = n->as_Mach()->ideal_Opcode();
1815
}
1816
1817
// Switch on branch type
1818
switch( op ) {
1819
case Op_CountedLoopEnd:
1820
case Op_If:
1821
return 2;
1822
1823
case Op_Root:
1824
case Op_Goto:
1825
return 1;
1826
1827
case Op_Catch: {
1828
for (uint i = 0; i < _num_succs; i++) {
1829
const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1830
if (ci->_con == CatchProjNode::fall_through_index) {
1831
return 1;
1832
}
1833
}
1834
return 0;
1835
}
1836
1837
case Op_Jump:
1838
case Op_NeverBranch:
1839
case Op_TailCall:
1840
case Op_TailJump:
1841
case Op_Return:
1842
case Op_Halt:
1843
case Op_Rethrow:
1844
return 0;
1845
1846
default:
1847
ShouldNotReachHere();
1848
}
1849
1850
return 0;
1851
}
1852
1853
//------------------------------succ_fall_through-----------------------------
1854
// Return true if a specific successor could be fall-through target.
1855
bool Block::succ_fall_through(uint i) {
1856
int eidx = end_idx();
1857
Node *n = get_node(eidx); // Get ending Node
1858
1859
int op = n->Opcode();
1860
if (n->is_Mach()) {
1861
if (n->is_MachNullCheck()) {
1862
// In theory, either side can fall-thru, for simplicity sake,
1863
// let's say only the false branch can now.
1864
return get_node(i + eidx + 1)->Opcode() == Op_IfFalse;
1865
}
1866
op = n->as_Mach()->ideal_Opcode();
1867
}
1868
1869
// Switch on branch type
1870
switch( op ) {
1871
case Op_CountedLoopEnd:
1872
case Op_If:
1873
case Op_Root:
1874
case Op_Goto:
1875
return true;
1876
1877
case Op_Catch: {
1878
const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1879
return ci->_con == CatchProjNode::fall_through_index;
1880
}
1881
1882
case Op_Jump:
1883
case Op_NeverBranch:
1884
case Op_TailCall:
1885
case Op_TailJump:
1886
case Op_Return:
1887
case Op_Halt:
1888
case Op_Rethrow:
1889
return false;
1890
1891
default:
1892
ShouldNotReachHere();
1893
}
1894
1895
return false;
1896
}
1897
1898
//------------------------------update_uncommon_branch------------------------
1899
// Update the probability of a two-branch to be uncommon
1900
void Block::update_uncommon_branch(Block* ub) {
1901
int eidx = end_idx();
1902
Node *n = get_node(eidx); // Get ending Node
1903
1904
int op = n->as_Mach()->ideal_Opcode();
1905
1906
assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If");
1907
assert(num_fall_throughs() == 2, "must be a two way branch block");
1908
1909
// Which successor is ub?
1910
uint s;
1911
for (s = 0; s <_num_succs; s++) {
1912
if (_succs[s] == ub) break;
1913
}
1914
assert(s < 2, "uncommon successor must be found");
1915
1916
// If ub is the true path, make the proability small, else
1917
// ub is the false path, and make the probability large
1918
bool invert = (get_node(s + eidx + 1)->Opcode() == Op_IfFalse);
1919
1920
// Get existing probability
1921
float p = n->as_MachIf()->_prob;
1922
1923
if (invert) p = 1.0 - p;
1924
if (p > PROB_MIN) {
1925
p = PROB_MIN;
1926
}
1927
if (invert) p = 1.0 - p;
1928
1929
n->as_MachIf()->_prob = p;
1930
}
1931
1932
//------------------------------update_succ_freq-------------------------------
1933
// Update the appropriate frequency associated with block 'b', a successor of
1934
// a block in this loop.
1935
void CFGLoop::update_succ_freq(Block* b, float freq) {
1936
if (b->_loop == this) {
1937
if (b == head()) {
1938
// back branch within the loop
1939
// Do nothing now, the loop carried frequency will be
1940
// adjust later in scale_freq().
1941
} else {
1942
// simple branch within the loop
1943
b->_freq += freq;
1944
}
1945
} else if (!in_loop_nest(b)) {
1946
// branch is exit from this loop
1947
BlockProbPair bpp(b, freq);
1948
_exits.append(bpp);
1949
} else {
1950
// branch into nested loop
1951
CFGLoop* ch = b->_loop;
1952
ch->_freq += freq;
1953
}
1954
}
1955
1956
//------------------------------in_loop_nest-----------------------------------
1957
// Determine if block b is in the receiver's loop nest.
1958
bool CFGLoop::in_loop_nest(Block* b) {
1959
int depth = _depth;
1960
CFGLoop* b_loop = b->_loop;
1961
int b_depth = b_loop->_depth;
1962
if (depth == b_depth) {
1963
return true;
1964
}
1965
while (b_depth > depth) {
1966
b_loop = b_loop->_parent;
1967
b_depth = b_loop->_depth;
1968
}
1969
return b_loop == this;
1970
}
1971
1972
//------------------------------scale_freq-------------------------------------
1973
// Scale frequency of loops and blocks by trip counts from outer loops
1974
// Do a top down traversal of loop tree (visit outer loops first.)
1975
void CFGLoop::scale_freq() {
1976
float loop_freq = _freq * trip_count();
1977
_freq = loop_freq;
1978
for (int i = 0; i < _members.length(); i++) {
1979
CFGElement* s = _members.at(i);
1980
float block_freq = s->_freq * loop_freq;
1981
if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)
1982
block_freq = MIN_BLOCK_FREQUENCY;
1983
s->_freq = block_freq;
1984
}
1985
CFGLoop* ch = _child;
1986
while (ch != NULL) {
1987
ch->scale_freq();
1988
ch = ch->_sibling;
1989
}
1990
}
1991
1992
// Frequency of outer loop
1993
float CFGLoop::outer_loop_freq() const {
1994
if (_child != NULL) {
1995
return _child->_freq;
1996
}
1997
return _freq;
1998
}
1999
2000
#ifndef PRODUCT
2001
//------------------------------dump_tree--------------------------------------
2002
void CFGLoop::dump_tree() const {
2003
dump();
2004
if (_child != NULL) _child->dump_tree();
2005
if (_sibling != NULL) _sibling->dump_tree();
2006
}
2007
2008
//------------------------------dump-------------------------------------------
2009
void CFGLoop::dump() const {
2010
for (int i = 0; i < _depth; i++) tty->print(" ");
2011
tty->print("%s: %d trip_count: %6.0f freq: %6.0f\n",
2012
_depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq);
2013
for (int i = 0; i < _depth; i++) tty->print(" ");
2014
tty->print(" members:");
2015
int k = 0;
2016
for (int i = 0; i < _members.length(); i++) {
2017
if (k++ >= 6) {
2018
tty->print("\n ");
2019
for (int j = 0; j < _depth+1; j++) tty->print(" ");
2020
k = 0;
2021
}
2022
CFGElement *s = _members.at(i);
2023
if (s->is_block()) {
2024
Block *b = s->as_Block();
2025
tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq);
2026
} else {
2027
CFGLoop* lp = s->as_CFGLoop();
2028
tty->print(" L%d(%6.3f)", lp->_id, lp->_freq);
2029
}
2030
}
2031
tty->print("\n");
2032
for (int i = 0; i < _depth; i++) tty->print(" ");
2033
tty->print(" exits: ");
2034
k = 0;
2035
for (int i = 0; i < _exits.length(); i++) {
2036
if (k++ >= 7) {
2037
tty->print("\n ");
2038
for (int j = 0; j < _depth+1; j++) tty->print(" ");
2039
k = 0;
2040
}
2041
Block *blk = _exits.at(i).get_target();
2042
float prob = _exits.at(i).get_prob();
2043
tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100));
2044
}
2045
tty->print("\n");
2046
}
2047
#endif
2048
2049