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