1 /* 2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2024, Alibaba Group Holding Limited. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26 #include "classfile/javaClasses.hpp" 27 #include "code/aotCodeCache.hpp" 28 #include "compiler/compileLog.hpp" 29 #include "gc/shared/barrierSet.hpp" 30 #include "gc/shared/c2/barrierSetC2.hpp" 31 #include "gc/shared/tlab_globals.hpp" 32 #include "memory/allocation.inline.hpp" 33 #include "memory/resourceArea.hpp" 34 #include "oops/objArrayKlass.hpp" 35 #include "opto/addnode.hpp" 36 #include "opto/arraycopynode.hpp" 37 #include "opto/cfgnode.hpp" 38 #include "opto/regalloc.hpp" 39 #include "opto/compile.hpp" 40 #include "opto/connode.hpp" 41 #include "opto/convertnode.hpp" 42 #include "opto/loopnode.hpp" 43 #include "opto/machnode.hpp" 44 #include "opto/matcher.hpp" 45 #include "opto/memnode.hpp" 46 #include "opto/mempointer.hpp" 47 #include "opto/mulnode.hpp" 48 #include "opto/narrowptrnode.hpp" 49 #include "opto/phaseX.hpp" 50 #include "opto/regmask.hpp" 51 #include "opto/rootnode.hpp" 52 #include "opto/traceMergeStoresTag.hpp" 53 #include "opto/vectornode.hpp" 54 #include "utilities/align.hpp" 55 #include "utilities/copy.hpp" 56 #include "utilities/macros.hpp" 57 #include "utilities/powerOfTwo.hpp" 58 #include "utilities/vmError.hpp" 59 60 // Portions of code courtesy of Clifford Click 61 62 // Optimization - Graph Style 63 64 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st); 65 66 //============================================================================= 67 uint MemNode::size_of() const { return sizeof(*this); } 68 69 const TypePtr *MemNode::adr_type() const { 70 Node* adr = in(Address); 71 if (adr == nullptr) return nullptr; // node is dead 72 const TypePtr* cross_check = nullptr; 73 DEBUG_ONLY(cross_check = _adr_type); 74 return calculate_adr_type(adr->bottom_type(), cross_check); 75 } 76 77 bool MemNode::check_if_adr_maybe_raw(Node* adr) { 78 if (adr != nullptr) { 79 if (adr->bottom_type()->base() == Type::RawPtr || adr->bottom_type()->base() == Type::AnyPtr) { 80 return true; 81 } 82 } 83 return false; 84 } 85 86 #ifndef PRODUCT 87 void MemNode::dump_spec(outputStream *st) const { 88 if (in(Address) == nullptr) return; // node is dead 89 #ifndef ASSERT 90 // fake the missing field 91 const TypePtr* _adr_type = nullptr; 92 if (in(Address) != nullptr) 93 _adr_type = in(Address)->bottom_type()->isa_ptr(); 94 #endif 95 dump_adr_type(this, _adr_type, st); 96 97 Compile* C = Compile::current(); 98 if (C->alias_type(_adr_type)->is_volatile()) { 99 st->print(" Volatile!"); 100 } 101 if (_unaligned_access) { 102 st->print(" unaligned"); 103 } 104 if (_mismatched_access) { 105 st->print(" mismatched"); 106 } 107 if (_unsafe_access) { 108 st->print(" unsafe"); 109 } 110 } 111 112 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) { 113 st->print(" @"); 114 if (adr_type == nullptr) { 115 st->print("null"); 116 } else { 117 adr_type->dump_on(st); 118 Compile* C = Compile::current(); 119 Compile::AliasType* atp = nullptr; 120 if (C->have_alias_type(adr_type)) atp = C->alias_type(adr_type); 121 if (atp == nullptr) 122 st->print(", idx=?\?;"); 123 else if (atp->index() == Compile::AliasIdxBot) 124 st->print(", idx=Bot;"); 125 else if (atp->index() == Compile::AliasIdxTop) 126 st->print(", idx=Top;"); 127 else if (atp->index() == Compile::AliasIdxRaw) 128 st->print(", idx=Raw;"); 129 else { 130 ciField* field = atp->field(); 131 if (field) { 132 st->print(", name="); 133 field->print_name_on(st); 134 } 135 st->print(", idx=%d;", atp->index()); 136 } 137 } 138 } 139 140 extern void print_alias_types(); 141 142 #endif 143 144 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypeOopPtr *t_oop, Node *load, PhaseGVN *phase) { 145 assert((t_oop != nullptr), "sanity"); 146 bool is_instance = t_oop->is_known_instance_field(); 147 bool is_boxed_value_load = t_oop->is_ptr_to_boxed_value() && 148 (load != nullptr) && load->is_Load() && 149 (phase->is_IterGVN() != nullptr); 150 if (!(is_instance || is_boxed_value_load)) 151 return mchain; // don't try to optimize non-instance types 152 uint instance_id = t_oop->instance_id(); 153 Node *start_mem = phase->C->start()->proj_out_or_null(TypeFunc::Memory); 154 Node *prev = nullptr; 155 Node *result = mchain; 156 while (prev != result) { 157 prev = result; 158 if (result == start_mem) 159 break; // hit one of our sentinels 160 // skip over a call which does not affect this memory slice 161 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) { 162 Node *proj_in = result->in(0); 163 if (proj_in->is_Allocate() && proj_in->_idx == instance_id) { 164 break; // hit one of our sentinels 165 } else if (proj_in->is_Call()) { 166 // ArrayCopyNodes processed here as well 167 CallNode *call = proj_in->as_Call(); 168 if (!call->may_modify(t_oop, phase)) { // returns false for instances 169 result = call->in(TypeFunc::Memory); 170 } 171 } else if (proj_in->is_Initialize()) { 172 AllocateNode* alloc = proj_in->as_Initialize()->allocation(); 173 // Stop if this is the initialization for the object instance which 174 // contains this memory slice, otherwise skip over it. 175 if ((alloc == nullptr) || (alloc->_idx == instance_id)) { 176 break; 177 } 178 if (is_instance) { 179 result = proj_in->in(TypeFunc::Memory); 180 } else if (is_boxed_value_load) { 181 Node* klass = alloc->in(AllocateNode::KlassNode); 182 const TypeKlassPtr* tklass = phase->type(klass)->is_klassptr(); 183 if (tklass->klass_is_exact() && !tklass->exact_klass()->equals(t_oop->is_instptr()->exact_klass())) { 184 result = proj_in->in(TypeFunc::Memory); // not related allocation 185 } 186 } 187 } else if (proj_in->is_MemBar()) { 188 ArrayCopyNode* ac = nullptr; 189 if (ArrayCopyNode::may_modify(t_oop, proj_in->as_MemBar(), phase, ac)) { 190 break; 191 } 192 result = proj_in->in(TypeFunc::Memory); 193 } else if (proj_in->is_top()) { 194 break; // dead code 195 } else { 196 assert(false, "unexpected projection"); 197 } 198 } else if (result->is_ClearArray()) { 199 if (!is_instance || !ClearArrayNode::step_through(&result, instance_id, phase)) { 200 // Can not bypass initialization of the instance 201 // we are looking for. 202 break; 203 } 204 // Otherwise skip it (the call updated 'result' value). 205 } else if (result->is_MergeMem()) { 206 result = step_through_mergemem(phase, result->as_MergeMem(), t_oop, nullptr, tty); 207 } 208 } 209 return result; 210 } 211 212 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, Node *load, PhaseGVN *phase) { 213 const TypeOopPtr* t_oop = t_adr->isa_oopptr(); 214 if (t_oop == nullptr) 215 return mchain; // don't try to optimize non-oop types 216 Node* result = optimize_simple_memory_chain(mchain, t_oop, load, phase); 217 bool is_instance = t_oop->is_known_instance_field(); 218 PhaseIterGVN *igvn = phase->is_IterGVN(); 219 if (is_instance && igvn != nullptr && result->is_Phi()) { 220 PhiNode *mphi = result->as_Phi(); 221 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required"); 222 const TypePtr *t = mphi->adr_type(); 223 bool do_split = false; 224 // In the following cases, Load memory input can be further optimized based on 225 // its precise address type 226 if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM ) { 227 do_split = true; 228 } else if (t->isa_oopptr() && !t->is_oopptr()->is_known_instance()) { 229 const TypeOopPtr* mem_t = 230 t->is_oopptr()->cast_to_exactness(true) 231 ->is_oopptr()->cast_to_ptr_type(t_oop->ptr()) 232 ->is_oopptr()->cast_to_instance_id(t_oop->instance_id()); 233 if (t_oop->isa_aryptr()) { 234 mem_t = mem_t->is_aryptr() 235 ->cast_to_stable(t_oop->is_aryptr()->is_stable()) 236 ->cast_to_size(t_oop->is_aryptr()->size()) 237 ->with_offset(t_oop->is_aryptr()->offset()) 238 ->is_aryptr(); 239 } 240 do_split = mem_t == t_oop; 241 } 242 if (do_split) { 243 // clone the Phi with our address type 244 result = mphi->split_out_instance(t_adr, igvn); 245 } else { 246 assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain"); 247 } 248 } 249 return result; 250 } 251 252 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) { 253 uint alias_idx = phase->C->get_alias_index(tp); 254 Node *mem = mmem; 255 #ifdef ASSERT 256 { 257 // Check that current type is consistent with the alias index used during graph construction 258 assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx"); 259 bool consistent = adr_check == nullptr || adr_check->empty() || 260 phase->C->must_alias(adr_check, alias_idx ); 261 // Sometimes dead array references collapse to a[-1], a[-2], or a[-3] 262 if( !consistent && adr_check != nullptr && !adr_check->empty() && 263 tp->isa_aryptr() && tp->offset() == Type::OffsetBot && 264 adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot && 265 ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() || 266 adr_check->offset() == oopDesc::klass_offset_in_bytes() || 267 adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) { 268 // don't assert if it is dead code. 269 consistent = true; 270 } 271 if( !consistent ) { 272 st->print("alias_idx==%d, adr_check==", alias_idx); 273 if( adr_check == nullptr ) { 274 st->print("null"); 275 } else { 276 adr_check->dump(); 277 } 278 st->cr(); 279 print_alias_types(); 280 assert(consistent, "adr_check must match alias idx"); 281 } 282 } 283 #endif 284 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally 285 // means an array I have not precisely typed yet. Do not do any 286 // alias stuff with it any time soon. 287 const TypeOopPtr *toop = tp->isa_oopptr(); 288 if (tp->base() != Type::AnyPtr && 289 !(toop && 290 toop->isa_instptr() && 291 toop->is_instptr()->instance_klass()->is_java_lang_Object() && 292 toop->offset() == Type::OffsetBot)) { 293 // IGVN _delay_transform may be set to true and if that is the case and mmem 294 // is already a registered node then the validation inside transform will 295 // complain. 296 Node* m = mmem; 297 PhaseIterGVN* igvn = phase->is_IterGVN(); 298 if (igvn == nullptr || !igvn->delay_transform()) { 299 // compress paths and change unreachable cycles to TOP 300 // If not, we can update the input infinitely along a MergeMem cycle 301 // Equivalent code in PhiNode::Ideal 302 m = phase->transform(mmem); 303 } 304 // If transformed to a MergeMem, get the desired slice 305 // Otherwise the returned node represents memory for every slice 306 mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m; 307 // Update input if it is progress over what we have now 308 } 309 return mem; 310 } 311 312 //--------------------------Ideal_common--------------------------------------- 313 // Look for degenerate control and memory inputs. Bypass MergeMem inputs. 314 // Unhook non-raw memories from complete (macro-expanded) initializations. 315 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) { 316 // If our control input is a dead region, kill all below the region 317 Node *ctl = in(MemNode::Control); 318 if (ctl && remove_dead_region(phase, can_reshape)) 319 return this; 320 ctl = in(MemNode::Control); 321 // Don't bother trying to transform a dead node 322 if (ctl && ctl->is_top()) return NodeSentinel; 323 324 PhaseIterGVN *igvn = phase->is_IterGVN(); 325 // Wait if control on the worklist. 326 if (ctl && can_reshape && igvn != nullptr) { 327 Node* bol = nullptr; 328 Node* cmp = nullptr; 329 if (ctl->in(0)->is_If()) { 330 assert(ctl->is_IfTrue() || ctl->is_IfFalse(), "sanity"); 331 bol = ctl->in(0)->in(1); 332 if (bol->is_Bool()) 333 cmp = ctl->in(0)->in(1)->in(1); 334 } 335 if (igvn->_worklist.member(ctl) || 336 (bol != nullptr && igvn->_worklist.member(bol)) || 337 (cmp != nullptr && igvn->_worklist.member(cmp)) ) { 338 // This control path may be dead. 339 // Delay this memory node transformation until the control is processed. 340 igvn->_worklist.push(this); 341 return NodeSentinel; // caller will return null 342 } 343 } 344 // Ignore if memory is dead, or self-loop 345 Node *mem = in(MemNode::Memory); 346 if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return null 347 assert(mem != this, "dead loop in MemNode::Ideal"); 348 349 if (can_reshape && igvn != nullptr && igvn->_worklist.member(mem)) { 350 // This memory slice may be dead. 351 // Delay this mem node transformation until the memory is processed. 352 igvn->_worklist.push(this); 353 return NodeSentinel; // caller will return null 354 } 355 356 Node *address = in(MemNode::Address); 357 const Type *t_adr = phase->type(address); 358 if (t_adr == Type::TOP) return NodeSentinel; // caller will return null 359 360 if (can_reshape && is_unsafe_access() && (t_adr == TypePtr::NULL_PTR)) { 361 // Unsafe off-heap access with zero address. Remove access and other control users 362 // to not confuse optimizations and add a HaltNode to fail if this is ever executed. 363 assert(ctl != nullptr, "unsafe accesses should be control dependent"); 364 for (DUIterator_Fast imax, i = ctl->fast_outs(imax); i < imax; i++) { 365 Node* u = ctl->fast_out(i); 366 if (u != ctl) { 367 igvn->rehash_node_delayed(u); 368 int nb = u->replace_edge(ctl, phase->C->top(), igvn); 369 --i, imax -= nb; 370 } 371 } 372 Node* frame = igvn->transform(new ParmNode(phase->C->start(), TypeFunc::FramePtr)); 373 Node* halt = igvn->transform(new HaltNode(ctl, frame, "unsafe off-heap access with zero address")); 374 phase->C->root()->add_req(halt); 375 return this; 376 } 377 378 if (can_reshape && igvn != nullptr && 379 (igvn->_worklist.member(address) || 380 (igvn->_worklist.size() > 0 && t_adr != adr_type())) ) { 381 // The address's base and type may change when the address is processed. 382 // Delay this mem node transformation until the address is processed. 383 igvn->_worklist.push(this); 384 return NodeSentinel; // caller will return null 385 } 386 387 // Do NOT remove or optimize the next lines: ensure a new alias index 388 // is allocated for an oop pointer type before Escape Analysis. 389 // Note: C++ will not remove it since the call has side effect. 390 if (t_adr->isa_oopptr()) { 391 int alias_idx = phase->C->get_alias_index(t_adr->is_ptr()); 392 } 393 394 Node* base = nullptr; 395 if (address->is_AddP()) { 396 base = address->in(AddPNode::Base); 397 } 398 if (base != nullptr && phase->type(base)->higher_equal(TypePtr::NULL_PTR) && 399 !t_adr->isa_rawptr()) { 400 // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true. 401 // Skip this node optimization if its address has TOP base. 402 return NodeSentinel; // caller will return null 403 } 404 405 // Avoid independent memory operations 406 Node* old_mem = mem; 407 408 // The code which unhooks non-raw memories from complete (macro-expanded) 409 // initializations was removed. After macro-expansion all stores caught 410 // by Initialize node became raw stores and there is no information 411 // which memory slices they modify. So it is unsafe to move any memory 412 // operation above these stores. Also in most cases hooked non-raw memories 413 // were already unhooked by using information from detect_ptr_independence() 414 // and find_previous_store(). 415 416 if (mem->is_MergeMem()) { 417 MergeMemNode* mmem = mem->as_MergeMem(); 418 const TypePtr *tp = t_adr->is_ptr(); 419 420 mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty); 421 } 422 423 if (mem != old_mem) { 424 set_req_X(MemNode::Memory, mem, phase); 425 if (phase->type(mem) == Type::TOP) return NodeSentinel; 426 return this; 427 } 428 429 // let the subclass continue analyzing... 430 return nullptr; 431 } 432 433 // Helper function for proving some simple control dominations. 434 // Attempt to prove that all control inputs of 'dom' dominate 'sub'. 435 // Already assumes that 'dom' is available at 'sub', and that 'sub' 436 // is not a constant (dominated by the method's StartNode). 437 // Used by MemNode::find_previous_store to prove that the 438 // control input of a memory operation predates (dominates) 439 // an allocation it wants to look past. 440 // Returns 'DomResult::Dominate' if all control inputs of 'dom' 441 // dominate 'sub', 'DomResult::NotDominate' if not, 442 // and 'DomResult::EncounteredDeadCode' if we can't decide due to 443 // dead code, but at the end of IGVN, we know the definite result 444 // once the dead code is cleaned up. 445 Node::DomResult MemNode::maybe_all_controls_dominate(Node* dom, Node* sub) { 446 if (dom == nullptr || dom->is_top() || sub == nullptr || sub->is_top()) { 447 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 448 } 449 450 // Check 'dom'. Skip Proj and CatchProj nodes. 451 dom = dom->find_exact_control(dom); 452 if (dom == nullptr || dom->is_top()) { 453 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 454 } 455 456 if (dom == sub) { 457 // For the case when, for example, 'sub' is Initialize and the original 458 // 'dom' is Proj node of the 'sub'. 459 return DomResult::NotDominate; 460 } 461 462 if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub) { 463 return DomResult::Dominate; 464 } 465 466 // 'dom' dominates 'sub' if its control edge and control edges 467 // of all its inputs dominate or equal to sub's control edge. 468 469 // Currently 'sub' is either Allocate, Initialize or Start nodes. 470 // Or Region for the check in LoadNode::Ideal(); 471 // 'sub' should have sub->in(0) != nullptr. 472 assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start() || 473 sub->is_Region() || sub->is_Call(), "expecting only these nodes"); 474 475 // Get control edge of 'sub'. 476 Node* orig_sub = sub; 477 sub = sub->find_exact_control(sub->in(0)); 478 if (sub == nullptr || sub->is_top()) { 479 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 480 } 481 482 assert(sub->is_CFG(), "expecting control"); 483 484 if (sub == dom) { 485 return DomResult::Dominate; 486 } 487 488 if (sub->is_Start() || sub->is_Root()) { 489 return DomResult::NotDominate; 490 } 491 492 { 493 // Check all control edges of 'dom'. 494 495 ResourceMark rm; 496 Node_List nlist; 497 Unique_Node_List dom_list; 498 499 dom_list.push(dom); 500 bool only_dominating_controls = false; 501 502 for (uint next = 0; next < dom_list.size(); next++) { 503 Node* n = dom_list.at(next); 504 if (n == orig_sub) { 505 return DomResult::NotDominate; // One of dom's inputs dominated by sub. 506 } 507 if (!n->is_CFG() && n->pinned()) { 508 // Check only own control edge for pinned non-control nodes. 509 n = n->find_exact_control(n->in(0)); 510 if (n == nullptr || n->is_top()) { 511 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 512 } 513 assert(n->is_CFG(), "expecting control"); 514 dom_list.push(n); 515 } else if (n->is_Con() || n->is_Start() || n->is_Root()) { 516 only_dominating_controls = true; 517 } else if (n->is_CFG()) { 518 DomResult dom_result = n->dominates(sub, nlist); 519 if (dom_result == DomResult::Dominate) { 520 only_dominating_controls = true; 521 } else { 522 return dom_result; 523 } 524 } else { 525 // First, own control edge. 526 Node* m = n->find_exact_control(n->in(0)); 527 if (m != nullptr) { 528 if (m->is_top()) { 529 return DomResult::EncounteredDeadCode; // Conservative answer for dead code 530 } 531 dom_list.push(m); 532 } 533 // Now, the rest of edges. 534 uint cnt = n->req(); 535 for (uint i = 1; i < cnt; i++) { 536 m = n->find_exact_control(n->in(i)); 537 if (m == nullptr || m->is_top()) { 538 continue; 539 } 540 dom_list.push(m); 541 } 542 } 543 } 544 return only_dominating_controls ? DomResult::Dominate : DomResult::NotDominate; 545 } 546 } 547 548 //---------------------detect_ptr_independence--------------------------------- 549 // Used by MemNode::find_previous_store to prove that two base 550 // pointers are never equal. 551 // The pointers are accompanied by their associated allocations, 552 // if any, which have been previously discovered by the caller. 553 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1, 554 Node* p2, AllocateNode* a2, 555 PhaseTransform* phase) { 556 // Attempt to prove that these two pointers cannot be aliased. 557 // They may both manifestly be allocations, and they should differ. 558 // Or, if they are not both allocations, they can be distinct constants. 559 // Otherwise, one is an allocation and the other a pre-existing value. 560 if (a1 == nullptr && a2 == nullptr) { // neither an allocation 561 return (p1 != p2) && p1->is_Con() && p2->is_Con(); 562 } else if (a1 != nullptr && a2 != nullptr) { // both allocations 563 return (a1 != a2); 564 } else if (a1 != nullptr) { // one allocation a1 565 // (Note: p2->is_Con implies p2->in(0)->is_Root, which dominates.) 566 return all_controls_dominate(p2, a1); 567 } else { //(a2 != null) // one allocation a2 568 return all_controls_dominate(p1, a2); 569 } 570 return false; 571 } 572 573 574 // Find an arraycopy ac that produces the memory state represented by parameter mem. 575 // Return ac if 576 // (a) can_see_stored_value=true and ac must have set the value for this load or if 577 // (b) can_see_stored_value=false and ac could have set the value for this load or if 578 // (c) can_see_stored_value=false and ac cannot have set the value for this load. 579 // In case (c) change the parameter mem to the memory input of ac to skip it 580 // when searching stored value. 581 // Otherwise return null. 582 Node* LoadNode::find_previous_arraycopy(PhaseValues* phase, Node* ld_alloc, Node*& mem, bool can_see_stored_value) const { 583 ArrayCopyNode* ac = find_array_copy_clone(ld_alloc, mem); 584 if (ac != nullptr) { 585 Node* ld_addp = in(MemNode::Address); 586 Node* src = ac->in(ArrayCopyNode::Src); 587 const TypeAryPtr* ary_t = phase->type(src)->isa_aryptr(); 588 589 // This is a load from a cloned array. The corresponding arraycopy ac must 590 // have set the value for the load and we can return ac but only if the load 591 // is known to be within bounds. This is checked below. 592 if (ary_t != nullptr && ld_addp->is_AddP()) { 593 Node* ld_offs = ld_addp->in(AddPNode::Offset); 594 BasicType ary_elem = ary_t->elem()->array_element_basic_type(); 595 jlong header = arrayOopDesc::base_offset_in_bytes(ary_elem); 596 jlong elemsize = type2aelembytes(ary_elem); 597 598 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); 599 const TypeInt* sizetype = ary_t->size(); 600 601 if (ld_offs_t->_lo >= header && ld_offs_t->_hi < (sizetype->_lo * elemsize + header)) { 602 // The load is known to be within bounds. It receives its value from ac. 603 return ac; 604 } 605 // The load is known to be out-of-bounds. 606 } 607 // The load could be out-of-bounds. It must not be hoisted but must remain 608 // dependent on the runtime range check. This is achieved by returning null. 609 } else if (mem->is_Proj() && mem->in(0) != nullptr && mem->in(0)->is_ArrayCopy()) { 610 ArrayCopyNode* ac = mem->in(0)->as_ArrayCopy(); 611 612 if (ac->is_arraycopy_validated() || 613 ac->is_copyof_validated() || 614 ac->is_copyofrange_validated()) { 615 Node* ld_addp = in(MemNode::Address); 616 if (ld_addp->is_AddP()) { 617 Node* ld_base = ld_addp->in(AddPNode::Address); 618 Node* ld_offs = ld_addp->in(AddPNode::Offset); 619 620 Node* dest = ac->in(ArrayCopyNode::Dest); 621 622 if (dest == ld_base) { 623 const TypeX* ld_offs_t = phase->type(ld_offs)->isa_intptr_t(); 624 assert(!ld_offs_t->empty(), "dead reference should be checked already"); 625 // Take into account vector or unsafe access size 626 jlong ld_size_in_bytes = (jlong)memory_size(); 627 jlong offset_hi = ld_offs_t->_hi + ld_size_in_bytes - 1; 628 offset_hi = MIN2(offset_hi, (jlong)(TypeX::MAX->_hi)); // Take care for overflow in 32-bit VM 629 if (ac->modifies(ld_offs_t->_lo, (intptr_t)offset_hi, phase, can_see_stored_value)) { 630 return ac; 631 } 632 if (!can_see_stored_value) { 633 mem = ac->in(TypeFunc::Memory); 634 return ac; 635 } 636 } 637 } 638 } 639 } 640 return nullptr; 641 } 642 643 ArrayCopyNode* MemNode::find_array_copy_clone(Node* ld_alloc, Node* mem) const { 644 if (mem->is_Proj() && mem->in(0) != nullptr && (mem->in(0)->Opcode() == Op_MemBarStoreStore || 645 mem->in(0)->Opcode() == Op_MemBarCPUOrder)) { 646 if (ld_alloc != nullptr) { 647 // Check if there is an array copy for a clone 648 Node* mb = mem->in(0); 649 ArrayCopyNode* ac = nullptr; 650 if (mb->in(0) != nullptr && mb->in(0)->is_Proj() && 651 mb->in(0)->in(0) != nullptr && mb->in(0)->in(0)->is_ArrayCopy()) { 652 ac = mb->in(0)->in(0)->as_ArrayCopy(); 653 } else { 654 // Step over GC barrier when ReduceInitialCardMarks is disabled 655 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 656 Node* control_proj_ac = bs->step_over_gc_barrier(mb->in(0)); 657 658 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) { 659 ac = control_proj_ac->in(0)->as_ArrayCopy(); 660 } 661 } 662 663 if (ac != nullptr && ac->is_clonebasic()) { 664 AllocateNode* alloc = AllocateNode::Ideal_allocation(ac->in(ArrayCopyNode::Dest)); 665 if (alloc != nullptr && alloc == ld_alloc) { 666 return ac; 667 } 668 } 669 } 670 } 671 return nullptr; 672 } 673 674 // The logic for reordering loads and stores uses four steps: 675 // (a) Walk carefully past stores and initializations which we 676 // can prove are independent of this load. 677 // (b) Observe that the next memory state makes an exact match 678 // with self (load or store), and locate the relevant store. 679 // (c) Ensure that, if we were to wire self directly to the store, 680 // the optimizer would fold it up somehow. 681 // (d) Do the rewiring, and return, depending on some other part of 682 // the optimizer to fold up the load. 683 // This routine handles steps (a) and (b). Steps (c) and (d) are 684 // specific to loads and stores, so they are handled by the callers. 685 // (Currently, only LoadNode::Ideal has steps (c), (d). More later.) 686 // 687 Node* MemNode::find_previous_store(PhaseValues* phase) { 688 Node* ctrl = in(MemNode::Control); 689 Node* adr = in(MemNode::Address); 690 intptr_t offset = 0; 691 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 692 AllocateNode* alloc = AllocateNode::Ideal_allocation(base); 693 694 if (offset == Type::OffsetBot) 695 return nullptr; // cannot unalias unless there are precise offsets 696 697 const bool adr_maybe_raw = check_if_adr_maybe_raw(adr); 698 const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr(); 699 700 intptr_t size_in_bytes = memory_size(); 701 702 Node* mem = in(MemNode::Memory); // start searching here... 703 704 int cnt = 50; // Cycle limiter 705 for (;;) { // While we can dance past unrelated stores... 706 if (--cnt < 0) break; // Caught in cycle or a complicated dance? 707 708 Node* prev = mem; 709 if (mem->is_Store()) { 710 Node* st_adr = mem->in(MemNode::Address); 711 intptr_t st_offset = 0; 712 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset); 713 if (st_base == nullptr) 714 break; // inscrutable pointer 715 716 // For raw accesses it's not enough to prove that constant offsets don't intersect. 717 // We need the bases to be the equal in order for the offset check to make sense. 718 if ((adr_maybe_raw || check_if_adr_maybe_raw(st_adr)) && st_base != base) { 719 break; 720 } 721 722 if (st_offset != offset && st_offset != Type::OffsetBot) { 723 const int MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize); 724 assert(mem->as_Store()->memory_size() <= MAX_STORE, ""); 725 if (st_offset >= offset + size_in_bytes || 726 st_offset <= offset - MAX_STORE || 727 st_offset <= offset - mem->as_Store()->memory_size()) { 728 // Success: The offsets are provably independent. 729 // (You may ask, why not just test st_offset != offset and be done? 730 // The answer is that stores of different sizes can co-exist 731 // in the same sequence of RawMem effects. We sometimes initialize 732 // a whole 'tile' of array elements with a single jint or jlong.) 733 mem = mem->in(MemNode::Memory); 734 continue; // (a) advance through independent store memory 735 } 736 } 737 if (st_base != base && 738 detect_ptr_independence(base, alloc, 739 st_base, 740 AllocateNode::Ideal_allocation(st_base), 741 phase)) { 742 // Success: The bases are provably independent. 743 mem = mem->in(MemNode::Memory); 744 continue; // (a) advance through independent store memory 745 } 746 747 // (b) At this point, if the bases or offsets do not agree, we lose, 748 // since we have not managed to prove 'this' and 'mem' independent. 749 if (st_base == base && st_offset == offset) { 750 return mem; // let caller handle steps (c), (d) 751 } 752 753 } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) { 754 InitializeNode* st_init = mem->in(0)->as_Initialize(); 755 AllocateNode* st_alloc = st_init->allocation(); 756 if (st_alloc == nullptr) { 757 break; // something degenerated 758 } 759 bool known_identical = false; 760 bool known_independent = false; 761 if (alloc == st_alloc) { 762 known_identical = true; 763 } else if (alloc != nullptr) { 764 known_independent = true; 765 } else if (all_controls_dominate(this, st_alloc)) { 766 known_independent = true; 767 } 768 769 if (known_independent) { 770 // The bases are provably independent: Either they are 771 // manifestly distinct allocations, or else the control 772 // of this load dominates the store's allocation. 773 int alias_idx = phase->C->get_alias_index(adr_type()); 774 if (alias_idx == Compile::AliasIdxRaw) { 775 mem = st_alloc->in(TypeFunc::Memory); 776 } else { 777 mem = st_init->memory(alias_idx); 778 } 779 continue; // (a) advance through independent store memory 780 } 781 782 // (b) at this point, if we are not looking at a store initializing 783 // the same allocation we are loading from, we lose. 784 if (known_identical) { 785 // From caller, can_see_stored_value will consult find_captured_store. 786 return mem; // let caller handle steps (c), (d) 787 } 788 789 } else if (find_previous_arraycopy(phase, alloc, mem, false) != nullptr) { 790 if (prev != mem) { 791 // Found an arraycopy but it doesn't affect that load 792 continue; 793 } 794 // Found an arraycopy that may affect that load 795 return mem; 796 } else if (addr_t != nullptr && addr_t->is_known_instance_field()) { 797 // Can't use optimize_simple_memory_chain() since it needs PhaseGVN. 798 if (mem->is_Proj() && mem->in(0)->is_Call()) { 799 // ArrayCopyNodes processed here as well. 800 CallNode *call = mem->in(0)->as_Call(); 801 if (!call->may_modify(addr_t, phase)) { 802 mem = call->in(TypeFunc::Memory); 803 continue; // (a) advance through independent call memory 804 } 805 } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) { 806 ArrayCopyNode* ac = nullptr; 807 if (ArrayCopyNode::may_modify(addr_t, mem->in(0)->as_MemBar(), phase, ac)) { 808 break; 809 } 810 mem = mem->in(0)->in(TypeFunc::Memory); 811 continue; // (a) advance through independent MemBar memory 812 } else if (mem->is_ClearArray()) { 813 if (ClearArrayNode::step_through(&mem, (uint)addr_t->instance_id(), phase)) { 814 // (the call updated 'mem' value) 815 continue; // (a) advance through independent allocation memory 816 } else { 817 // Can not bypass initialization of the instance 818 // we are looking for. 819 return mem; 820 } 821 } else if (mem->is_MergeMem()) { 822 int alias_idx = phase->C->get_alias_index(adr_type()); 823 mem = mem->as_MergeMem()->memory_at(alias_idx); 824 continue; // (a) advance through independent MergeMem memory 825 } 826 } 827 828 // Unless there is an explicit 'continue', we must bail out here, 829 // because 'mem' is an inscrutable memory state (e.g., a call). 830 break; 831 } 832 833 return nullptr; // bail out 834 } 835 836 //----------------------calculate_adr_type------------------------------------- 837 // Helper function. Notices when the given type of address hits top or bottom. 838 // Also, asserts a cross-check of the type against the expected address type. 839 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) { 840 if (t == Type::TOP) return nullptr; // does not touch memory any more? 841 #ifdef ASSERT 842 if (!VerifyAliases || VMError::is_error_reported() || Node::in_dump()) cross_check = nullptr; 843 #endif 844 const TypePtr* tp = t->isa_ptr(); 845 if (tp == nullptr) { 846 assert(cross_check == nullptr || cross_check == TypePtr::BOTTOM, "expected memory type must be wide"); 847 return TypePtr::BOTTOM; // touches lots of memory 848 } else { 849 #ifdef ASSERT 850 // %%%% [phh] We don't check the alias index if cross_check is 851 // TypeRawPtr::BOTTOM. Needs to be investigated. 852 if (cross_check != nullptr && 853 cross_check != TypePtr::BOTTOM && 854 cross_check != TypeRawPtr::BOTTOM) { 855 // Recheck the alias index, to see if it has changed (due to a bug). 856 Compile* C = Compile::current(); 857 assert(C->get_alias_index(cross_check) == C->get_alias_index(tp), 858 "must stay in the original alias category"); 859 // The type of the address must be contained in the adr_type, 860 // disregarding "null"-ness. 861 // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.) 862 const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr(); 863 assert(cross_check->meet(tp_notnull) == cross_check->remove_speculative(), 864 "real address must not escape from expected memory type"); 865 } 866 #endif 867 return tp; 868 } 869 } 870 871 uint8_t MemNode::barrier_data(const Node* n) { 872 if (n->is_LoadStore()) { 873 return n->as_LoadStore()->barrier_data(); 874 } else if (n->is_Mem()) { 875 return n->as_Mem()->barrier_data(); 876 } 877 return 0; 878 } 879 880 //============================================================================= 881 // Should LoadNode::Ideal() attempt to remove control edges? 882 bool LoadNode::can_remove_control() const { 883 return !has_pinned_control_dependency(); 884 } 885 uint LoadNode::size_of() const { return sizeof(*this); } 886 bool LoadNode::cmp(const Node &n) const { 887 LoadNode& load = (LoadNode &)n; 888 return Type::equals(_type, load._type) && 889 _control_dependency == load._control_dependency && 890 _mo == load._mo; 891 } 892 const Type *LoadNode::bottom_type() const { return _type; } 893 uint LoadNode::ideal_reg() const { 894 return _type->ideal_reg(); 895 } 896 897 #ifndef PRODUCT 898 void LoadNode::dump_spec(outputStream *st) const { 899 MemNode::dump_spec(st); 900 if( !Verbose && !WizardMode ) { 901 // standard dump does this in Verbose and WizardMode 902 st->print(" #"); _type->dump_on(st); 903 } 904 if (!depends_only_on_test()) { 905 st->print(" (does not depend only on test, "); 906 if (control_dependency() == UnknownControl) { 907 st->print("unknown control"); 908 } else if (control_dependency() == Pinned) { 909 st->print("pinned"); 910 } else if (adr_type() == TypeRawPtr::BOTTOM) { 911 st->print("raw access"); 912 } else { 913 st->print("unknown reason"); 914 } 915 st->print(")"); 916 } 917 } 918 #endif 919 920 #ifdef ASSERT 921 //----------------------------is_immutable_value------------------------------- 922 // Helper function to allow a raw load without control edge for some cases 923 bool LoadNode::is_immutable_value(Node* adr) { 924 if (adr->is_AddP() && adr->in(AddPNode::Base)->is_top() && 925 adr->in(AddPNode::Address)->Opcode() == Op_ThreadLocal) { 926 927 jlong offset = adr->in(AddPNode::Offset)->find_intptr_t_con(-1); 928 int offsets[] = { 929 in_bytes(JavaThread::osthread_offset()), 930 in_bytes(JavaThread::threadObj_offset()), 931 in_bytes(JavaThread::vthread_offset()), 932 in_bytes(JavaThread::scopedValueCache_offset()), 933 }; 934 935 for (size_t i = 0; i < sizeof offsets / sizeof offsets[0]; i++) { 936 if (offset == offsets[i]) { 937 return true; 938 } 939 } 940 } 941 942 return false; 943 } 944 #endif 945 946 //----------------------------LoadNode::make----------------------------------- 947 // Polymorphic factory method: 948 Node* LoadNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt, BasicType bt, MemOrd mo, 949 ControlDependency control_dependency, bool require_atomic_access, bool unaligned, bool mismatched, bool unsafe, uint8_t barrier_data) { 950 Compile* C = gvn.C; 951 952 // sanity check the alias category against the created node type 953 assert(!(adr_type->isa_oopptr() && 954 adr_type->offset() == oopDesc::klass_offset_in_bytes()), 955 "use LoadKlassNode instead"); 956 assert(!(adr_type->isa_aryptr() && 957 adr_type->offset() == arrayOopDesc::length_offset_in_bytes()), 958 "use LoadRangeNode instead"); 959 // Check control edge of raw loads 960 assert( ctl != nullptr || C->get_alias_index(adr_type) != Compile::AliasIdxRaw || 961 // oop will be recorded in oop map if load crosses safepoint 962 rt->isa_oopptr() || is_immutable_value(adr), 963 "raw memory operations should have control edge"); 964 LoadNode* load = nullptr; 965 switch (bt) { 966 case T_BOOLEAN: load = new LoadUBNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 967 case T_BYTE: load = new LoadBNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 968 case T_INT: load = new LoadINode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 969 case T_CHAR: load = new LoadUSNode(ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 970 case T_SHORT: load = new LoadSNode (ctl, mem, adr, adr_type, rt->is_int(), mo, control_dependency); break; 971 case T_LONG: load = new LoadLNode (ctl, mem, adr, adr_type, rt->is_long(), mo, control_dependency, require_atomic_access); break; 972 case T_FLOAT: load = new LoadFNode (ctl, mem, adr, adr_type, rt, mo, control_dependency); break; 973 case T_DOUBLE: load = new LoadDNode (ctl, mem, adr, adr_type, rt, mo, control_dependency, require_atomic_access); break; 974 case T_ADDRESS: load = new LoadPNode (ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); break; 975 case T_OBJECT: 976 case T_NARROWOOP: 977 #ifdef _LP64 978 if (adr->bottom_type()->is_ptr_to_narrowoop()) { 979 load = new LoadNNode(ctl, mem, adr, adr_type, rt->make_narrowoop(), mo, control_dependency); 980 } else 981 #endif 982 { 983 assert(!adr->bottom_type()->is_ptr_to_narrowoop() && !adr->bottom_type()->is_ptr_to_narrowklass(), "should have got back a narrow oop"); 984 load = new LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr(), mo, control_dependency); 985 } 986 break; 987 default: 988 ShouldNotReachHere(); 989 break; 990 } 991 assert(load != nullptr, "LoadNode should have been created"); 992 if (unaligned) { 993 load->set_unaligned_access(); 994 } 995 if (mismatched) { 996 load->set_mismatched_access(); 997 } 998 if (unsafe) { 999 load->set_unsafe_access(); 1000 } 1001 load->set_barrier_data(barrier_data); 1002 if (load->Opcode() == Op_LoadN) { 1003 Node* ld = gvn.transform(load); 1004 return new DecodeNNode(ld, ld->bottom_type()->make_ptr()); 1005 } 1006 1007 return load; 1008 } 1009 1010 //------------------------------hash------------------------------------------- 1011 uint LoadNode::hash() const { 1012 // unroll addition of interesting fields 1013 return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address); 1014 } 1015 1016 static bool skip_through_membars(Compile::AliasType* atp, const TypeInstPtr* tp, bool eliminate_boxing) { 1017 if ((atp != nullptr) && (atp->index() >= Compile::AliasIdxRaw)) { 1018 bool non_volatile = (atp->field() != nullptr) && !atp->field()->is_volatile(); 1019 bool is_stable_ary = FoldStableValues && 1020 (tp != nullptr) && (tp->isa_aryptr() != nullptr) && 1021 tp->isa_aryptr()->is_stable(); 1022 1023 return (eliminate_boxing && non_volatile) || is_stable_ary; 1024 } 1025 1026 return false; 1027 } 1028 1029 LoadNode* LoadNode::pin_array_access_node() const { 1030 const TypePtr* adr_type = this->adr_type(); 1031 if (adr_type != nullptr && adr_type->isa_aryptr()) { 1032 return clone_pinned(); 1033 } 1034 return nullptr; 1035 } 1036 1037 // Is the value loaded previously stored by an arraycopy? If so return 1038 // a load node that reads from the source array so we may be able to 1039 // optimize out the ArrayCopy node later. 1040 Node* LoadNode::can_see_arraycopy_value(Node* st, PhaseGVN* phase) const { 1041 Node* ld_adr = in(MemNode::Address); 1042 intptr_t ld_off = 0; 1043 AllocateNode* ld_alloc = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off); 1044 Node* ac = find_previous_arraycopy(phase, ld_alloc, st, true); 1045 if (ac != nullptr) { 1046 assert(ac->is_ArrayCopy(), "what kind of node can this be?"); 1047 1048 Node* mem = ac->in(TypeFunc::Memory); 1049 Node* ctl = ac->in(0); 1050 Node* src = ac->in(ArrayCopyNode::Src); 1051 1052 if (!ac->as_ArrayCopy()->is_clonebasic() && !phase->type(src)->isa_aryptr()) { 1053 return nullptr; 1054 } 1055 1056 // load depends on the tests that validate the arraycopy 1057 LoadNode* ld = clone_pinned(); 1058 Node* addp = in(MemNode::Address)->clone(); 1059 if (ac->as_ArrayCopy()->is_clonebasic()) { 1060 assert(ld_alloc != nullptr, "need an alloc"); 1061 assert(addp->is_AddP(), "address must be addp"); 1062 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1063 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Base)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern"); 1064 assert(bs->step_over_gc_barrier(addp->in(AddPNode::Address)) == bs->step_over_gc_barrier(ac->in(ArrayCopyNode::Dest)), "strange pattern"); 1065 addp->set_req(AddPNode::Base, src); 1066 addp->set_req(AddPNode::Address, src); 1067 } else { 1068 assert(ac->as_ArrayCopy()->is_arraycopy_validated() || 1069 ac->as_ArrayCopy()->is_copyof_validated() || 1070 ac->as_ArrayCopy()->is_copyofrange_validated(), "only supported cases"); 1071 assert(addp->in(AddPNode::Base) == addp->in(AddPNode::Address), "should be"); 1072 addp->set_req(AddPNode::Base, src); 1073 addp->set_req(AddPNode::Address, src); 1074 1075 const TypeAryPtr* ary_t = phase->type(in(MemNode::Address))->isa_aryptr(); 1076 BasicType ary_elem = ary_t->isa_aryptr()->elem()->array_element_basic_type(); 1077 if (is_reference_type(ary_elem, true)) ary_elem = T_OBJECT; 1078 1079 uint header = arrayOopDesc::base_offset_in_bytes(ary_elem); 1080 uint shift = exact_log2(type2aelembytes(ary_elem)); 1081 1082 Node* diff = phase->transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos))); 1083 #ifdef _LP64 1084 diff = phase->transform(new ConvI2LNode(diff)); 1085 #endif 1086 diff = phase->transform(new LShiftXNode(diff, phase->intcon(shift))); 1087 1088 Node* offset = phase->transform(new AddXNode(addp->in(AddPNode::Offset), diff)); 1089 addp->set_req(AddPNode::Offset, offset); 1090 } 1091 addp = phase->transform(addp); 1092 #ifdef ASSERT 1093 const TypePtr* adr_type = phase->type(addp)->is_ptr(); 1094 ld->_adr_type = adr_type; 1095 #endif 1096 ld->set_req(MemNode::Address, addp); 1097 ld->set_req(0, ctl); 1098 ld->set_req(MemNode::Memory, mem); 1099 return ld; 1100 } 1101 return nullptr; 1102 } 1103 1104 1105 //---------------------------can_see_stored_value------------------------------ 1106 // This routine exists to make sure this set of tests is done the same 1107 // everywhere. We need to make a coordinated change: first LoadNode::Ideal 1108 // will change the graph shape in a way which makes memory alive twice at the 1109 // same time (uses the Oracle model of aliasing), then some 1110 // LoadXNode::Identity will fold things back to the equivalence-class model 1111 // of aliasing. 1112 Node* MemNode::can_see_stored_value(Node* st, PhaseValues* phase) const { 1113 Node* ld_adr = in(MemNode::Address); 1114 intptr_t ld_off = 0; 1115 Node* ld_base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ld_off); 1116 Node* ld_alloc = AllocateNode::Ideal_allocation(ld_base); 1117 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr(); 1118 Compile::AliasType* atp = (tp != nullptr) ? phase->C->alias_type(tp) : nullptr; 1119 // This is more general than load from boxing objects. 1120 if (skip_through_membars(atp, tp, phase->C->eliminate_boxing())) { 1121 uint alias_idx = atp->index(); 1122 Node* result = nullptr; 1123 Node* current = st; 1124 // Skip through chains of MemBarNodes checking the MergeMems for 1125 // new states for the slice of this load. Stop once any other 1126 // kind of node is encountered. Loads from final memory can skip 1127 // through any kind of MemBar but normal loads shouldn't skip 1128 // through MemBarAcquire since the could allow them to move out of 1129 // a synchronized region. It is not safe to step over MemBarCPUOrder, 1130 // because alias info above them may be inaccurate (e.g., due to 1131 // mixed/mismatched unsafe accesses). 1132 bool is_final_mem = !atp->is_rewritable(); 1133 while (current->is_Proj()) { 1134 int opc = current->in(0)->Opcode(); 1135 if ((is_final_mem && (opc == Op_MemBarAcquire || 1136 opc == Op_MemBarAcquireLock || 1137 opc == Op_LoadFence)) || 1138 opc == Op_MemBarRelease || 1139 opc == Op_StoreFence || 1140 opc == Op_MemBarReleaseLock || 1141 opc == Op_MemBarStoreStore || 1142 opc == Op_StoreStoreFence) { 1143 Node* mem = current->in(0)->in(TypeFunc::Memory); 1144 if (mem->is_MergeMem()) { 1145 MergeMemNode* merge = mem->as_MergeMem(); 1146 Node* new_st = merge->memory_at(alias_idx); 1147 if (new_st == merge->base_memory()) { 1148 // Keep searching 1149 current = new_st; 1150 continue; 1151 } 1152 // Save the new memory state for the slice and fall through 1153 // to exit. 1154 result = new_st; 1155 } 1156 } 1157 break; 1158 } 1159 if (result != nullptr) { 1160 st = result; 1161 } 1162 } 1163 1164 // Loop around twice in the case Load -> Initialize -> Store. 1165 // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.) 1166 for (int trip = 0; trip <= 1; trip++) { 1167 1168 if (st->is_Store()) { 1169 Node* st_adr = st->in(MemNode::Address); 1170 if (st_adr != ld_adr) { 1171 // Try harder before giving up. Unify base pointers with casts (e.g., raw/non-raw pointers). 1172 intptr_t st_off = 0; 1173 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_off); 1174 if (ld_base == nullptr) return nullptr; 1175 if (st_base == nullptr) return nullptr; 1176 if (!ld_base->eqv_uncast(st_base, /*keep_deps=*/true)) return nullptr; 1177 if (ld_off != st_off) return nullptr; 1178 if (ld_off == Type::OffsetBot) return nullptr; 1179 // Same base, same offset. 1180 // Possible improvement for arrays: check index value instead of absolute offset. 1181 1182 // At this point we have proven something like this setup: 1183 // B = << base >> 1184 // L = LoadQ(AddP(Check/CastPP(B), #Off)) 1185 // S = StoreQ(AddP( B , #Off), V) 1186 // (Actually, we haven't yet proven the Q's are the same.) 1187 // In other words, we are loading from a casted version of 1188 // the same pointer-and-offset that we stored to. 1189 // Casted version may carry a dependency and it is respected. 1190 // Thus, we are able to replace L by V. 1191 } 1192 // Now prove that we have a LoadQ matched to a StoreQ, for some Q. 1193 if (store_Opcode() != st->Opcode()) { 1194 return nullptr; 1195 } 1196 // LoadVector/StoreVector needs additional check to ensure the types match. 1197 if (st->is_StoreVector()) { 1198 const TypeVect* in_vt = st->as_StoreVector()->vect_type(); 1199 const TypeVect* out_vt = as_LoadVector()->vect_type(); 1200 if (in_vt != out_vt) { 1201 return nullptr; 1202 } 1203 } 1204 return st->in(MemNode::ValueIn); 1205 } 1206 1207 // A load from a freshly-created object always returns zero. 1208 // (This can happen after LoadNode::Ideal resets the load's memory input 1209 // to find_captured_store, which returned InitializeNode::zero_memory.) 1210 if (st->is_Proj() && st->in(0)->is_Allocate() && 1211 (st->in(0) == ld_alloc) && 1212 (ld_off >= st->in(0)->as_Allocate()->minimum_header_size())) { 1213 // return a zero value for the load's basic type 1214 // (This is one of the few places where a generic PhaseTransform 1215 // can create new nodes. Think of it as lazily manifesting 1216 // virtually pre-existing constants.) 1217 if (value_basic_type() != T_VOID) { 1218 if (ReduceBulkZeroing || find_array_copy_clone(ld_alloc, in(MemNode::Memory)) == nullptr) { 1219 // If ReduceBulkZeroing is disabled, we need to check if the allocation does not belong to an 1220 // ArrayCopyNode clone. If it does, then we cannot assume zero since the initialization is done 1221 // by the ArrayCopyNode. 1222 return phase->zerocon(value_basic_type()); 1223 } 1224 } else { 1225 // TODO: materialize all-zero vector constant 1226 assert(!isa_Load() || as_Load()->type()->isa_vect(), ""); 1227 } 1228 } 1229 1230 // A load from an initialization barrier can match a captured store. 1231 if (st->is_Proj() && st->in(0)->is_Initialize()) { 1232 InitializeNode* init = st->in(0)->as_Initialize(); 1233 AllocateNode* alloc = init->allocation(); 1234 if ((alloc != nullptr) && (alloc == ld_alloc)) { 1235 // examine a captured store value 1236 st = init->find_captured_store(ld_off, memory_size(), phase); 1237 if (st != nullptr) { 1238 continue; // take one more trip around 1239 } 1240 } 1241 } 1242 1243 // Load boxed value from result of valueOf() call is input parameter. 1244 if (this->is_Load() && ld_adr->is_AddP() && 1245 (tp != nullptr) && tp->is_ptr_to_boxed_value()) { 1246 intptr_t ignore = 0; 1247 Node* base = AddPNode::Ideal_base_and_offset(ld_adr, phase, ignore); 1248 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 1249 base = bs->step_over_gc_barrier(base); 1250 if (base != nullptr && base->is_Proj() && 1251 base->as_Proj()->_con == TypeFunc::Parms && 1252 base->in(0)->is_CallStaticJava() && 1253 base->in(0)->as_CallStaticJava()->is_boxing_method()) { 1254 return base->in(0)->in(TypeFunc::Parms); 1255 } 1256 } 1257 1258 break; 1259 } 1260 1261 return nullptr; 1262 } 1263 1264 //----------------------is_instance_field_load_with_local_phi------------------ 1265 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) { 1266 if( in(Memory)->is_Phi() && in(Memory)->in(0) == ctrl && 1267 in(Address)->is_AddP() ) { 1268 const TypeOopPtr* t_oop = in(Address)->bottom_type()->isa_oopptr(); 1269 // Only instances and boxed values. 1270 if( t_oop != nullptr && 1271 (t_oop->is_ptr_to_boxed_value() || 1272 t_oop->is_known_instance_field()) && 1273 t_oop->offset() != Type::OffsetBot && 1274 t_oop->offset() != Type::OffsetTop) { 1275 return true; 1276 } 1277 } 1278 return false; 1279 } 1280 1281 //------------------------------Identity--------------------------------------- 1282 // Loads are identity if previous store is to same address 1283 Node* LoadNode::Identity(PhaseGVN* phase) { 1284 // If the previous store-maker is the right kind of Store, and the store is 1285 // to the same address, then we are equal to the value stored. 1286 Node* mem = in(Memory); 1287 Node* value = can_see_stored_value(mem, phase); 1288 if( value ) { 1289 // byte, short & char stores truncate naturally. 1290 // A load has to load the truncated value which requires 1291 // some sort of masking operation and that requires an 1292 // Ideal call instead of an Identity call. 1293 if (memory_size() < BytesPerInt) { 1294 // If the input to the store does not fit with the load's result type, 1295 // it must be truncated via an Ideal call. 1296 if (!phase->type(value)->higher_equal(phase->type(this))) 1297 return this; 1298 } 1299 // (This works even when value is a Con, but LoadNode::Value 1300 // usually runs first, producing the singleton type of the Con.) 1301 if (!has_pinned_control_dependency() || value->is_Con()) { 1302 return value; 1303 } else { 1304 return this; 1305 } 1306 } 1307 1308 if (has_pinned_control_dependency()) { 1309 return this; 1310 } 1311 // Search for an existing data phi which was generated before for the same 1312 // instance's field to avoid infinite generation of phis in a loop. 1313 Node *region = mem->in(0); 1314 if (is_instance_field_load_with_local_phi(region)) { 1315 const TypeOopPtr *addr_t = in(Address)->bottom_type()->isa_oopptr(); 1316 int this_index = phase->C->get_alias_index(addr_t); 1317 int this_offset = addr_t->offset(); 1318 int this_iid = addr_t->instance_id(); 1319 if (!addr_t->is_known_instance() && 1320 addr_t->is_ptr_to_boxed_value()) { 1321 // Use _idx of address base (could be Phi node) for boxed values. 1322 intptr_t ignore = 0; 1323 Node* base = AddPNode::Ideal_base_and_offset(in(Address), phase, ignore); 1324 if (base == nullptr) { 1325 return this; 1326 } 1327 this_iid = base->_idx; 1328 } 1329 const Type* this_type = bottom_type(); 1330 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) { 1331 Node* phi = region->fast_out(i); 1332 if (phi->is_Phi() && phi != mem && 1333 phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) { 1334 return phi; 1335 } 1336 } 1337 } 1338 1339 return this; 1340 } 1341 1342 // Construct an equivalent unsigned load. 1343 Node* LoadNode::convert_to_unsigned_load(PhaseGVN& gvn) { 1344 BasicType bt = T_ILLEGAL; 1345 const Type* rt = nullptr; 1346 switch (Opcode()) { 1347 case Op_LoadUB: return this; 1348 case Op_LoadUS: return this; 1349 case Op_LoadB: bt = T_BOOLEAN; rt = TypeInt::UBYTE; break; 1350 case Op_LoadS: bt = T_CHAR; rt = TypeInt::CHAR; break; 1351 default: 1352 assert(false, "no unsigned variant: %s", Name()); 1353 return nullptr; 1354 } 1355 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1356 raw_adr_type(), rt, bt, _mo, _control_dependency, 1357 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); 1358 } 1359 1360 // Construct an equivalent signed load. 1361 Node* LoadNode::convert_to_signed_load(PhaseGVN& gvn) { 1362 BasicType bt = T_ILLEGAL; 1363 const Type* rt = nullptr; 1364 switch (Opcode()) { 1365 case Op_LoadUB: bt = T_BYTE; rt = TypeInt::BYTE; break; 1366 case Op_LoadUS: bt = T_SHORT; rt = TypeInt::SHORT; break; 1367 case Op_LoadB: // fall through 1368 case Op_LoadS: // fall through 1369 case Op_LoadI: // fall through 1370 case Op_LoadL: return this; 1371 default: 1372 assert(false, "no signed variant: %s", Name()); 1373 return nullptr; 1374 } 1375 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1376 raw_adr_type(), rt, bt, _mo, _control_dependency, 1377 false /*require_atomic_access*/, is_unaligned_access(), is_mismatched_access()); 1378 } 1379 1380 bool LoadNode::has_reinterpret_variant(const Type* rt) { 1381 BasicType bt = rt->basic_type(); 1382 switch (Opcode()) { 1383 case Op_LoadI: return (bt == T_FLOAT); 1384 case Op_LoadL: return (bt == T_DOUBLE); 1385 case Op_LoadF: return (bt == T_INT); 1386 case Op_LoadD: return (bt == T_LONG); 1387 1388 default: return false; 1389 } 1390 } 1391 1392 Node* LoadNode::convert_to_reinterpret_load(PhaseGVN& gvn, const Type* rt) { 1393 BasicType bt = rt->basic_type(); 1394 assert(has_reinterpret_variant(rt), "no reinterpret variant: %s %s", Name(), type2name(bt)); 1395 bool is_mismatched = is_mismatched_access(); 1396 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); 1397 if (raw_type == nullptr) { 1398 is_mismatched = true; // conservatively match all non-raw accesses as mismatched 1399 } 1400 const int op = Opcode(); 1401 bool require_atomic_access = (op == Op_LoadL && ((LoadLNode*)this)->require_atomic_access()) || 1402 (op == Op_LoadD && ((LoadDNode*)this)->require_atomic_access()); 1403 return LoadNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1404 raw_adr_type(), rt, bt, _mo, _control_dependency, 1405 require_atomic_access, is_unaligned_access(), is_mismatched); 1406 } 1407 1408 bool StoreNode::has_reinterpret_variant(const Type* vt) { 1409 BasicType bt = vt->basic_type(); 1410 switch (Opcode()) { 1411 case Op_StoreI: return (bt == T_FLOAT); 1412 case Op_StoreL: return (bt == T_DOUBLE); 1413 case Op_StoreF: return (bt == T_INT); 1414 case Op_StoreD: return (bt == T_LONG); 1415 1416 default: return false; 1417 } 1418 } 1419 1420 Node* StoreNode::convert_to_reinterpret_store(PhaseGVN& gvn, Node* val, const Type* vt) { 1421 BasicType bt = vt->basic_type(); 1422 assert(has_reinterpret_variant(vt), "no reinterpret variant: %s %s", Name(), type2name(bt)); 1423 const int op = Opcode(); 1424 bool require_atomic_access = (op == Op_StoreL && ((StoreLNode*)this)->require_atomic_access()) || 1425 (op == Op_StoreD && ((StoreDNode*)this)->require_atomic_access()); 1426 StoreNode* st = StoreNode::make(gvn, in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), 1427 raw_adr_type(), val, bt, _mo, require_atomic_access); 1428 1429 bool is_mismatched = is_mismatched_access(); 1430 const TypeRawPtr* raw_type = gvn.type(in(MemNode::Memory))->isa_rawptr(); 1431 if (raw_type == nullptr) { 1432 is_mismatched = true; // conservatively match all non-raw accesses as mismatched 1433 } 1434 if (is_mismatched) { 1435 st->set_mismatched_access(); 1436 } 1437 return st; 1438 } 1439 1440 // We're loading from an object which has autobox behaviour. 1441 // If this object is result of a valueOf call we'll have a phi 1442 // merging a newly allocated object and a load from the cache. 1443 // We want to replace this load with the original incoming 1444 // argument to the valueOf call. 1445 Node* LoadNode::eliminate_autobox(PhaseIterGVN* igvn) { 1446 assert(igvn->C->eliminate_boxing(), "sanity"); 1447 intptr_t ignore = 0; 1448 Node* base = AddPNode::Ideal_base_and_offset(in(Address), igvn, ignore); 1449 if ((base == nullptr) || base->is_Phi()) { 1450 // Push the loads from the phi that comes from valueOf up 1451 // through it to allow elimination of the loads and the recovery 1452 // of the original value. It is done in split_through_phi(). 1453 return nullptr; 1454 } else if (base->is_Load() || 1455 (base->is_DecodeN() && base->in(1)->is_Load())) { 1456 // Eliminate the load of boxed value for integer types from the cache 1457 // array by deriving the value from the index into the array. 1458 // Capture the offset of the load and then reverse the computation. 1459 1460 // Get LoadN node which loads a boxing object from 'cache' array. 1461 if (base->is_DecodeN()) { 1462 base = base->in(1); 1463 } 1464 if (!base->in(Address)->is_AddP()) { 1465 return nullptr; // Complex address 1466 } 1467 AddPNode* address = base->in(Address)->as_AddP(); 1468 Node* cache_base = address->in(AddPNode::Base); 1469 if ((cache_base != nullptr) && cache_base->is_DecodeN()) { 1470 // Get ConP node which is static 'cache' field. 1471 cache_base = cache_base->in(1); 1472 } 1473 if ((cache_base != nullptr) && cache_base->is_Con()) { 1474 const TypeAryPtr* base_type = cache_base->bottom_type()->isa_aryptr(); 1475 if ((base_type != nullptr) && base_type->is_autobox_cache()) { 1476 Node* elements[4]; 1477 int shift = exact_log2(type2aelembytes(T_OBJECT)); 1478 int count = address->unpack_offsets(elements, ARRAY_SIZE(elements)); 1479 if (count > 0 && elements[0]->is_Con() && 1480 (count == 1 || 1481 (count == 2 && elements[1]->Opcode() == Op_LShiftX && 1482 elements[1]->in(2) == igvn->intcon(shift)))) { 1483 ciObjArray* array = base_type->const_oop()->as_obj_array(); 1484 // Fetch the box object cache[0] at the base of the array and get its value 1485 ciInstance* box = array->obj_at(0)->as_instance(); 1486 ciInstanceKlass* ik = box->klass()->as_instance_klass(); 1487 assert(ik->is_box_klass(), "sanity"); 1488 assert(ik->nof_nonstatic_fields() == 1, "change following code"); 1489 if (ik->nof_nonstatic_fields() == 1) { 1490 // This should be true nonstatic_field_at requires calling 1491 // nof_nonstatic_fields so check it anyway 1492 ciConstant c = box->field_value(ik->nonstatic_field_at(0)); 1493 BasicType bt = c.basic_type(); 1494 // Only integer types have boxing cache. 1495 assert(bt == T_BOOLEAN || bt == T_CHAR || 1496 bt == T_BYTE || bt == T_SHORT || 1497 bt == T_INT || bt == T_LONG, "wrong type = %s", type2name(bt)); 1498 jlong cache_low = (bt == T_LONG) ? c.as_long() : c.as_int(); 1499 if (cache_low != (int)cache_low) { 1500 return nullptr; // should not happen since cache is array indexed by value 1501 } 1502 jlong offset = arrayOopDesc::base_offset_in_bytes(T_OBJECT) - (cache_low << shift); 1503 if (offset != (int)offset) { 1504 return nullptr; // should not happen since cache is array indexed by value 1505 } 1506 // Add up all the offsets making of the address of the load 1507 Node* result = elements[0]; 1508 for (int i = 1; i < count; i++) { 1509 result = igvn->transform(new AddXNode(result, elements[i])); 1510 } 1511 // Remove the constant offset from the address and then 1512 result = igvn->transform(new AddXNode(result, igvn->MakeConX(-(int)offset))); 1513 // remove the scaling of the offset to recover the original index. 1514 if (result->Opcode() == Op_LShiftX && result->in(2) == igvn->intcon(shift)) { 1515 // Peel the shift off directly but wrap it in a dummy node 1516 // since Ideal can't return existing nodes 1517 igvn->_worklist.push(result); // remove dead node later 1518 result = new RShiftXNode(result->in(1), igvn->intcon(0)); 1519 } else if (result->is_Add() && result->in(2)->is_Con() && 1520 result->in(1)->Opcode() == Op_LShiftX && 1521 result->in(1)->in(2) == igvn->intcon(shift)) { 1522 // We can't do general optimization: ((X<<Z) + Y) >> Z ==> X + (Y>>Z) 1523 // but for boxing cache access we know that X<<Z will not overflow 1524 // (there is range check) so we do this optimizatrion by hand here. 1525 igvn->_worklist.push(result); // remove dead node later 1526 Node* add_con = new RShiftXNode(result->in(2), igvn->intcon(shift)); 1527 result = new AddXNode(result->in(1)->in(1), igvn->transform(add_con)); 1528 } else { 1529 result = new RShiftXNode(result, igvn->intcon(shift)); 1530 } 1531 #ifdef _LP64 1532 if (bt != T_LONG) { 1533 result = new ConvL2INode(igvn->transform(result)); 1534 } 1535 #else 1536 if (bt == T_LONG) { 1537 result = new ConvI2LNode(igvn->transform(result)); 1538 } 1539 #endif 1540 // Boxing/unboxing can be done from signed & unsigned loads (e.g. LoadUB -> ... -> LoadB pair). 1541 // Need to preserve unboxing load type if it is unsigned. 1542 switch(this->Opcode()) { 1543 case Op_LoadUB: 1544 result = new AndINode(igvn->transform(result), igvn->intcon(0xFF)); 1545 break; 1546 case Op_LoadUS: 1547 result = new AndINode(igvn->transform(result), igvn->intcon(0xFFFF)); 1548 break; 1549 } 1550 return result; 1551 } 1552 } 1553 } 1554 } 1555 } 1556 return nullptr; 1557 } 1558 1559 static bool stable_phi(PhiNode* phi, PhaseGVN *phase) { 1560 Node* region = phi->in(0); 1561 if (region == nullptr) { 1562 return false; // Wait stable graph 1563 } 1564 uint cnt = phi->req(); 1565 for (uint i = 1; i < cnt; i++) { 1566 Node* rc = region->in(i); 1567 if (rc == nullptr || phase->type(rc) == Type::TOP) 1568 return false; // Wait stable graph 1569 Node* in = phi->in(i); 1570 if (in == nullptr || phase->type(in) == Type::TOP) 1571 return false; // Wait stable graph 1572 } 1573 return true; 1574 } 1575 1576 //------------------------------split_through_phi------------------------------ 1577 // Check whether a call to 'split_through_phi' would split this load through the 1578 // Phi *base*. This method is essentially a copy of the validations performed 1579 // by 'split_through_phi'. The first use of this method was in EA code as part 1580 // of simplification of allocation merges. 1581 // Some differences from original method (split_through_phi): 1582 // - If base->is_CastPP(): base = base->in(1) 1583 bool LoadNode::can_split_through_phi_base(PhaseGVN* phase) { 1584 Node* mem = in(Memory); 1585 Node* address = in(Address); 1586 intptr_t ignore = 0; 1587 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1588 1589 if (base->is_CastPP()) { 1590 base = base->in(1); 1591 } 1592 1593 if (req() > 3 || base == nullptr || !base->is_Phi()) { 1594 return false; 1595 } 1596 1597 if (!mem->is_Phi()) { 1598 if (!MemNode::all_controls_dominate(mem, base->in(0))) { 1599 return false; 1600 } 1601 } else if (base->in(0) != mem->in(0)) { 1602 if (!MemNode::all_controls_dominate(mem, base->in(0))) { 1603 return false; 1604 } 1605 } 1606 1607 return true; 1608 } 1609 1610 //------------------------------split_through_phi------------------------------ 1611 // Split instance or boxed field load through Phi. 1612 Node* LoadNode::split_through_phi(PhaseGVN* phase, bool ignore_missing_instance_id) { 1613 if (req() > 3) { 1614 assert(is_LoadVector() && Opcode() != Op_LoadVector, "load has too many inputs"); 1615 // LoadVector subclasses such as LoadVectorMasked have extra inputs that the logic below doesn't take into account 1616 return nullptr; 1617 } 1618 Node* mem = in(Memory); 1619 Node* address = in(Address); 1620 const TypeOopPtr *t_oop = phase->type(address)->isa_oopptr(); 1621 1622 assert((t_oop != nullptr) && 1623 (ignore_missing_instance_id || 1624 t_oop->is_known_instance_field() || 1625 t_oop->is_ptr_to_boxed_value()), "invalid conditions"); 1626 1627 Compile* C = phase->C; 1628 intptr_t ignore = 0; 1629 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1630 bool base_is_phi = (base != nullptr) && base->is_Phi(); 1631 bool load_boxed_values = t_oop->is_ptr_to_boxed_value() && C->aggressive_unboxing() && 1632 (base != nullptr) && (base == address->in(AddPNode::Base)) && 1633 phase->type(base)->higher_equal(TypePtr::NOTNULL); 1634 1635 if (!((mem->is_Phi() || base_is_phi) && 1636 (ignore_missing_instance_id || load_boxed_values || t_oop->is_known_instance_field()))) { 1637 return nullptr; // Neither memory or base are Phi 1638 } 1639 1640 if (mem->is_Phi()) { 1641 if (!stable_phi(mem->as_Phi(), phase)) { 1642 return nullptr; // Wait stable graph 1643 } 1644 uint cnt = mem->req(); 1645 // Check for loop invariant memory. 1646 if (cnt == 3) { 1647 for (uint i = 1; i < cnt; i++) { 1648 Node* in = mem->in(i); 1649 Node* m = optimize_memory_chain(in, t_oop, this, phase); 1650 if (m == mem) { 1651 if (i == 1) { 1652 // if the first edge was a loop, check second edge too. 1653 // If both are replaceable - we are in an infinite loop 1654 Node *n = optimize_memory_chain(mem->in(2), t_oop, this, phase); 1655 if (n == mem) { 1656 break; 1657 } 1658 } 1659 set_req(Memory, mem->in(cnt - i)); 1660 return this; // made change 1661 } 1662 } 1663 } 1664 } 1665 if (base_is_phi) { 1666 if (!stable_phi(base->as_Phi(), phase)) { 1667 return nullptr; // Wait stable graph 1668 } 1669 uint cnt = base->req(); 1670 // Check for loop invariant memory. 1671 if (cnt == 3) { 1672 for (uint i = 1; i < cnt; i++) { 1673 if (base->in(i) == base) { 1674 return nullptr; // Wait stable graph 1675 } 1676 } 1677 } 1678 } 1679 1680 // Split through Phi (see original code in loopopts.cpp). 1681 assert(ignore_missing_instance_id || C->have_alias_type(t_oop), "instance should have alias type"); 1682 1683 // Do nothing here if Identity will find a value 1684 // (to avoid infinite chain of value phis generation). 1685 if (this != Identity(phase)) { 1686 return nullptr; 1687 } 1688 1689 // Select Region to split through. 1690 Node* region; 1691 DomResult dom_result = DomResult::Dominate; 1692 if (!base_is_phi) { 1693 assert(mem->is_Phi(), "sanity"); 1694 region = mem->in(0); 1695 // Skip if the region dominates some control edge of the address. 1696 // We will check `dom_result` later. 1697 dom_result = MemNode::maybe_all_controls_dominate(address, region); 1698 } else if (!mem->is_Phi()) { 1699 assert(base_is_phi, "sanity"); 1700 region = base->in(0); 1701 // Skip if the region dominates some control edge of the memory. 1702 // We will check `dom_result` later. 1703 dom_result = MemNode::maybe_all_controls_dominate(mem, region); 1704 } else if (base->in(0) != mem->in(0)) { 1705 assert(base_is_phi && mem->is_Phi(), "sanity"); 1706 dom_result = MemNode::maybe_all_controls_dominate(mem, base->in(0)); 1707 if (dom_result == DomResult::Dominate) { 1708 region = base->in(0); 1709 } else { 1710 dom_result = MemNode::maybe_all_controls_dominate(address, mem->in(0)); 1711 if (dom_result == DomResult::Dominate) { 1712 region = mem->in(0); 1713 } 1714 // Otherwise we encountered a complex graph. 1715 } 1716 } else { 1717 assert(base->in(0) == mem->in(0), "sanity"); 1718 region = mem->in(0); 1719 } 1720 1721 PhaseIterGVN* igvn = phase->is_IterGVN(); 1722 if (dom_result != DomResult::Dominate) { 1723 if (dom_result == DomResult::EncounteredDeadCode) { 1724 // There is some dead code which eventually will be removed in IGVN. 1725 // Once this is the case, we get an unambiguous dominance result. 1726 // Push the node to the worklist again until the dead code is removed. 1727 igvn->_worklist.push(this); 1728 } 1729 return nullptr; 1730 } 1731 1732 Node* phi = nullptr; 1733 const Type* this_type = this->bottom_type(); 1734 if (t_oop != nullptr && (t_oop->is_known_instance_field() || load_boxed_values)) { 1735 int this_index = C->get_alias_index(t_oop); 1736 int this_offset = t_oop->offset(); 1737 int this_iid = t_oop->is_known_instance_field() ? t_oop->instance_id() : base->_idx; 1738 phi = new PhiNode(region, this_type, nullptr, mem->_idx, this_iid, this_index, this_offset); 1739 } else if (ignore_missing_instance_id) { 1740 phi = new PhiNode(region, this_type, nullptr, mem->_idx); 1741 } else { 1742 return nullptr; 1743 } 1744 1745 for (uint i = 1; i < region->req(); i++) { 1746 Node* x; 1747 Node* the_clone = nullptr; 1748 Node* in = region->in(i); 1749 if (region->is_CountedLoop() && region->as_Loop()->is_strip_mined() && i == LoopNode::EntryControl && 1750 in != nullptr && in->is_OuterStripMinedLoop()) { 1751 // No node should go in the outer strip mined loop 1752 in = in->in(LoopNode::EntryControl); 1753 } 1754 if (in == nullptr || in == C->top()) { 1755 x = C->top(); // Dead path? Use a dead data op 1756 } else { 1757 x = this->clone(); // Else clone up the data op 1758 the_clone = x; // Remember for possible deletion. 1759 // Alter data node to use pre-phi inputs 1760 if (this->in(0) == region) { 1761 x->set_req(0, in); 1762 } else { 1763 x->set_req(0, nullptr); 1764 } 1765 if (mem->is_Phi() && (mem->in(0) == region)) { 1766 x->set_req(Memory, mem->in(i)); // Use pre-Phi input for the clone. 1767 } 1768 if (address->is_Phi() && address->in(0) == region) { 1769 x->set_req(Address, address->in(i)); // Use pre-Phi input for the clone 1770 } 1771 if (base_is_phi && (base->in(0) == region)) { 1772 Node* base_x = base->in(i); // Clone address for loads from boxed objects. 1773 Node* adr_x = phase->transform(new AddPNode(base_x,base_x,address->in(AddPNode::Offset))); 1774 x->set_req(Address, adr_x); 1775 } 1776 } 1777 // Check for a 'win' on some paths 1778 const Type *t = x->Value(igvn); 1779 1780 bool singleton = t->singleton(); 1781 1782 // See comments in PhaseIdealLoop::split_thru_phi(). 1783 if (singleton && t == Type::TOP) { 1784 singleton &= region->is_Loop() && (i != LoopNode::EntryControl); 1785 } 1786 1787 if (singleton) { 1788 x = igvn->makecon(t); 1789 } else { 1790 // We now call Identity to try to simplify the cloned node. 1791 // Note that some Identity methods call phase->type(this). 1792 // Make sure that the type array is big enough for 1793 // our new node, even though we may throw the node away. 1794 // (This tweaking with igvn only works because x is a new node.) 1795 igvn->set_type(x, t); 1796 // If x is a TypeNode, capture any more-precise type permanently into Node 1797 // otherwise it will be not updated during igvn->transform since 1798 // igvn->type(x) is set to x->Value() already. 1799 x->raise_bottom_type(t); 1800 Node* y = x->Identity(igvn); 1801 if (y != x) { 1802 x = y; 1803 } else { 1804 y = igvn->hash_find_insert(x); 1805 if (y) { 1806 x = y; 1807 } else { 1808 // Else x is a new node we are keeping 1809 // We do not need register_new_node_with_optimizer 1810 // because set_type has already been called. 1811 igvn->_worklist.push(x); 1812 } 1813 } 1814 } 1815 if (x != the_clone && the_clone != nullptr) { 1816 igvn->remove_dead_node(the_clone); 1817 } 1818 phi->set_req(i, x); 1819 } 1820 // Record Phi 1821 igvn->register_new_node_with_optimizer(phi); 1822 return phi; 1823 } 1824 1825 AllocateNode* LoadNode::is_new_object_mark_load() const { 1826 if (Opcode() == Op_LoadX) { 1827 Node* address = in(MemNode::Address); 1828 AllocateNode* alloc = AllocateNode::Ideal_allocation(address); 1829 Node* mem = in(MemNode::Memory); 1830 if (alloc != nullptr && mem->is_Proj() && 1831 mem->in(0) != nullptr && 1832 mem->in(0) == alloc->initialization() && 1833 alloc->initialization()->proj_out_or_null(0) != nullptr) { 1834 return alloc; 1835 } 1836 } 1837 return nullptr; 1838 } 1839 1840 1841 //------------------------------Ideal------------------------------------------ 1842 // If the load is from Field memory and the pointer is non-null, it might be possible to 1843 // zero out the control input. 1844 // If the offset is constant and the base is an object allocation, 1845 // try to hook me up to the exact initializing store. 1846 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) { 1847 if (has_pinned_control_dependency()) { 1848 return nullptr; 1849 } 1850 Node* p = MemNode::Ideal_common(phase, can_reshape); 1851 if (p) return (p == NodeSentinel) ? nullptr : p; 1852 1853 Node* ctrl = in(MemNode::Control); 1854 Node* address = in(MemNode::Address); 1855 bool progress = false; 1856 1857 bool addr_mark = ((phase->type(address)->isa_oopptr() || phase->type(address)->isa_narrowoop()) && 1858 phase->type(address)->is_ptr()->offset() == oopDesc::mark_offset_in_bytes()); 1859 1860 // Skip up past a SafePoint control. Cannot do this for Stores because 1861 // pointer stores & cardmarks must stay on the same side of a SafePoint. 1862 if( ctrl != nullptr && ctrl->Opcode() == Op_SafePoint && 1863 phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw && 1864 !addr_mark && 1865 (depends_only_on_test() || has_unknown_control_dependency())) { 1866 ctrl = ctrl->in(0); 1867 set_req(MemNode::Control,ctrl); 1868 progress = true; 1869 } 1870 1871 intptr_t ignore = 0; 1872 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore); 1873 if (base != nullptr 1874 && phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw) { 1875 // Check for useless control edge in some common special cases 1876 if (in(MemNode::Control) != nullptr 1877 && can_remove_control() 1878 && phase->type(base)->higher_equal(TypePtr::NOTNULL) 1879 && all_controls_dominate(base, phase->C->start())) { 1880 // A method-invariant, non-null address (constant or 'this' argument). 1881 set_req(MemNode::Control, nullptr); 1882 progress = true; 1883 } 1884 } 1885 1886 Node* mem = in(MemNode::Memory); 1887 const TypePtr *addr_t = phase->type(address)->isa_ptr(); 1888 1889 if (can_reshape && (addr_t != nullptr)) { 1890 // try to optimize our memory input 1891 Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, this, phase); 1892 if (opt_mem != mem) { 1893 set_req_X(MemNode::Memory, opt_mem, phase); 1894 if (phase->type( opt_mem ) == Type::TOP) return nullptr; 1895 return this; 1896 } 1897 const TypeOopPtr *t_oop = addr_t->isa_oopptr(); 1898 if ((t_oop != nullptr) && 1899 (t_oop->is_known_instance_field() || 1900 t_oop->is_ptr_to_boxed_value())) { 1901 PhaseIterGVN *igvn = phase->is_IterGVN(); 1902 assert(igvn != nullptr, "must be PhaseIterGVN when can_reshape is true"); 1903 if (igvn->_worklist.member(opt_mem)) { 1904 // Delay this transformation until memory Phi is processed. 1905 igvn->_worklist.push(this); 1906 return nullptr; 1907 } 1908 // Split instance field load through Phi. 1909 Node* result = split_through_phi(phase); 1910 if (result != nullptr) return result; 1911 1912 if (t_oop->is_ptr_to_boxed_value()) { 1913 Node* result = eliminate_autobox(igvn); 1914 if (result != nullptr) return result; 1915 } 1916 } 1917 } 1918 1919 // Is there a dominating load that loads the same value? Leave 1920 // anything that is not a load of a field/array element (like 1921 // barriers etc.) alone 1922 if (in(0) != nullptr && !adr_type()->isa_rawptr() && can_reshape) { 1923 for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) { 1924 Node *use = mem->fast_out(i); 1925 if (use != this && 1926 use->Opcode() == Opcode() && 1927 use->in(0) != nullptr && 1928 use->in(0) != in(0) && 1929 use->in(Address) == in(Address)) { 1930 Node* ctl = in(0); 1931 for (int i = 0; i < 10 && ctl != nullptr; i++) { 1932 ctl = IfNode::up_one_dom(ctl); 1933 if (ctl == use->in(0)) { 1934 set_req(0, use->in(0)); 1935 return this; 1936 } 1937 } 1938 } 1939 } 1940 } 1941 1942 // Check for prior store with a different base or offset; make Load 1943 // independent. Skip through any number of them. Bail out if the stores 1944 // are in an endless dead cycle and report no progress. This is a key 1945 // transform for Reflection. However, if after skipping through the Stores 1946 // we can't then fold up against a prior store do NOT do the transform as 1947 // this amounts to using the 'Oracle' model of aliasing. It leaves the same 1948 // array memory alive twice: once for the hoisted Load and again after the 1949 // bypassed Store. This situation only works if EVERYBODY who does 1950 // anti-dependence work knows how to bypass. I.e. we need all 1951 // anti-dependence checks to ask the same Oracle. Right now, that Oracle is 1952 // the alias index stuff. So instead, peek through Stores and IFF we can 1953 // fold up, do so. 1954 Node* prev_mem = find_previous_store(phase); 1955 if (prev_mem != nullptr) { 1956 Node* value = can_see_arraycopy_value(prev_mem, phase); 1957 if (value != nullptr) { 1958 return value; 1959 } 1960 } 1961 // Steps (a), (b): Walk past independent stores to find an exact match. 1962 if (prev_mem != nullptr && prev_mem != in(MemNode::Memory)) { 1963 // (c) See if we can fold up on the spot, but don't fold up here. 1964 // Fold-up might require truncation (for LoadB/LoadS/LoadUS) or 1965 // just return a prior value, which is done by Identity calls. 1966 if (can_see_stored_value(prev_mem, phase)) { 1967 // Make ready for step (d): 1968 set_req_X(MemNode::Memory, prev_mem, phase); 1969 return this; 1970 } 1971 } 1972 1973 return progress ? this : nullptr; 1974 } 1975 1976 // Helper to recognize certain Klass fields which are invariant across 1977 // some group of array types (e.g., int[] or all T[] where T < Object). 1978 const Type* 1979 LoadNode::load_array_final_field(const TypeKlassPtr *tkls, 1980 ciKlass* klass) const { 1981 assert(!UseCompactObjectHeaders || 1982 AOTCodeCache::is_on_for_dump() || 1983 tkls->offset() != in_bytes(Klass::prototype_header_offset()), 1984 "must not happen"); 1985 if (tkls->offset() == in_bytes(Klass::access_flags_offset())) { 1986 // The field is Klass::_access_flags. Return its (constant) value. 1987 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).) 1988 assert(Opcode() == Op_LoadUS, "must load an unsigned short from _access_flags"); 1989 return TypeInt::make(klass->access_flags()); 1990 } 1991 if (tkls->offset() == in_bytes(Klass::misc_flags_offset())) { 1992 // The field is Klass::_misc_flags. Return its (constant) value. 1993 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).) 1994 assert(Opcode() == Op_LoadUB, "must load an unsigned byte from _misc_flags"); 1995 return TypeInt::make(klass->misc_flags()); 1996 } 1997 if (tkls->offset() == in_bytes(Klass::layout_helper_offset())) { 1998 // The field is Klass::_layout_helper. Return its constant value if known. 1999 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper"); 2000 return TypeInt::make(klass->layout_helper()); 2001 } 2002 2003 // No match. 2004 return nullptr; 2005 } 2006 2007 //------------------------------Value----------------------------------------- 2008 const Type* LoadNode::Value(PhaseGVN* phase) const { 2009 // Either input is TOP ==> the result is TOP 2010 Node* mem = in(MemNode::Memory); 2011 const Type *t1 = phase->type(mem); 2012 if (t1 == Type::TOP) return Type::TOP; 2013 Node* adr = in(MemNode::Address); 2014 const TypePtr* tp = phase->type(adr)->isa_ptr(); 2015 if (tp == nullptr || tp->empty()) return Type::TOP; 2016 int off = tp->offset(); 2017 assert(off != Type::OffsetTop, "case covered by TypePtr::empty"); 2018 Compile* C = phase->C; 2019 2020 // If we are loading from a freshly-allocated object, produce a zero, 2021 // if the load is provably beyond the header of the object. 2022 // (Also allow a variable load from a fresh array to produce zero.) 2023 const TypeOopPtr* tinst = tp->isa_oopptr(); 2024 bool is_instance = (tinst != nullptr) && tinst->is_known_instance_field(); 2025 Node* value = can_see_stored_value(mem, phase); 2026 if (value != nullptr && value->is_Con()) { 2027 assert(value->bottom_type()->higher_equal(_type), "sanity"); 2028 return value->bottom_type(); 2029 } 2030 2031 // Try to guess loaded type from pointer type 2032 if (tp->isa_aryptr()) { 2033 const TypeAryPtr* ary = tp->is_aryptr(); 2034 const Type* t = ary->elem(); 2035 2036 // Determine whether the reference is beyond the header or not, by comparing 2037 // the offset against the offset of the start of the array's data. 2038 // Different array types begin at slightly different offsets (12 vs. 16). 2039 // We choose T_BYTE as an example base type that is least restrictive 2040 // as to alignment, which will therefore produce the smallest 2041 // possible base offset. 2042 const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE); 2043 const bool off_beyond_header = (off >= min_base_off); 2044 2045 // Try to constant-fold a stable array element. 2046 if (FoldStableValues && !is_mismatched_access() && ary->is_stable()) { 2047 // Make sure the reference is not into the header and the offset is constant 2048 ciObject* aobj = ary->const_oop(); 2049 if (aobj != nullptr && off_beyond_header && adr->is_AddP() && off != Type::OffsetBot) { 2050 int stable_dimension = (ary->stable_dimension() > 0 ? ary->stable_dimension() - 1 : 0); 2051 const Type* con_type = Type::make_constant_from_array_element(aobj->as_array(), off, 2052 stable_dimension, 2053 value_basic_type(), is_unsigned()); 2054 if (con_type != nullptr) { 2055 return con_type; 2056 } 2057 } 2058 } 2059 2060 // Don't do this for integer types. There is only potential profit if 2061 // the element type t is lower than _type; that is, for int types, if _type is 2062 // more restrictive than t. This only happens here if one is short and the other 2063 // char (both 16 bits), and in those cases we've made an intentional decision 2064 // to use one kind of load over the other. See AndINode::Ideal and 4965907. 2065 // Also, do not try to narrow the type for a LoadKlass, regardless of offset. 2066 // 2067 // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8)) 2068 // where the _gvn.type of the AddP is wider than 8. This occurs when an earlier 2069 // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been 2070 // subsumed by p1. If p1 is on the worklist but has not yet been re-transformed, 2071 // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any. 2072 // In fact, that could have been the original type of p1, and p1 could have 2073 // had an original form like p1:(AddP x x (LShiftL quux 3)), where the 2074 // expression (LShiftL quux 3) independently optimized to the constant 8. 2075 if ((t->isa_int() == nullptr) && (t->isa_long() == nullptr) 2076 && (_type->isa_vect() == nullptr) 2077 && Opcode() != Op_LoadKlass && Opcode() != Op_LoadNKlass) { 2078 // t might actually be lower than _type, if _type is a unique 2079 // concrete subclass of abstract class t. 2080 if (off_beyond_header || off == Type::OffsetBot) { // is the offset beyond the header? 2081 const Type* jt = t->join_speculative(_type); 2082 // In any case, do not allow the join, per se, to empty out the type. 2083 if (jt->empty() && !t->empty()) { 2084 // This can happen if a interface-typed array narrows to a class type. 2085 jt = _type; 2086 } 2087 #ifdef ASSERT 2088 if (phase->C->eliminate_boxing() && adr->is_AddP()) { 2089 // The pointers in the autobox arrays are always non-null 2090 Node* base = adr->in(AddPNode::Base); 2091 if ((base != nullptr) && base->is_DecodeN()) { 2092 // Get LoadN node which loads IntegerCache.cache field 2093 base = base->in(1); 2094 } 2095 if ((base != nullptr) && base->is_Con()) { 2096 const TypeAryPtr* base_type = base->bottom_type()->isa_aryptr(); 2097 if ((base_type != nullptr) && base_type->is_autobox_cache()) { 2098 // It could be narrow oop 2099 assert(jt->make_ptr()->ptr() == TypePtr::NotNull,"sanity"); 2100 } 2101 } 2102 } 2103 #endif 2104 return jt; 2105 } 2106 } 2107 } else if (tp->base() == Type::InstPtr) { 2108 assert( off != Type::OffsetBot || 2109 // arrays can be cast to Objects 2110 !tp->isa_instptr() || 2111 tp->is_instptr()->instance_klass()->is_java_lang_Object() || 2112 // unsafe field access may not have a constant offset 2113 C->has_unsafe_access(), 2114 "Field accesses must be precise" ); 2115 // For oop loads, we expect the _type to be precise. 2116 2117 // Optimize loads from constant fields. 2118 const TypeInstPtr* tinst = tp->is_instptr(); 2119 ciObject* const_oop = tinst->const_oop(); 2120 if (!is_mismatched_access() && off != Type::OffsetBot && const_oop != nullptr && const_oop->is_instance()) { 2121 const Type* con_type = Type::make_constant_from_field(const_oop->as_instance(), off, is_unsigned(), value_basic_type()); 2122 if (con_type != nullptr) { 2123 return con_type; 2124 } 2125 } 2126 } else if (tp->base() == Type::KlassPtr || tp->base() == Type::InstKlassPtr || tp->base() == Type::AryKlassPtr) { 2127 assert(off != Type::OffsetBot || 2128 !tp->isa_instklassptr() || 2129 // arrays can be cast to Objects 2130 tp->isa_instklassptr()->instance_klass()->is_java_lang_Object() || 2131 // also allow array-loading from the primary supertype 2132 // array during subtype checks 2133 Opcode() == Op_LoadKlass, 2134 "Field accesses must be precise"); 2135 // For klass/static loads, we expect the _type to be precise 2136 } else if (tp->base() == Type::RawPtr && adr->is_Load() && off == 0) { 2137 /* With mirrors being an indirect in the Klass* 2138 * the VM is now using two loads. LoadKlass(LoadP(LoadP(Klass, mirror_offset), zero_offset)) 2139 * The LoadP from the Klass has a RawPtr type (see LibraryCallKit::load_mirror_from_klass). 2140 * 2141 * So check the type and klass of the node before the LoadP. 2142 */ 2143 Node* adr2 = adr->in(MemNode::Address); 2144 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr(); 2145 if (tkls != nullptr && !StressReflectiveCode) { 2146 if (tkls->is_loaded() && tkls->klass_is_exact() && tkls->offset() == in_bytes(Klass::java_mirror_offset())) { 2147 ciKlass* klass = tkls->exact_klass(); 2148 assert(adr->Opcode() == Op_LoadP, "must load an oop from _java_mirror"); 2149 assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror"); 2150 return TypeInstPtr::make(klass->java_mirror()); 2151 } 2152 } 2153 } 2154 2155 const TypeKlassPtr *tkls = tp->isa_klassptr(); 2156 if (tkls != nullptr) { 2157 if (tkls->is_loaded() && tkls->klass_is_exact()) { 2158 ciKlass* klass = tkls->exact_klass(); 2159 // We are loading a field from a Klass metaobject whose identity 2160 // is known at compile time (the type is "exact" or "precise"). 2161 // Check for fields we know are maintained as constants by the VM. 2162 if (tkls->offset() == in_bytes(Klass::super_check_offset_offset())) { 2163 // The field is Klass::_super_check_offset. Return its (constant) value. 2164 // (Folds up type checking code.) 2165 assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset"); 2166 return TypeInt::make(klass->super_check_offset()); 2167 } 2168 // Class encoding in prototype header may change between runs. 2169 // Force loading prototype header when AOT code is generated. 2170 if (UseCompactObjectHeaders && !AOTCodeCache::is_on_for_dump()) { 2171 if (tkls->offset() == in_bytes(Klass::prototype_header_offset())) { 2172 // The field is Klass::_prototype_header. Return its (constant) value. 2173 assert(this->Opcode() == Op_LoadX, "must load a proper type from _prototype_header"); 2174 return TypeX::make(klass->prototype_header()); 2175 } 2176 } 2177 // Compute index into primary_supers array 2178 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*); 2179 // Check for overflowing; use unsigned compare to handle the negative case. 2180 if( depth < ciKlass::primary_super_limit() ) { 2181 // The field is an element of Klass::_primary_supers. Return its (constant) value. 2182 // (Folds up type checking code.) 2183 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers"); 2184 ciKlass *ss = klass->super_of_depth(depth); 2185 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR; 2186 } 2187 const Type* aift = load_array_final_field(tkls, klass); 2188 if (aift != nullptr) return aift; 2189 } 2190 2191 // We can still check if we are loading from the primary_supers array at a 2192 // shallow enough depth. Even though the klass is not exact, entries less 2193 // than or equal to its super depth are correct. 2194 if (tkls->is_loaded()) { 2195 ciKlass* klass = nullptr; 2196 if (tkls->isa_instklassptr()) { 2197 klass = tkls->is_instklassptr()->instance_klass(); 2198 } else { 2199 int dims; 2200 const Type* inner = tkls->is_aryklassptr()->base_element_type(dims); 2201 if (inner->isa_instklassptr()) { 2202 klass = inner->is_instklassptr()->instance_klass(); 2203 klass = ciObjArrayKlass::make(klass, dims); 2204 } 2205 } 2206 if (klass != nullptr) { 2207 // Compute index into primary_supers array 2208 juint depth = (tkls->offset() - in_bytes(Klass::primary_supers_offset())) / sizeof(Klass*); 2209 // Check for overflowing; use unsigned compare to handle the negative case. 2210 if (depth < ciKlass::primary_super_limit() && 2211 depth <= klass->super_depth()) { // allow self-depth checks to handle self-check case 2212 // The field is an element of Klass::_primary_supers. Return its (constant) value. 2213 // (Folds up type checking code.) 2214 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers"); 2215 ciKlass *ss = klass->super_of_depth(depth); 2216 return ss ? TypeKlassPtr::make(ss, Type::trust_interfaces) : TypePtr::NULL_PTR; 2217 } 2218 } 2219 } 2220 2221 // If the type is enough to determine that the thing is not an array, 2222 // we can give the layout_helper a positive interval type. 2223 // This will help short-circuit some reflective code. 2224 if (tkls->offset() == in_bytes(Klass::layout_helper_offset()) && 2225 tkls->isa_instklassptr() && // not directly typed as an array 2226 !tkls->is_instklassptr()->might_be_an_array() // not the supertype of all T[] (java.lang.Object) or has an interface that is not Serializable or Cloneable 2227 ) { 2228 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper"); 2229 jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false); 2230 // The key property of this type is that it folds up tests 2231 // for array-ness, since it proves that the layout_helper is positive. 2232 // Thus, a generic value like the basic object layout helper works fine. 2233 return TypeInt::make(min_size, max_jint, Type::WidenMin); 2234 } 2235 } 2236 2237 bool is_vect = (_type->isa_vect() != nullptr); 2238 if (is_instance && !is_vect) { 2239 // If we have an instance type and our memory input is the 2240 // programs's initial memory state, there is no matching store, 2241 // so just return a zero of the appropriate type - 2242 // except if it is vectorized - then we have no zero constant. 2243 Node *mem = in(MemNode::Memory); 2244 if (mem->is_Parm() && mem->in(0)->is_Start()) { 2245 assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm"); 2246 return Type::get_zero_type(_type->basic_type()); 2247 } 2248 } 2249 2250 if (!UseCompactObjectHeaders) { 2251 Node* alloc = is_new_object_mark_load(); 2252 if (alloc != nullptr) { 2253 return TypeX::make(markWord::prototype().value()); 2254 } 2255 } 2256 2257 return _type; 2258 } 2259 2260 //------------------------------match_edge------------------------------------- 2261 // Do we Match on this edge index or not? Match only the address. 2262 uint LoadNode::match_edge(uint idx) const { 2263 return idx == MemNode::Address; 2264 } 2265 2266 //--------------------------LoadBNode::Ideal-------------------------------------- 2267 // 2268 // If the previous store is to the same address as this load, 2269 // and the value stored was larger than a byte, replace this load 2270 // with the value stored truncated to a byte. If no truncation is 2271 // needed, the replacement is done in LoadNode::Identity(). 2272 // 2273 Node* LoadBNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2274 Node* mem = in(MemNode::Memory); 2275 Node* value = can_see_stored_value(mem,phase); 2276 if (value != nullptr) { 2277 Node* narrow = Compile::narrow_value(T_BYTE, value, _type, phase, false); 2278 if (narrow != value) { 2279 return narrow; 2280 } 2281 } 2282 // Identity call will handle the case where truncation is not needed. 2283 return LoadNode::Ideal(phase, can_reshape); 2284 } 2285 2286 const Type* LoadBNode::Value(PhaseGVN* phase) const { 2287 Node* mem = in(MemNode::Memory); 2288 Node* value = can_see_stored_value(mem,phase); 2289 if (value != nullptr && value->is_Con() && 2290 !value->bottom_type()->higher_equal(_type)) { 2291 // If the input to the store does not fit with the load's result type, 2292 // it must be truncated. We can't delay until Ideal call since 2293 // a singleton Value is needed for split_thru_phi optimization. 2294 int con = value->get_int(); 2295 return TypeInt::make((con << 24) >> 24); 2296 } 2297 return LoadNode::Value(phase); 2298 } 2299 2300 //--------------------------LoadUBNode::Ideal------------------------------------- 2301 // 2302 // If the previous store is to the same address as this load, 2303 // and the value stored was larger than a byte, replace this load 2304 // with the value stored truncated to a byte. If no truncation is 2305 // needed, the replacement is done in LoadNode::Identity(). 2306 // 2307 Node* LoadUBNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2308 Node* mem = in(MemNode::Memory); 2309 Node* value = can_see_stored_value(mem, phase); 2310 if (value != nullptr) { 2311 Node* narrow = Compile::narrow_value(T_BOOLEAN, value, _type, phase, false); 2312 if (narrow != value) { 2313 return narrow; 2314 } 2315 } 2316 // Identity call will handle the case where truncation is not needed. 2317 return LoadNode::Ideal(phase, can_reshape); 2318 } 2319 2320 const Type* LoadUBNode::Value(PhaseGVN* phase) const { 2321 Node* mem = in(MemNode::Memory); 2322 Node* value = can_see_stored_value(mem,phase); 2323 if (value != nullptr && value->is_Con() && 2324 !value->bottom_type()->higher_equal(_type)) { 2325 // If the input to the store does not fit with the load's result type, 2326 // it must be truncated. We can't delay until Ideal call since 2327 // a singleton Value is needed for split_thru_phi optimization. 2328 int con = value->get_int(); 2329 return TypeInt::make(con & 0xFF); 2330 } 2331 return LoadNode::Value(phase); 2332 } 2333 2334 //--------------------------LoadUSNode::Ideal------------------------------------- 2335 // 2336 // If the previous store is to the same address as this load, 2337 // and the value stored was larger than a char, replace this load 2338 // with the value stored truncated to a char. If no truncation is 2339 // needed, the replacement is done in LoadNode::Identity(). 2340 // 2341 Node* LoadUSNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2342 Node* mem = in(MemNode::Memory); 2343 Node* value = can_see_stored_value(mem,phase); 2344 if (value != nullptr) { 2345 Node* narrow = Compile::narrow_value(T_CHAR, value, _type, phase, false); 2346 if (narrow != value) { 2347 return narrow; 2348 } 2349 } 2350 // Identity call will handle the case where truncation is not needed. 2351 return LoadNode::Ideal(phase, can_reshape); 2352 } 2353 2354 const Type* LoadUSNode::Value(PhaseGVN* phase) const { 2355 Node* mem = in(MemNode::Memory); 2356 Node* value = can_see_stored_value(mem,phase); 2357 if (value != nullptr && value->is_Con() && 2358 !value->bottom_type()->higher_equal(_type)) { 2359 // If the input to the store does not fit with the load's result type, 2360 // it must be truncated. We can't delay until Ideal call since 2361 // a singleton Value is needed for split_thru_phi optimization. 2362 int con = value->get_int(); 2363 return TypeInt::make(con & 0xFFFF); 2364 } 2365 return LoadNode::Value(phase); 2366 } 2367 2368 //--------------------------LoadSNode::Ideal-------------------------------------- 2369 // 2370 // If the previous store is to the same address as this load, 2371 // and the value stored was larger than a short, replace this load 2372 // with the value stored truncated to a short. If no truncation is 2373 // needed, the replacement is done in LoadNode::Identity(). 2374 // 2375 Node* LoadSNode::Ideal(PhaseGVN* phase, bool can_reshape) { 2376 Node* mem = in(MemNode::Memory); 2377 Node* value = can_see_stored_value(mem,phase); 2378 if (value != nullptr) { 2379 Node* narrow = Compile::narrow_value(T_SHORT, value, _type, phase, false); 2380 if (narrow != value) { 2381 return narrow; 2382 } 2383 } 2384 // Identity call will handle the case where truncation is not needed. 2385 return LoadNode::Ideal(phase, can_reshape); 2386 } 2387 2388 const Type* LoadSNode::Value(PhaseGVN* phase) const { 2389 Node* mem = in(MemNode::Memory); 2390 Node* value = can_see_stored_value(mem,phase); 2391 if (value != nullptr && value->is_Con() && 2392 !value->bottom_type()->higher_equal(_type)) { 2393 // If the input to the store does not fit with the load's result type, 2394 // it must be truncated. We can't delay until Ideal call since 2395 // a singleton Value is needed for split_thru_phi optimization. 2396 int con = value->get_int(); 2397 return TypeInt::make((con << 16) >> 16); 2398 } 2399 return LoadNode::Value(phase); 2400 } 2401 2402 //============================================================================= 2403 //----------------------------LoadKlassNode::make------------------------------ 2404 // Polymorphic factory method: 2405 Node* LoadKlassNode::make(PhaseGVN& gvn, Node* mem, Node* adr, const TypePtr* at, const TypeKlassPtr* tk) { 2406 // sanity check the alias category against the created node type 2407 const TypePtr* adr_type = adr->bottom_type()->isa_ptr(); 2408 assert(adr_type != nullptr, "expecting TypeKlassPtr"); 2409 #ifdef _LP64 2410 if (adr_type->is_ptr_to_narrowklass()) { 2411 assert(UseCompressedClassPointers, "no compressed klasses"); 2412 Node* load_klass = gvn.transform(new LoadNKlassNode(mem, adr, at, tk->make_narrowklass(), MemNode::unordered)); 2413 return new DecodeNKlassNode(load_klass, load_klass->bottom_type()->make_ptr()); 2414 } 2415 #endif 2416 assert(!adr_type->is_ptr_to_narrowklass() && !adr_type->is_ptr_to_narrowoop(), "should have got back a narrow oop"); 2417 return new LoadKlassNode(mem, adr, at, tk, MemNode::unordered); 2418 } 2419 2420 //------------------------------Value------------------------------------------ 2421 const Type* LoadKlassNode::Value(PhaseGVN* phase) const { 2422 return klass_value_common(phase); 2423 } 2424 2425 const Type* LoadNode::klass_value_common(PhaseGVN* phase) const { 2426 // Either input is TOP ==> the result is TOP 2427 const Type *t1 = phase->type( in(MemNode::Memory) ); 2428 if (t1 == Type::TOP) return Type::TOP; 2429 Node *adr = in(MemNode::Address); 2430 const Type *t2 = phase->type( adr ); 2431 if (t2 == Type::TOP) return Type::TOP; 2432 const TypePtr *tp = t2->is_ptr(); 2433 if (TypePtr::above_centerline(tp->ptr()) || 2434 tp->ptr() == TypePtr::Null) return Type::TOP; 2435 2436 // Return a more precise klass, if possible 2437 const TypeInstPtr *tinst = tp->isa_instptr(); 2438 if (tinst != nullptr) { 2439 ciInstanceKlass* ik = tinst->instance_klass(); 2440 int offset = tinst->offset(); 2441 if (ik == phase->C->env()->Class_klass() 2442 && (offset == java_lang_Class::klass_offset() || 2443 offset == java_lang_Class::array_klass_offset())) { 2444 // We are loading a special hidden field from a Class mirror object, 2445 // the field which points to the VM's Klass metaobject. 2446 ciType* t = tinst->java_mirror_type(); 2447 // java_mirror_type returns non-null for compile-time Class constants. 2448 if (t != nullptr) { 2449 // constant oop => constant klass 2450 if (offset == java_lang_Class::array_klass_offset()) { 2451 if (t->is_void()) { 2452 // We cannot create a void array. Since void is a primitive type return null 2453 // klass. Users of this result need to do a null check on the returned klass. 2454 return TypePtr::NULL_PTR; 2455 } 2456 return TypeKlassPtr::make(ciArrayKlass::make(t), Type::trust_interfaces); 2457 } 2458 if (!t->is_klass()) { 2459 // a primitive Class (e.g., int.class) has null for a klass field 2460 return TypePtr::NULL_PTR; 2461 } 2462 // Fold up the load of the hidden field 2463 return TypeKlassPtr::make(t->as_klass(), Type::trust_interfaces); 2464 } 2465 // non-constant mirror, so we can't tell what's going on 2466 } 2467 if (!tinst->is_loaded()) 2468 return _type; // Bail out if not loaded 2469 if (offset == oopDesc::klass_offset_in_bytes()) { 2470 return tinst->as_klass_type(true); 2471 } 2472 } 2473 2474 // Check for loading klass from an array 2475 const TypeAryPtr *tary = tp->isa_aryptr(); 2476 if (tary != nullptr && 2477 tary->offset() == oopDesc::klass_offset_in_bytes()) { 2478 return tary->as_klass_type(true); 2479 } 2480 2481 // Check for loading klass from an array klass 2482 const TypeKlassPtr *tkls = tp->isa_klassptr(); 2483 if (tkls != nullptr && !StressReflectiveCode) { 2484 if (!tkls->is_loaded()) 2485 return _type; // Bail out if not loaded 2486 if (tkls->isa_aryklassptr() && tkls->is_aryklassptr()->elem()->isa_klassptr() && 2487 tkls->offset() == in_bytes(ObjArrayKlass::element_klass_offset())) { 2488 // // Always returning precise element type is incorrect, 2489 // // e.g., element type could be object and array may contain strings 2490 // return TypeKlassPtr::make(TypePtr::Constant, elem, 0); 2491 2492 // The array's TypeKlassPtr was declared 'precise' or 'not precise' 2493 // according to the element type's subclassing. 2494 return tkls->is_aryklassptr()->elem()->isa_klassptr()->cast_to_exactness(tkls->klass_is_exact()); 2495 } 2496 if (tkls->isa_instklassptr() != nullptr && tkls->klass_is_exact() && 2497 tkls->offset() == in_bytes(Klass::super_offset())) { 2498 ciKlass* sup = tkls->is_instklassptr()->instance_klass()->super(); 2499 // The field is Klass::_super. Return its (constant) value. 2500 // (Folds up the 2nd indirection in aClassConstant.getSuperClass().) 2501 return sup ? TypeKlassPtr::make(sup, Type::trust_interfaces) : TypePtr::NULL_PTR; 2502 } 2503 } 2504 2505 if (tkls != nullptr && !UseSecondarySupersCache 2506 && tkls->offset() == in_bytes(Klass::secondary_super_cache_offset())) { 2507 // Treat Klass::_secondary_super_cache as a constant when the cache is disabled. 2508 return TypePtr::NULL_PTR; 2509 } 2510 2511 // Bailout case 2512 return LoadNode::Value(phase); 2513 } 2514 2515 //------------------------------Identity--------------------------------------- 2516 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k. 2517 // Also feed through the klass in Allocate(...klass...)._klass. 2518 Node* LoadKlassNode::Identity(PhaseGVN* phase) { 2519 return klass_identity_common(phase); 2520 } 2521 2522 Node* LoadNode::klass_identity_common(PhaseGVN* phase) { 2523 Node* x = LoadNode::Identity(phase); 2524 if (x != this) return x; 2525 2526 // Take apart the address into an oop and offset. 2527 // Return 'this' if we cannot. 2528 Node* adr = in(MemNode::Address); 2529 intptr_t offset = 0; 2530 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2531 if (base == nullptr) return this; 2532 const TypeOopPtr* toop = phase->type(adr)->isa_oopptr(); 2533 if (toop == nullptr) return this; 2534 2535 // Step over potential GC barrier for OopHandle resolve 2536 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 2537 if (bs->is_gc_barrier_node(base)) { 2538 base = bs->step_over_gc_barrier(base); 2539 } 2540 2541 // We can fetch the klass directly through an AllocateNode. 2542 // This works even if the klass is not constant (clone or newArray). 2543 if (offset == oopDesc::klass_offset_in_bytes()) { 2544 Node* allocated_klass = AllocateNode::Ideal_klass(base, phase); 2545 if (allocated_klass != nullptr) { 2546 return allocated_klass; 2547 } 2548 } 2549 2550 // Simplify k.java_mirror.as_klass to plain k, where k is a Klass*. 2551 // See inline_native_Class_query for occurrences of these patterns. 2552 // Java Example: x.getClass().isAssignableFrom(y) 2553 // 2554 // This improves reflective code, often making the Class 2555 // mirror go completely dead. (Current exception: Class 2556 // mirrors may appear in debug info, but we could clean them out by 2557 // introducing a new debug info operator for Klass.java_mirror). 2558 2559 if (toop->isa_instptr() && toop->is_instptr()->instance_klass() == phase->C->env()->Class_klass() 2560 && offset == java_lang_Class::klass_offset()) { 2561 if (base->is_Load()) { 2562 Node* base2 = base->in(MemNode::Address); 2563 if (base2->is_Load()) { /* direct load of a load which is the OopHandle */ 2564 Node* adr2 = base2->in(MemNode::Address); 2565 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr(); 2566 if (tkls != nullptr && !tkls->empty() 2567 && (tkls->isa_instklassptr() || tkls->isa_aryklassptr()) 2568 && adr2->is_AddP() 2569 ) { 2570 int mirror_field = in_bytes(Klass::java_mirror_offset()); 2571 if (tkls->offset() == mirror_field) { 2572 return adr2->in(AddPNode::Base); 2573 } 2574 } 2575 } 2576 } 2577 } 2578 2579 return this; 2580 } 2581 2582 LoadNode* LoadNode::clone_pinned() const { 2583 LoadNode* ld = clone()->as_Load(); 2584 ld->_control_dependency = UnknownControl; 2585 return ld; 2586 } 2587 2588 2589 //------------------------------Value------------------------------------------ 2590 const Type* LoadNKlassNode::Value(PhaseGVN* phase) const { 2591 const Type *t = klass_value_common(phase); 2592 if (t == Type::TOP) 2593 return t; 2594 2595 return t->make_narrowklass(); 2596 } 2597 2598 //------------------------------Identity--------------------------------------- 2599 // To clean up reflective code, simplify k.java_mirror.as_klass to narrow k. 2600 // Also feed through the klass in Allocate(...klass...)._klass. 2601 Node* LoadNKlassNode::Identity(PhaseGVN* phase) { 2602 Node *x = klass_identity_common(phase); 2603 2604 const Type *t = phase->type( x ); 2605 if( t == Type::TOP ) return x; 2606 if( t->isa_narrowklass()) return x; 2607 assert (!t->isa_narrowoop(), "no narrow oop here"); 2608 2609 return phase->transform(new EncodePKlassNode(x, t->make_narrowklass())); 2610 } 2611 2612 //------------------------------Value----------------------------------------- 2613 const Type* LoadRangeNode::Value(PhaseGVN* phase) const { 2614 // Either input is TOP ==> the result is TOP 2615 const Type *t1 = phase->type( in(MemNode::Memory) ); 2616 if( t1 == Type::TOP ) return Type::TOP; 2617 Node *adr = in(MemNode::Address); 2618 const Type *t2 = phase->type( adr ); 2619 if( t2 == Type::TOP ) return Type::TOP; 2620 const TypePtr *tp = t2->is_ptr(); 2621 if (TypePtr::above_centerline(tp->ptr())) return Type::TOP; 2622 const TypeAryPtr *tap = tp->isa_aryptr(); 2623 if( !tap ) return _type; 2624 return tap->size(); 2625 } 2626 2627 //-------------------------------Ideal--------------------------------------- 2628 // Feed through the length in AllocateArray(...length...)._length. 2629 Node *LoadRangeNode::Ideal(PhaseGVN *phase, bool can_reshape) { 2630 Node* p = MemNode::Ideal_common(phase, can_reshape); 2631 if (p) return (p == NodeSentinel) ? nullptr : p; 2632 2633 // Take apart the address into an oop and offset. 2634 // Return 'this' if we cannot. 2635 Node* adr = in(MemNode::Address); 2636 intptr_t offset = 0; 2637 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2638 if (base == nullptr) return nullptr; 2639 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr(); 2640 if (tary == nullptr) return nullptr; 2641 2642 // We can fetch the length directly through an AllocateArrayNode. 2643 // This works even if the length is not constant (clone or newArray). 2644 if (offset == arrayOopDesc::length_offset_in_bytes()) { 2645 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base); 2646 if (alloc != nullptr) { 2647 Node* allocated_length = alloc->Ideal_length(); 2648 Node* len = alloc->make_ideal_length(tary, phase); 2649 if (allocated_length != len) { 2650 // New CastII improves on this. 2651 return len; 2652 } 2653 } 2654 } 2655 2656 return nullptr; 2657 } 2658 2659 //------------------------------Identity--------------------------------------- 2660 // Feed through the length in AllocateArray(...length...)._length. 2661 Node* LoadRangeNode::Identity(PhaseGVN* phase) { 2662 Node* x = LoadINode::Identity(phase); 2663 if (x != this) return x; 2664 2665 // Take apart the address into an oop and offset. 2666 // Return 'this' if we cannot. 2667 Node* adr = in(MemNode::Address); 2668 intptr_t offset = 0; 2669 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset); 2670 if (base == nullptr) return this; 2671 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr(); 2672 if (tary == nullptr) return this; 2673 2674 // We can fetch the length directly through an AllocateArrayNode. 2675 // This works even if the length is not constant (clone or newArray). 2676 if (offset == arrayOopDesc::length_offset_in_bytes()) { 2677 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(base); 2678 if (alloc != nullptr) { 2679 Node* allocated_length = alloc->Ideal_length(); 2680 // Do not allow make_ideal_length to allocate a CastII node. 2681 Node* len = alloc->make_ideal_length(tary, phase, false); 2682 if (allocated_length == len) { 2683 // Return allocated_length only if it would not be improved by a CastII. 2684 return allocated_length; 2685 } 2686 } 2687 } 2688 2689 return this; 2690 2691 } 2692 2693 //============================================================================= 2694 //---------------------------StoreNode::make----------------------------------- 2695 // Polymorphic factory method: 2696 StoreNode* StoreNode::make(PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt, MemOrd mo, bool require_atomic_access) { 2697 assert((mo == unordered || mo == release), "unexpected"); 2698 Compile* C = gvn.C; 2699 assert(C->get_alias_index(adr_type) != Compile::AliasIdxRaw || 2700 ctl != nullptr, "raw memory operations should have control edge"); 2701 2702 switch (bt) { 2703 case T_BOOLEAN: val = gvn.transform(new AndINode(val, gvn.intcon(0x1))); // Fall through to T_BYTE case 2704 case T_BYTE: return new StoreBNode(ctl, mem, adr, adr_type, val, mo); 2705 case T_INT: return new StoreINode(ctl, mem, adr, adr_type, val, mo); 2706 case T_CHAR: 2707 case T_SHORT: return new StoreCNode(ctl, mem, adr, adr_type, val, mo); 2708 case T_LONG: return new StoreLNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); 2709 case T_FLOAT: return new StoreFNode(ctl, mem, adr, adr_type, val, mo); 2710 case T_DOUBLE: return new StoreDNode(ctl, mem, adr, adr_type, val, mo, require_atomic_access); 2711 case T_METADATA: 2712 case T_ADDRESS: 2713 case T_OBJECT: 2714 #ifdef _LP64 2715 if (adr->bottom_type()->is_ptr_to_narrowoop()) { 2716 val = gvn.transform(new EncodePNode(val, val->bottom_type()->make_narrowoop())); 2717 return new StoreNNode(ctl, mem, adr, adr_type, val, mo); 2718 } else if (adr->bottom_type()->is_ptr_to_narrowklass() || 2719 (UseCompressedClassPointers && val->bottom_type()->isa_klassptr() && 2720 adr->bottom_type()->isa_rawptr())) { 2721 val = gvn.transform(new EncodePKlassNode(val, val->bottom_type()->make_narrowklass())); 2722 return new StoreNKlassNode(ctl, mem, adr, adr_type, val, mo); 2723 } 2724 #endif 2725 { 2726 return new StorePNode(ctl, mem, adr, adr_type, val, mo); 2727 } 2728 default: 2729 ShouldNotReachHere(); 2730 return (StoreNode*)nullptr; 2731 } 2732 } 2733 2734 //--------------------------bottom_type---------------------------------------- 2735 const Type *StoreNode::bottom_type() const { 2736 return Type::MEMORY; 2737 } 2738 2739 //------------------------------hash------------------------------------------- 2740 uint StoreNode::hash() const { 2741 // unroll addition of interesting fields 2742 //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn); 2743 2744 // Since they are not commoned, do not hash them: 2745 return NO_HASH; 2746 } 2747 2748 // Link together multiple stores (B/S/C/I) into a longer one. 2749 // 2750 // Example: _store = StoreB[i+3] 2751 // 2752 // RangeCheck[i+0] RangeCheck[i+0] 2753 // StoreB[i+0] 2754 // RangeCheck[i+3] RangeCheck[i+3] 2755 // StoreB[i+1] --> pass: fail: 2756 // StoreB[i+2] StoreI[i+0] StoreB[i+0] 2757 // StoreB[i+3] 2758 // 2759 // The 4 StoreB are merged into a single StoreI node. We have to be careful with RangeCheck[i+1]: before 2760 // the optimization, if this RangeCheck[i+1] fails, then we execute only StoreB[i+0], and then trap. After 2761 // the optimization, the new StoreI[i+0] is on the passing path of RangeCheck[i+3], and StoreB[i+0] on the 2762 // failing path. 2763 // 2764 // Note: For normal array stores, every store at first has a RangeCheck. But they can be removed with: 2765 // - RCE (RangeCheck Elimination): the RangeChecks in the loop are hoisted out and before the loop, 2766 // and possibly no RangeChecks remain between the stores. 2767 // - RangeCheck smearing: the earlier RangeChecks are adjusted such that they cover later RangeChecks, 2768 // and those later RangeChecks can be removed. Example: 2769 // 2770 // RangeCheck[i+0] RangeCheck[i+0] <- before first store 2771 // StoreB[i+0] StoreB[i+0] <- first store 2772 // RangeCheck[i+1] --> smeared --> RangeCheck[i+3] <- only RC between first and last store 2773 // StoreB[i+1] StoreB[i+1] <- second store 2774 // RangeCheck[i+2] --> removed 2775 // StoreB[i+2] StoreB[i+2] 2776 // RangeCheck[i+3] --> removed 2777 // StoreB[i+3] StoreB[i+3] <- last store 2778 // 2779 // Thus, it is a common pattern that between the first and last store in a chain 2780 // of adjacent stores there remains exactly one RangeCheck, located between the 2781 // first and the second store (e.g. RangeCheck[i+3]). 2782 // 2783 class MergePrimitiveStores : public StackObj { 2784 private: 2785 PhaseGVN* const _phase; 2786 StoreNode* const _store; 2787 // State machine with initial state Unknown 2788 // Allowed transitions: 2789 // Unknown -> Const 2790 // Unknown -> Platform 2791 // Unknown -> Reverse 2792 // Unknown -> NotAdjacent 2793 // Const -> Const 2794 // Const -> NotAdjacent 2795 // Platform -> Platform 2796 // Platform -> NotAdjacent 2797 // Reverse -> Reverse 2798 // Reverse -> NotAdjacent 2799 // NotAdjacent -> NotAdjacent 2800 enum ValueOrder : uint8_t { 2801 Unknown, // Initial state 2802 Const, // Input values are const 2803 Platform, // Platform order 2804 Reverse, // Reverse platform order 2805 NotAdjacent // Not adjacent 2806 }; 2807 ValueOrder _value_order; 2808 2809 NOT_PRODUCT( const CHeapBitMap &_trace_tags; ) 2810 2811 public: 2812 MergePrimitiveStores(PhaseGVN* phase, StoreNode* store) : 2813 _phase(phase), _store(store), _value_order(ValueOrder::Unknown) 2814 NOT_PRODUCT( COMMA _trace_tags(Compile::current()->directive()->trace_merge_stores_tags()) ) 2815 {} 2816 2817 StoreNode* run(); 2818 2819 private: 2820 bool is_compatible_store(const StoreNode* other_store) const; 2821 bool is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const; 2822 bool is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const; 2823 static bool is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out, PhaseGVN* phase); 2824 enum CFGStatus { SuccessNoRangeCheck, SuccessWithRangeCheck, Failure }; 2825 static CFGStatus cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store); 2826 2827 class Status { 2828 private: 2829 StoreNode* _found_store; 2830 bool _found_range_check; 2831 2832 Status(StoreNode* found_store, bool found_range_check) 2833 : _found_store(found_store), _found_range_check(found_range_check) {} 2834 2835 public: 2836 StoreNode* found_store() const { return _found_store; } 2837 bool found_range_check() const { return _found_range_check; } 2838 static Status make_failure() { return Status(nullptr, false); } 2839 2840 static Status make(StoreNode* found_store, const CFGStatus cfg_status) { 2841 if (cfg_status == CFGStatus::Failure) { 2842 return Status::make_failure(); 2843 } 2844 return Status(found_store, cfg_status == CFGStatus::SuccessWithRangeCheck); 2845 } 2846 2847 #ifndef PRODUCT 2848 void print_on(outputStream* st) const { 2849 if (_found_store == nullptr) { 2850 st->print_cr("None"); 2851 } else { 2852 st->print_cr("Found[%d %s, %s]", _found_store->_idx, _found_store->Name(), 2853 _found_range_check ? "RC" : "no-RC"); 2854 } 2855 } 2856 #endif 2857 }; 2858 2859 enum ValueOrder find_adjacent_input_value_order(const Node* n1, const Node* n2, const int memory_size) const; 2860 Status find_adjacent_use_store(const StoreNode* def_store) const; 2861 Status find_adjacent_def_store(const StoreNode* use_store) const; 2862 Status find_use_store(const StoreNode* def_store) const; 2863 Status find_def_store(const StoreNode* use_store) const; 2864 Status find_use_store_unidirectional(const StoreNode* def_store) const; 2865 Status find_def_store_unidirectional(const StoreNode* use_store) const; 2866 2867 void collect_merge_list(Node_List& merge_list) const; 2868 Node* make_merged_input_value(const Node_List& merge_list); 2869 StoreNode* make_merged_store(const Node_List& merge_list, Node* merged_input_value); 2870 2871 #ifndef PRODUCT 2872 // Access to TraceMergeStores tags 2873 bool is_trace(TraceMergeStores::Tag tag) const { 2874 return _trace_tags.at(tag); 2875 } 2876 2877 bool is_trace_basic() const { 2878 return is_trace(TraceMergeStores::Tag::BASIC); 2879 } 2880 2881 bool is_trace_pointer_parsing() const { 2882 return is_trace(TraceMergeStores::Tag::POINTER_PARSING); 2883 } 2884 2885 bool is_trace_pointer_aliasing() const { 2886 return is_trace(TraceMergeStores::Tag::POINTER_ALIASING); 2887 } 2888 2889 bool is_trace_pointer_adjacency() const { 2890 return is_trace(TraceMergeStores::Tag::POINTER_ADJACENCY); 2891 } 2892 2893 bool is_trace_success() const { 2894 return is_trace(TraceMergeStores::Tag::SUCCESS); 2895 } 2896 #endif 2897 2898 NOT_PRODUCT( void trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const; ) 2899 }; 2900 2901 StoreNode* MergePrimitiveStores::run() { 2902 // Check for B/S/C/I 2903 int opc = _store->Opcode(); 2904 if (opc != Op_StoreB && opc != Op_StoreC && opc != Op_StoreI) { 2905 return nullptr; 2906 } 2907 2908 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] MergePrimitiveStores::run: "); _store->dump(); }) 2909 2910 // The _store must be the "last" store in a chain. If we find a use we could merge with 2911 // then that use or a store further down is the "last" store. 2912 Status status_use = find_adjacent_use_store(_store); 2913 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect no use: "); status_use.print_on(tty); }) 2914 if (status_use.found_store() != nullptr) { 2915 return nullptr; 2916 } 2917 2918 // Check if we can merge with at least one def, so that we have at least 2 stores to merge. 2919 Status status_def = find_adjacent_def_store(_store); 2920 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] expect def: "); status_def.print_on(tty); }) 2921 Node* def_store = status_def.found_store(); 2922 if (def_store == nullptr) { 2923 return nullptr; 2924 } 2925 2926 // Initialize value order 2927 _value_order = find_adjacent_input_value_order(def_store->in(MemNode::ValueIn), 2928 _store->in(MemNode::ValueIn), 2929 _store->memory_size()); 2930 assert(_value_order != ValueOrder::NotAdjacent && _value_order != ValueOrder::Unknown, "Order should be checked"); 2931 2932 ResourceMark rm; 2933 Node_List merge_list; 2934 collect_merge_list(merge_list); 2935 2936 Node* merged_input_value = make_merged_input_value(merge_list); 2937 if (merged_input_value == nullptr) { return nullptr; } 2938 2939 StoreNode* merged_store = make_merged_store(merge_list, merged_input_value); 2940 2941 NOT_PRODUCT( if (is_trace_success()) { trace(merge_list, merged_input_value, merged_store); } ) 2942 2943 return merged_store; 2944 } 2945 2946 // Check compatibility between _store and other_store. 2947 bool MergePrimitiveStores::is_compatible_store(const StoreNode* other_store) const { 2948 int opc = _store->Opcode(); 2949 assert(opc == Op_StoreB || opc == Op_StoreC || opc == Op_StoreI, "precondition"); 2950 2951 if (other_store == nullptr || 2952 _store->Opcode() != other_store->Opcode()) { 2953 return false; 2954 } 2955 2956 return true; 2957 } 2958 2959 bool MergePrimitiveStores::is_adjacent_pair(const StoreNode* use_store, const StoreNode* def_store) const { 2960 if (!is_adjacent_input_pair(def_store->in(MemNode::ValueIn), 2961 use_store->in(MemNode::ValueIn), 2962 def_store->memory_size())) { 2963 return false; 2964 } 2965 2966 ResourceMark rm; 2967 #ifndef PRODUCT 2968 const TraceMemPointer trace(is_trace_pointer_parsing(), 2969 is_trace_pointer_aliasing(), 2970 is_trace_pointer_adjacency(), 2971 true); 2972 #endif 2973 const MemPointer pointer_use(use_store NOT_PRODUCT(COMMA trace)); 2974 const MemPointer pointer_def(def_store NOT_PRODUCT(COMMA trace)); 2975 return pointer_def.is_adjacent_to_and_before(pointer_use); 2976 } 2977 2978 // Check input values n1 and n2 can be merged and return the value order 2979 MergePrimitiveStores::ValueOrder MergePrimitiveStores::find_adjacent_input_value_order(const Node* n1, const Node* n2, 2980 const int memory_size) const { 2981 // Pattern: [n1 = ConI, n2 = ConI] 2982 if (n1->Opcode() == Op_ConI && n2->Opcode() == Op_ConI) { 2983 return ValueOrder::Const; 2984 } 2985 2986 Node const *base_n2; 2987 jint shift_n2; 2988 if (!is_con_RShift(n2, base_n2, shift_n2, _phase)) { 2989 return ValueOrder::NotAdjacent; 2990 } 2991 Node const *base_n1; 2992 jint shift_n1; 2993 if (!is_con_RShift(n1, base_n1, shift_n1, _phase)) { 2994 return ValueOrder::NotAdjacent; 2995 } 2996 2997 int bits_per_store = memory_size * 8; 2998 if (base_n1 != base_n2 || 2999 abs(shift_n1 - shift_n2) != bits_per_store || 3000 shift_n1 % bits_per_store != 0) { 3001 // Values are not adjacent 3002 return ValueOrder::NotAdjacent; 3003 } 3004 3005 // Detect value order 3006 #ifdef VM_LITTLE_ENDIAN 3007 return shift_n1 < shift_n2 ? ValueOrder::Platform // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)] 3008 : ValueOrder::Reverse; // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift] 3009 #else 3010 return shift_n1 > shift_n2 ? ValueOrder::Platform // Pattern: [n1 = base >> (shift + memory_size), n2 = base >> shift] 3011 : ValueOrder::Reverse; // Pattern: [n1 = base >> shift, n2 = base >> (shift + memory_size)] 3012 #endif 3013 } 3014 3015 bool MergePrimitiveStores::is_adjacent_input_pair(const Node* n1, const Node* n2, const int memory_size) const { 3016 ValueOrder input_value_order = find_adjacent_input_value_order(n1, n2, memory_size); 3017 3018 switch (input_value_order) { 3019 case ValueOrder::NotAdjacent: 3020 return false; 3021 case ValueOrder::Reverse: 3022 if (memory_size != 1 || 3023 !Matcher::match_rule_supported(Op_ReverseBytesS) || 3024 !Matcher::match_rule_supported(Op_ReverseBytesI) || 3025 !Matcher::match_rule_supported(Op_ReverseBytesL)) { 3026 // ReverseBytes are not supported by platform 3027 return false; 3028 } 3029 // fall-through. 3030 case ValueOrder::Const: 3031 case ValueOrder::Platform: 3032 if (_value_order == ValueOrder::Unknown) { 3033 // Initial state is Unknown, and we find a valid input value order 3034 return true; 3035 } 3036 // The value order can not be changed 3037 return _value_order == input_value_order; 3038 case ValueOrder::Unknown: 3039 default: 3040 ShouldNotReachHere(); 3041 } 3042 return false; 3043 } 3044 3045 // Detect pattern: n = base_out >> shift_out 3046 bool MergePrimitiveStores::is_con_RShift(const Node* n, Node const*& base_out, jint& shift_out, PhaseGVN* phase) { 3047 assert(n != nullptr, "precondition"); 3048 3049 int opc = n->Opcode(); 3050 if (opc == Op_ConvL2I) { 3051 n = n->in(1); 3052 opc = n->Opcode(); 3053 } 3054 3055 if ((opc == Op_RShiftI || 3056 opc == Op_RShiftL || 3057 opc == Op_URShiftI || 3058 opc == Op_URShiftL) && 3059 n->in(2)->is_ConI()) { 3060 base_out = n->in(1); 3061 shift_out = n->in(2)->get_int(); 3062 // The shift must be positive: 3063 return shift_out >= 0; 3064 } 3065 3066 if (phase->type(n)->isa_int() != nullptr || 3067 phase->type(n)->isa_long() != nullptr) { 3068 // (base >> 0) 3069 base_out = n; 3070 shift_out = 0; 3071 return true; 3072 } 3073 return false; 3074 } 3075 3076 // Check if there is nothing between the two stores, except optionally a RangeCheck leading to an uncommon trap. 3077 MergePrimitiveStores::CFGStatus MergePrimitiveStores::cfg_status_for_pair(const StoreNode* use_store, const StoreNode* def_store) { 3078 assert(use_store->in(MemNode::Memory) == def_store, "use-def relationship"); 3079 3080 Node* ctrl_use = use_store->in(MemNode::Control); 3081 Node* ctrl_def = def_store->in(MemNode::Control); 3082 if (ctrl_use == nullptr || ctrl_def == nullptr) { 3083 return CFGStatus::Failure; 3084 } 3085 3086 if (ctrl_use == ctrl_def) { 3087 // Same ctrl -> no RangeCheck in between. 3088 // Check: use_store must be the only use of def_store. 3089 if (def_store->outcnt() > 1) { 3090 return CFGStatus::Failure; 3091 } 3092 return CFGStatus::SuccessNoRangeCheck; 3093 } 3094 3095 // Different ctrl -> could have RangeCheck in between. 3096 // Check: 1. def_store only has these uses: use_store and MergeMem for uncommon trap, and 3097 // 2. ctrl separated by RangeCheck. 3098 if (def_store->outcnt() != 2) { 3099 return CFGStatus::Failure; // Cannot have exactly these uses: use_store and MergeMem for uncommon trap. 3100 } 3101 int use_store_out_idx = def_store->raw_out(0) == use_store ? 0 : 1; 3102 Node* merge_mem = def_store->raw_out(1 - use_store_out_idx)->isa_MergeMem(); 3103 if (merge_mem == nullptr || 3104 merge_mem->outcnt() != 1) { 3105 return CFGStatus::Failure; // Does not have MergeMem for uncommon trap. 3106 } 3107 if (!ctrl_use->is_IfProj() || 3108 !ctrl_use->in(0)->is_RangeCheck() || 3109 ctrl_use->in(0)->outcnt() != 2) { 3110 return CFGStatus::Failure; // Not RangeCheck. 3111 } 3112 ProjNode* other_proj = ctrl_use->as_IfProj()->other_if_proj(); 3113 Node* trap = other_proj->is_uncommon_trap_proj(Deoptimization::Reason_range_check); 3114 if (trap != merge_mem->unique_out() || 3115 ctrl_use->in(0)->in(0) != ctrl_def) { 3116 return CFGStatus::Failure; // Not RangeCheck with merge_mem leading to uncommon trap. 3117 } 3118 3119 return CFGStatus::SuccessWithRangeCheck; 3120 } 3121 3122 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_use_store(const StoreNode* def_store) const { 3123 Status status_use = find_use_store(def_store); 3124 StoreNode* use_store = status_use.found_store(); 3125 if (use_store != nullptr && !is_adjacent_pair(use_store, def_store)) { 3126 return Status::make_failure(); 3127 } 3128 return status_use; 3129 } 3130 3131 MergePrimitiveStores::Status MergePrimitiveStores::find_adjacent_def_store(const StoreNode* use_store) const { 3132 Status status_def = find_def_store(use_store); 3133 StoreNode* def_store = status_def.found_store(); 3134 if (def_store != nullptr && !is_adjacent_pair(use_store, def_store)) { 3135 return Status::make_failure(); 3136 } 3137 return status_def; 3138 } 3139 3140 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store(const StoreNode* def_store) const { 3141 Status status_use = find_use_store_unidirectional(def_store); 3142 3143 #ifdef ASSERT 3144 StoreNode* use_store = status_use.found_store(); 3145 if (use_store != nullptr) { 3146 Status status_def = find_def_store_unidirectional(use_store); 3147 assert(status_def.found_store() == def_store && 3148 status_def.found_range_check() == status_use.found_range_check(), 3149 "find_use_store and find_def_store must be symmetric"); 3150 } 3151 #endif 3152 3153 return status_use; 3154 } 3155 3156 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store(const StoreNode* use_store) const { 3157 Status status_def = find_def_store_unidirectional(use_store); 3158 3159 #ifdef ASSERT 3160 StoreNode* def_store = status_def.found_store(); 3161 if (def_store != nullptr) { 3162 Status status_use = find_use_store_unidirectional(def_store); 3163 assert(status_use.found_store() == use_store && 3164 status_use.found_range_check() == status_def.found_range_check(), 3165 "find_use_store and find_def_store must be symmetric"); 3166 } 3167 #endif 3168 3169 return status_def; 3170 } 3171 3172 MergePrimitiveStores::Status MergePrimitiveStores::find_use_store_unidirectional(const StoreNode* def_store) const { 3173 assert(is_compatible_store(def_store), "precondition: must be compatible with _store"); 3174 3175 for (DUIterator_Fast imax, i = def_store->fast_outs(imax); i < imax; i++) { 3176 StoreNode* use_store = def_store->fast_out(i)->isa_Store(); 3177 if (is_compatible_store(use_store)) { 3178 return Status::make(use_store, cfg_status_for_pair(use_store, def_store)); 3179 } 3180 } 3181 3182 return Status::make_failure(); 3183 } 3184 3185 MergePrimitiveStores::Status MergePrimitiveStores::find_def_store_unidirectional(const StoreNode* use_store) const { 3186 assert(is_compatible_store(use_store), "precondition: must be compatible with _store"); 3187 3188 StoreNode* def_store = use_store->in(MemNode::Memory)->isa_Store(); 3189 if (!is_compatible_store(def_store)) { 3190 return Status::make_failure(); 3191 } 3192 3193 return Status::make(def_store, cfg_status_for_pair(use_store, def_store)); 3194 } 3195 3196 void MergePrimitiveStores::collect_merge_list(Node_List& merge_list) const { 3197 // The merged store can be at most 8 bytes. 3198 const uint merge_list_max_size = 8 / _store->memory_size(); 3199 assert(merge_list_max_size >= 2 && 3200 merge_list_max_size <= 8 && 3201 is_power_of_2(merge_list_max_size), 3202 "must be 2, 4 or 8"); 3203 3204 // Traverse up the chain of adjacent def stores. 3205 StoreNode* current = _store; 3206 merge_list.push(current); 3207 while (current != nullptr && merge_list.size() < merge_list_max_size) { 3208 Status status = find_adjacent_def_store(current); 3209 NOT_PRODUCT( if (is_trace_basic()) { tty->print("[TraceMergeStores] find def: "); status.print_on(tty); }) 3210 3211 current = status.found_store(); 3212 if (current != nullptr) { 3213 merge_list.push(current); 3214 3215 // We can have at most one RangeCheck. 3216 if (status.found_range_check()) { 3217 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found RangeCheck, stop traversal."); }) 3218 break; 3219 } 3220 } 3221 } 3222 3223 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] found:"); merge_list.dump(); }) 3224 3225 // Truncate the merge_list to a power of 2. 3226 const uint pow2size = round_down_power_of_2(merge_list.size()); 3227 assert(pow2size >= 2, "must be merging at least 2 stores"); 3228 while (merge_list.size() > pow2size) { merge_list.pop(); } 3229 3230 NOT_PRODUCT( if (is_trace_basic()) { tty->print_cr("[TraceMergeStores] truncated:"); merge_list.dump(); }) 3231 } 3232 3233 // Merge the input values of the smaller stores to a single larger input value. 3234 Node* MergePrimitiveStores::make_merged_input_value(const Node_List& merge_list) { 3235 int new_memory_size = _store->memory_size() * merge_list.size(); 3236 Node* first = merge_list.at(merge_list.size()-1); 3237 Node* merged_input_value = nullptr; 3238 if (_store->in(MemNode::ValueIn)->Opcode() == Op_ConI) { 3239 assert(_value_order == ValueOrder::Const, "must match"); 3240 // Pattern: [ConI, ConI, ...] -> new constant 3241 jlong con = 0; 3242 jlong bits_per_store = _store->memory_size() * 8; 3243 jlong mask = (((jlong)1) << bits_per_store) - 1; 3244 for (uint i = 0; i < merge_list.size(); i++) { 3245 jlong con_i = merge_list.at(i)->in(MemNode::ValueIn)->get_int(); 3246 #ifdef VM_LITTLE_ENDIAN 3247 con = con << bits_per_store; 3248 con = con | (mask & con_i); 3249 #else // VM_LITTLE_ENDIAN 3250 con_i = (mask & con_i) << (i * bits_per_store); 3251 con = con | con_i; 3252 #endif // VM_LITTLE_ENDIAN 3253 } 3254 merged_input_value = _phase->longcon(con); 3255 } else { 3256 assert(_value_order == ValueOrder::Platform || _value_order == ValueOrder::Reverse, "must match"); 3257 // Pattern: [base >> 24, base >> 16, base >> 8, base] -> base 3258 // | | 3259 // _store first 3260 // 3261 Node* hi = _store->in(MemNode::ValueIn); 3262 Node* lo = first->in(MemNode::ValueIn); 3263 #ifndef VM_LITTLE_ENDIAN 3264 // `_store` and `first` are swapped in the diagram above 3265 swap(hi, lo); 3266 #endif // !VM_LITTLE_ENDIAN 3267 if (_value_order == ValueOrder::Reverse) { 3268 swap(hi, lo); 3269 } 3270 Node const* hi_base; 3271 jint hi_shift; 3272 merged_input_value = lo; 3273 bool is_true = is_con_RShift(hi, hi_base, hi_shift, _phase); 3274 assert(is_true, "must detect con RShift"); 3275 if (merged_input_value != hi_base && merged_input_value->Opcode() == Op_ConvL2I) { 3276 // look through 3277 merged_input_value = merged_input_value->in(1); 3278 } 3279 if (merged_input_value != hi_base) { 3280 // merged_input_value is not the base 3281 return nullptr; 3282 } 3283 } 3284 3285 if (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size <= 4) { 3286 // Example: 3287 // 3288 // long base = ...; 3289 // a[0] = (byte)(base >> 0); 3290 // a[1] = (byte)(base >> 8); 3291 // 3292 merged_input_value = _phase->transform(new ConvL2INode(merged_input_value)); 3293 } 3294 3295 assert((_phase->type(merged_input_value)->isa_int() != nullptr && new_memory_size <= 4) || 3296 (_phase->type(merged_input_value)->isa_long() != nullptr && new_memory_size == 8), 3297 "merged_input_value is either int or long, and new_memory_size is small enough"); 3298 3299 if (_value_order == ValueOrder::Reverse) { 3300 assert(_store->memory_size() == 1, "only implemented for bytes"); 3301 if (new_memory_size == 8) { 3302 merged_input_value = _phase->transform(new ReverseBytesLNode(merged_input_value)); 3303 } else if (new_memory_size == 4) { 3304 merged_input_value = _phase->transform(new ReverseBytesINode(merged_input_value)); 3305 } else { 3306 assert(new_memory_size == 2, "sanity check"); 3307 merged_input_value = _phase->transform(new ReverseBytesSNode(merged_input_value)); 3308 } 3309 } 3310 return merged_input_value; 3311 } 3312 3313 // // 3314 // first_ctrl first_mem first_adr first_ctrl first_mem first_adr // 3315 // | | | | | | // 3316 // | | | | +---------------+ | // 3317 // | | | | | | | // 3318 // | | +---------+ | | +---------------+ // 3319 // | | | | | | | | // 3320 // +--------------+ | | v1 +------------------------------+ | | v1 // 3321 // | | | | | | | | | | | | // 3322 // RangeCheck first_store RangeCheck | | first_store // 3323 // | | | | | | | // 3324 // last_ctrl | +----> unc_trap last_ctrl | | +----> unc_trap // 3325 // | | ===> | | | // 3326 // +--------------+ | a2 v2 | | | // 3327 // | | | | | | | | // 3328 // | second_store | | | // 3329 // | | | | | [v1 v2 ... vn] // 3330 // ... ... | | | | // 3331 // | | | | | v // 3332 // +--------------+ | an vn +--------------+ | | merged_input_value // 3333 // | | | | | | | | // 3334 // last_store (= _store) merged_store // 3335 // // 3336 StoreNode* MergePrimitiveStores::make_merged_store(const Node_List& merge_list, Node* merged_input_value) { 3337 Node* first_store = merge_list.at(merge_list.size()-1); 3338 Node* last_ctrl = _store->in(MemNode::Control); // after (optional) RangeCheck 3339 Node* first_mem = first_store->in(MemNode::Memory); 3340 Node* first_adr = first_store->in(MemNode::Address); 3341 3342 const TypePtr* new_adr_type = _store->adr_type(); 3343 3344 int new_memory_size = _store->memory_size() * merge_list.size(); 3345 BasicType bt = T_ILLEGAL; 3346 switch (new_memory_size) { 3347 case 2: bt = T_SHORT; break; 3348 case 4: bt = T_INT; break; 3349 case 8: bt = T_LONG; break; 3350 } 3351 3352 StoreNode* merged_store = StoreNode::make(*_phase, last_ctrl, first_mem, first_adr, 3353 new_adr_type, merged_input_value, bt, MemNode::unordered); 3354 3355 // Marking the store mismatched is sufficient to prevent reordering, since array stores 3356 // are all on the same slice. Hence, we need no barriers. 3357 merged_store->set_mismatched_access(); 3358 3359 // Constants above may now also be be packed -> put candidate on worklist 3360 _phase->is_IterGVN()->_worklist.push(first_mem); 3361 3362 return merged_store; 3363 } 3364 3365 #ifndef PRODUCT 3366 void MergePrimitiveStores::trace(const Node_List& merge_list, const Node* merged_input_value, const StoreNode* merged_store) const { 3367 stringStream ss; 3368 ss.print_cr("[TraceMergeStores]: Replace"); 3369 for (int i = (int)merge_list.size() - 1; i >= 0; i--) { 3370 merge_list.at(i)->dump("\n", false, &ss); 3371 } 3372 ss.print_cr("[TraceMergeStores]: with"); 3373 merged_input_value->dump("\n", false, &ss); 3374 merged_store->dump("\n", false, &ss); 3375 tty->print("%s", ss.as_string()); 3376 } 3377 #endif 3378 3379 //------------------------------Ideal------------------------------------------ 3380 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x). 3381 // When a store immediately follows a relevant allocation/initialization, 3382 // try to capture it into the initialization, or hoist it above. 3383 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) { 3384 Node* p = MemNode::Ideal_common(phase, can_reshape); 3385 if (p) return (p == NodeSentinel) ? nullptr : p; 3386 3387 Node* mem = in(MemNode::Memory); 3388 Node* address = in(MemNode::Address); 3389 Node* value = in(MemNode::ValueIn); 3390 // Back-to-back stores to same address? Fold em up. Generally 3391 // unsafe if I have intervening uses. 3392 { 3393 Node* st = mem; 3394 // If Store 'st' has more than one use, we cannot fold 'st' away. 3395 // For example, 'st' might be the final state at a conditional 3396 // return. Or, 'st' might be used by some node which is live at 3397 // the same time 'st' is live, which might be unschedulable. So, 3398 // require exactly ONE user until such time as we clone 'mem' for 3399 // each of 'mem's uses (thus making the exactly-1-user-rule hold 3400 // true). 3401 while (st->is_Store() && st->outcnt() == 1) { 3402 // Looking at a dead closed cycle of memory? 3403 assert(st != st->in(MemNode::Memory), "dead loop in StoreNode::Ideal"); 3404 assert(Opcode() == st->Opcode() || 3405 st->Opcode() == Op_StoreVector || 3406 Opcode() == Op_StoreVector || 3407 st->Opcode() == Op_StoreVectorScatter || 3408 Opcode() == Op_StoreVectorScatter || 3409 phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw || 3410 (Opcode() == Op_StoreL && st->Opcode() == Op_StoreI) || // expanded ClearArrayNode 3411 (Opcode() == Op_StoreI && st->Opcode() == Op_StoreL) || // initialization by arraycopy 3412 (is_mismatched_access() || st->as_Store()->is_mismatched_access()), 3413 "no mismatched stores, except on raw memory: %s %s", NodeClassNames[Opcode()], NodeClassNames[st->Opcode()]); 3414 3415 if (st->in(MemNode::Address)->eqv_uncast(address) && 3416 st->as_Store()->memory_size() <= this->memory_size()) { 3417 Node* use = st->raw_out(0); 3418 if (phase->is_IterGVN()) { 3419 phase->is_IterGVN()->rehash_node_delayed(use); 3420 } 3421 // It's OK to do this in the parser, since DU info is always accurate, 3422 // and the parser always refers to nodes via SafePointNode maps. 3423 use->set_req_X(MemNode::Memory, st->in(MemNode::Memory), phase); 3424 return this; 3425 } 3426 st = st->in(MemNode::Memory); 3427 } 3428 } 3429 3430 3431 // Capture an unaliased, unconditional, simple store into an initializer. 3432 // Or, if it is independent of the allocation, hoist it above the allocation. 3433 if (ReduceFieldZeroing && /*can_reshape &&*/ 3434 mem->is_Proj() && mem->in(0)->is_Initialize()) { 3435 InitializeNode* init = mem->in(0)->as_Initialize(); 3436 intptr_t offset = init->can_capture_store(this, phase, can_reshape); 3437 if (offset > 0) { 3438 Node* moved = init->capture_store(this, offset, phase, can_reshape); 3439 // If the InitializeNode captured me, it made a raw copy of me, 3440 // and I need to disappear. 3441 if (moved != nullptr) { 3442 // %%% hack to ensure that Ideal returns a new node: 3443 mem = MergeMemNode::make(mem); 3444 return mem; // fold me away 3445 } 3446 } 3447 } 3448 3449 // Fold reinterpret cast into memory operation: 3450 // StoreX mem (MoveY2X v) => StoreY mem v 3451 if (value->is_Move()) { 3452 const Type* vt = value->in(1)->bottom_type(); 3453 if (has_reinterpret_variant(vt)) { 3454 if (phase->C->post_loop_opts_phase()) { 3455 return convert_to_reinterpret_store(*phase, value->in(1), vt); 3456 } else { 3457 phase->C->record_for_post_loop_opts_igvn(this); // attempt the transformation once loop opts are over 3458 } 3459 } 3460 } 3461 3462 if (MergeStores && UseUnalignedAccesses) { 3463 if (phase->C->merge_stores_phase()) { 3464 MergePrimitiveStores merge(phase, this); 3465 Node* progress = merge.run(); 3466 if (progress != nullptr) { return progress; } 3467 } else { 3468 // We need to wait with merging stores until RangeCheck smearing has removed the RangeChecks during 3469 // the post loops IGVN phase. If we do it earlier, then there may still be some RangeChecks between 3470 // the stores, and we merge the wrong sequence of stores. 3471 // Example: 3472 // StoreI RangeCheck StoreI StoreI RangeCheck StoreI 3473 // Apply MergeStores: 3474 // StoreI RangeCheck [ StoreL ] RangeCheck StoreI 3475 // Remove more RangeChecks: 3476 // StoreI [ StoreL ] StoreI 3477 // But now it would have been better to do this instead: 3478 // [ StoreL ] [ StoreL ] 3479 phase->C->record_for_merge_stores_igvn(this); 3480 } 3481 } 3482 3483 return nullptr; // No further progress 3484 } 3485 3486 //------------------------------Value----------------------------------------- 3487 const Type* StoreNode::Value(PhaseGVN* phase) const { 3488 // Either input is TOP ==> the result is TOP 3489 const Type *t1 = phase->type( in(MemNode::Memory) ); 3490 if( t1 == Type::TOP ) return Type::TOP; 3491 const Type *t2 = phase->type( in(MemNode::Address) ); 3492 if( t2 == Type::TOP ) return Type::TOP; 3493 const Type *t3 = phase->type( in(MemNode::ValueIn) ); 3494 if( t3 == Type::TOP ) return Type::TOP; 3495 return Type::MEMORY; 3496 } 3497 3498 //------------------------------Identity--------------------------------------- 3499 // Remove redundant stores: 3500 // Store(m, p, Load(m, p)) changes to m. 3501 // Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x). 3502 Node* StoreNode::Identity(PhaseGVN* phase) { 3503 Node* mem = in(MemNode::Memory); 3504 Node* adr = in(MemNode::Address); 3505 Node* val = in(MemNode::ValueIn); 3506 3507 Node* result = this; 3508 3509 // Load then Store? Then the Store is useless 3510 if (val->is_Load() && 3511 val->in(MemNode::Address)->eqv_uncast(adr) && 3512 val->in(MemNode::Memory )->eqv_uncast(mem) && 3513 val->as_Load()->store_Opcode() == Opcode()) { 3514 // Ensure vector type is the same 3515 if (!is_StoreVector() || (mem->is_LoadVector() && as_StoreVector()->vect_type() == mem->as_LoadVector()->vect_type())) { 3516 result = mem; 3517 } 3518 } 3519 3520 // Two stores in a row of the same value? 3521 if (result == this && 3522 mem->is_Store() && 3523 mem->in(MemNode::Address)->eqv_uncast(adr) && 3524 mem->in(MemNode::ValueIn)->eqv_uncast(val) && 3525 mem->Opcode() == Opcode()) { 3526 if (!is_StoreVector()) { 3527 result = mem; 3528 } else { 3529 const StoreVectorNode* store_vector = as_StoreVector(); 3530 const StoreVectorNode* mem_vector = mem->as_StoreVector(); 3531 const Node* store_indices = store_vector->indices(); 3532 const Node* mem_indices = mem_vector->indices(); 3533 const Node* store_mask = store_vector->mask(); 3534 const Node* mem_mask = mem_vector->mask(); 3535 // Ensure types, indices, and masks match 3536 if (store_vector->vect_type() == mem_vector->vect_type() && 3537 ((store_indices == nullptr) == (mem_indices == nullptr) && 3538 (store_indices == nullptr || store_indices->eqv_uncast(mem_indices))) && 3539 ((store_mask == nullptr) == (mem_mask == nullptr) && 3540 (store_mask == nullptr || store_mask->eqv_uncast(mem_mask)))) { 3541 result = mem; 3542 } 3543 } 3544 } 3545 3546 // Store of zero anywhere into a freshly-allocated object? 3547 // Then the store is useless. 3548 // (It must already have been captured by the InitializeNode.) 3549 if (result == this && 3550 ReduceFieldZeroing && phase->type(val)->is_zero_type()) { 3551 // a newly allocated object is already all-zeroes everywhere 3552 if (mem->is_Proj() && mem->in(0)->is_Allocate()) { 3553 result = mem; 3554 } 3555 3556 if (result == this) { 3557 // the store may also apply to zero-bits in an earlier object 3558 Node* prev_mem = find_previous_store(phase); 3559 // Steps (a), (b): Walk past independent stores to find an exact match. 3560 if (prev_mem != nullptr) { 3561 Node* prev_val = can_see_stored_value(prev_mem, phase); 3562 if (prev_val != nullptr && prev_val == val) { 3563 // prev_val and val might differ by a cast; it would be good 3564 // to keep the more informative of the two. 3565 result = mem; 3566 } 3567 } 3568 } 3569 } 3570 3571 PhaseIterGVN* igvn = phase->is_IterGVN(); 3572 if (result != this && igvn != nullptr) { 3573 MemBarNode* trailing = trailing_membar(); 3574 if (trailing != nullptr) { 3575 #ifdef ASSERT 3576 const TypeOopPtr* t_oop = phase->type(in(Address))->isa_oopptr(); 3577 assert(t_oop == nullptr || t_oop->is_known_instance_field(), "only for non escaping objects"); 3578 #endif 3579 trailing->remove(igvn); 3580 } 3581 } 3582 3583 return result; 3584 } 3585 3586 //------------------------------match_edge------------------------------------- 3587 // Do we Match on this edge index or not? Match only memory & value 3588 uint StoreNode::match_edge(uint idx) const { 3589 return idx == MemNode::Address || idx == MemNode::ValueIn; 3590 } 3591 3592 //------------------------------cmp-------------------------------------------- 3593 // Do not common stores up together. They generally have to be split 3594 // back up anyways, so do not bother. 3595 bool StoreNode::cmp( const Node &n ) const { 3596 return (&n == this); // Always fail except on self 3597 } 3598 3599 //------------------------------Ideal_masked_input----------------------------- 3600 // Check for a useless mask before a partial-word store 3601 // (StoreB ... (AndI valIn conIa) ) 3602 // If (conIa & mask == mask) this simplifies to 3603 // (StoreB ... (valIn) ) 3604 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) { 3605 Node *val = in(MemNode::ValueIn); 3606 if( val->Opcode() == Op_AndI ) { 3607 const TypeInt *t = phase->type( val->in(2) )->isa_int(); 3608 if( t && t->is_con() && (t->get_con() & mask) == mask ) { 3609 set_req_X(MemNode::ValueIn, val->in(1), phase); 3610 return this; 3611 } 3612 } 3613 return nullptr; 3614 } 3615 3616 3617 //------------------------------Ideal_sign_extended_input---------------------- 3618 // Check for useless sign-extension before a partial-word store 3619 // (StoreB ... (RShiftI _ (LShiftI _ v conIL) conIR)) 3620 // If (conIL == conIR && conIR <= num_rejected_bits) this simplifies to 3621 // (StoreB ... (v)) 3622 // If (conIL > conIR) under some conditions, it can be simplified into 3623 // (StoreB ... (LShiftI _ v (conIL - conIR))) 3624 // This case happens when the value of the store was itself a left shift, that 3625 // gets merged into the inner left shift of the sign-extension. For instance, 3626 // if we have 3627 // array_of_shorts[0] = (short)(v << 2) 3628 // We get a structure such as: 3629 // (StoreB ... (RShiftI _ (LShiftI _ (LShiftI _ v 2) 16) 16)) 3630 // that is simplified into 3631 // (StoreB ... (RShiftI _ (LShiftI _ v 18) 16)). 3632 // It is thus useful to handle cases where conIL > conIR. But this simplification 3633 // does not always hold. Let's see in which cases it's valid. 3634 // 3635 // Let's assume we have the following 32 bits integer v: 3636 // +----------------------------------+ 3637 // | v[0..31] | 3638 // +----------------------------------+ 3639 // 31 0 3640 // that will be stuffed in 8 bits byte after a shift left and a shift right of 3641 // potentially different magnitudes. 3642 // We denote num_rejected_bits the number of bits of the discarded part. In this 3643 // case, num_rejected_bits == 24. 3644 // 3645 // Statement (proved further below in case analysis): 3646 // Given: 3647 // - 0 <= conIL < BitsPerJavaInteger (no wrap in shift, enforced by maskShiftAmount) 3648 // - 0 <= conIR < BitsPerJavaInteger (no wrap in shift, enforced by maskShiftAmount) 3649 // - conIL >= conIR 3650 // - num_rejected_bits >= conIR 3651 // Then this form: 3652 // (RShiftI _ (LShiftI _ v conIL) conIR) 3653 // can be replaced with this form: 3654 // (LShiftI _ v (conIL-conIR)) 3655 // 3656 // Note: We only have to show that the non-rejected lowest bits (8 bits for byte) 3657 // have to be correct, as the higher bits are rejected / truncated by the store. 3658 // 3659 // The hypotheses 3660 // 0 <= conIL < BitsPerJavaInteger 3661 // 0 <= conIR < BitsPerJavaInteger 3662 // are ensured by maskShiftAmount (called from ::Ideal of shift nodes). Indeed, 3663 // (v << 31) << 2 must be simplified into 0, not into v << 33 (which is equivalent 3664 // to v << 1). 3665 // 3666 // 3667 // If you don't like case analysis, jump after the conclusion. 3668 // ### Case 1 : conIL == conIR 3669 // ###### Case 1.1: conIL == conIR == num_rejected_bits 3670 // If we do the shift left then right by 24 bits, we get: 3671 // after: v << 24 3672 // +---------+------------------------+ 3673 // | v[0..7] | 0 | 3674 // +---------+------------------------+ 3675 // 31 24 23 0 3676 // after: (v << 24) >> 24 3677 // +------------------------+---------+ 3678 // | sign bit | v[0..7] | 3679 // +------------------------+---------+ 3680 // 31 8 7 0 3681 // The non-rejected bits (bits kept by the store, that is the 8 lower bits of the 3682 // result) are the same before and after, so, indeed, simplifying is correct. 3683 3684 // ###### Case 1.2: conIL == conIR < num_rejected_bits 3685 // If we do the shift left then right by 22 bits, we get: 3686 // after: v << 22 3687 // +---------+------------------------+ 3688 // | v[0..9] | 0 | 3689 // +---------+------------------------+ 3690 // 31 22 21 0 3691 // after: (v << 22) >> 22 3692 // +------------------------+---------+ 3693 // | sign bit | v[0..9] | 3694 // +------------------------+---------+ 3695 // 31 10 9 0 3696 // The non-rejected bits are the 8 lower bits of v. The bits 8 and 9 of v are still 3697 // present in (v << 22) >> 22 but will be dropped by the store. The simplification is 3698 // still correct. 3699 3700 // ###### But! Case 1.3: conIL == conIR > num_rejected_bits 3701 // If we do the shift left then right by 26 bits, we get: 3702 // after: v << 26 3703 // +---------+------------------------+ 3704 // | v[0..5] | 0 | 3705 // +---------+------------------------+ 3706 // 31 26 25 0 3707 // after: (v << 26) >> 26 3708 // +------------------------+---------+ 3709 // | sign bit | v[0..5] | 3710 // +------------------------+---------+ 3711 // 31 6 5 0 3712 // The non-rejected bits are made of 3713 // - 0-5 => the bits 0 to 5 of v 3714 // - 6-7 => the sign bit of v[0..5] (that is v[5]) 3715 // Simplifying this as v is not correct. 3716 // The condition conIR <= num_rejected_bits is indeed necessary in Case 1 3717 // 3718 // ### Case 2: conIL > conIR 3719 // ###### Case 2.1: num_rejected_bits == conIR 3720 // We take conIL == 26 for this example. 3721 // after: v << 26 3722 // +---------+------------------------+ 3723 // | v[0..5] | 0 | 3724 // +---------+------------------------+ 3725 // 31 26 25 0 3726 // after: (v << 26) >> 24 3727 // +------------------+---------+-----+ 3728 // | sign bit | v[0..5] | 0 | 3729 // +------------------+---------+-----+ 3730 // 31 8 7 2 1 0 3731 // The non-rejected bits are the 8 lower ones of (v << conIL - conIR). 3732 // The bits 6 and 7 of v have been thrown away after the shift left. 3733 // The simplification is still correct. 3734 // 3735 // ###### Case 2.2: num_rejected_bits > conIR. 3736 // Let's say conIL == 26 and conIR == 22. 3737 // after: v << 26 3738 // +---------+------------------------+ 3739 // | v[0..5] | 0 | 3740 // +---------+------------------------+ 3741 // 31 26 25 0 3742 // after: (v << 26) >> 22 3743 // +------------------+---------+-----+ 3744 // | sign bit | v[0..5] | 0 | 3745 // +------------------+---------+-----+ 3746 // 31 10 9 4 3 0 3747 // The bits non-rejected by the store are exactly the 8 lower ones of (v << (conIL - conIR)): 3748 // - 0-3 => 0 3749 // - 4-7 => bits 0 to 3 of v 3750 // The simplification is still correct. 3751 // The bits 4 and 5 of v are still present in (v << (conIL - conIR)) but they don't 3752 // matter as they are not in the 8 lower bits: they will be cut out by the store. 3753 // 3754 // ###### But! Case 2.3: num_rejected_bits < conIR. 3755 // Let's see that this case is not as easy to simplify. 3756 // Let's say conIL == 28 and conIR == 26. 3757 // after: v << 28 3758 // +---------+------------------------+ 3759 // | v[0..3] | 0 | 3760 // +---------+------------------------+ 3761 // 31 28 27 0 3762 // after: (v << 28) >> 26 3763 // +------------------+---------+-----+ 3764 // | sign bit | v[0..3] | 0 | 3765 // +------------------+---------+-----+ 3766 // 31 6 5 2 1 0 3767 // The non-rejected bits are made of 3768 // - 0-1 => 0 3769 // - 2-5 => the bits 0 to 3 of v 3770 // - 6-7 => the sign bit of v[0..3] (that is v[3]) 3771 // Simplifying this as (v << 2) is not correct. 3772 // The condition conIR <= num_rejected_bits is indeed necessary in Case 2. 3773 // 3774 // ### Conclusion: 3775 // Our hypotheses are indeed sufficient: 3776 // - 0 <= conIL < BitsPerJavaInteger 3777 // - 0 <= conIR < BitsPerJavaInteger 3778 // - conIL >= conIR 3779 // - num_rejected_bits >= conIR 3780 // 3781 // ### A rationale without case analysis: 3782 // After the shift left, conIL upper bits of v are discarded and conIL lower bit 3783 // zeroes are added. After the shift right, conIR lower bits of the previous result 3784 // are discarded. If conIL >= conIR, we discard only the zeroes we made up during 3785 // the shift left, but if conIL < conIR, then we discard also lower bits of v. But 3786 // the point of the simplification is to get an expression of the form 3787 // (v << (conIL - conIR)). This expression discard only higher bits of v, thus the 3788 // simplification is not correct if conIL < conIR. 3789 // 3790 // Moreover, after the shift right, the higher bit of (v << conIL) is repeated on the 3791 // conIR higher bits of ((v << conIL) >> conIR), it's the sign-extension. If 3792 // conIR > num_rejected_bits, then at least one artificial copy of this sign bit will 3793 // be in the window of the store. Thus ((v << conIL) >> conIR) is not equivalent to 3794 // (v << (conIL-conIR)) if conIR > num_rejected_bits. 3795 // 3796 // We do not treat the case conIL < conIR here since the point of this function is 3797 // to skip sign-extensions (that is conIL == conIR == num_rejected_bits). The need 3798 // of treating conIL > conIR comes from the cases where the sign-extended value is 3799 // also left-shift expression. Computing the sign-extension of a right-shift expression 3800 // doesn't yield a situation such as 3801 // (StoreB ... (RShiftI _ (LShiftI _ v conIL) conIR)) 3802 // where conIL < conIR. 3803 Node* StoreNode::Ideal_sign_extended_input(PhaseGVN* phase, int num_rejected_bits) { 3804 Node* shr = in(MemNode::ValueIn); 3805 if (shr->Opcode() == Op_RShiftI) { 3806 const TypeInt* conIR = phase->type(shr->in(2))->isa_int(); 3807 if (conIR != nullptr && conIR->is_con() && conIR->get_con() >= 0 && conIR->get_con() < BitsPerJavaInteger && conIR->get_con() <= num_rejected_bits) { 3808 Node* shl = shr->in(1); 3809 if (shl->Opcode() == Op_LShiftI) { 3810 const TypeInt* conIL = phase->type(shl->in(2))->isa_int(); 3811 if (conIL != nullptr && conIL->is_con() && conIL->get_con() >= 0 && conIL->get_con() < BitsPerJavaInteger) { 3812 if (conIL->get_con() == conIR->get_con()) { 3813 set_req_X(MemNode::ValueIn, shl->in(1), phase); 3814 return this; 3815 } 3816 if (conIL->get_con() > conIR->get_con()) { 3817 Node* new_shl = phase->transform(new LShiftINode(shl->in(1), phase->intcon(conIL->get_con() - conIR->get_con()))); 3818 set_req_X(MemNode::ValueIn, new_shl, phase); 3819 return this; 3820 } 3821 } 3822 } 3823 } 3824 } 3825 return nullptr; 3826 } 3827 3828 //------------------------------value_never_loaded----------------------------------- 3829 // Determine whether there are any possible loads of the value stored. 3830 // For simplicity, we actually check if there are any loads from the 3831 // address stored to, not just for loads of the value stored by this node. 3832 // 3833 bool StoreNode::value_never_loaded(PhaseValues* phase) const { 3834 Node *adr = in(Address); 3835 const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr(); 3836 if (adr_oop == nullptr) 3837 return false; 3838 if (!adr_oop->is_known_instance_field()) 3839 return false; // if not a distinct instance, there may be aliases of the address 3840 for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) { 3841 Node *use = adr->fast_out(i); 3842 if (use->is_Load() || use->is_LoadStore()) { 3843 return false; 3844 } 3845 } 3846 return true; 3847 } 3848 3849 MemBarNode* StoreNode::trailing_membar() const { 3850 if (is_release()) { 3851 MemBarNode* trailing_mb = nullptr; 3852 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3853 Node* u = fast_out(i); 3854 if (u->is_MemBar()) { 3855 if (u->as_MemBar()->trailing_store()) { 3856 assert(u->Opcode() == Op_MemBarVolatile, ""); 3857 assert(trailing_mb == nullptr, "only one"); 3858 trailing_mb = u->as_MemBar(); 3859 #ifdef ASSERT 3860 Node* leading = u->as_MemBar()->leading_membar(); 3861 assert(leading->Opcode() == Op_MemBarRelease, "incorrect membar"); 3862 assert(leading->as_MemBar()->leading_store(), "incorrect membar pair"); 3863 assert(leading->as_MemBar()->trailing_membar() == u, "incorrect membar pair"); 3864 #endif 3865 } else { 3866 assert(u->as_MemBar()->standalone(), ""); 3867 } 3868 } 3869 } 3870 return trailing_mb; 3871 } 3872 return nullptr; 3873 } 3874 3875 3876 //============================================================================= 3877 //------------------------------Ideal------------------------------------------ 3878 // If the store is from an AND mask that leaves the low bits untouched, then 3879 // we can skip the AND operation. If the store is from a sign-extension 3880 // (a left shift, then right shift) we can skip both. 3881 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){ 3882 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF); 3883 if( progress != nullptr ) return progress; 3884 3885 progress = StoreNode::Ideal_sign_extended_input(phase, 24); 3886 if( progress != nullptr ) return progress; 3887 3888 // Finally check the default case 3889 return StoreNode::Ideal(phase, can_reshape); 3890 } 3891 3892 //============================================================================= 3893 //------------------------------Ideal------------------------------------------ 3894 // If the store is from an AND mask that leaves the low bits untouched, then 3895 // we can skip the AND operation 3896 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){ 3897 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF); 3898 if( progress != nullptr ) return progress; 3899 3900 progress = StoreNode::Ideal_sign_extended_input(phase, 16); 3901 if( progress != nullptr ) return progress; 3902 3903 // Finally check the default case 3904 return StoreNode::Ideal(phase, can_reshape); 3905 } 3906 3907 //============================================================================= 3908 //----------------------------------SCMemProjNode------------------------------ 3909 const Type* SCMemProjNode::Value(PhaseGVN* phase) const 3910 { 3911 if (in(0) == nullptr || phase->type(in(0)) == Type::TOP) { 3912 return Type::TOP; 3913 } 3914 return bottom_type(); 3915 } 3916 3917 //============================================================================= 3918 //----------------------------------LoadStoreNode------------------------------ 3919 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, const TypePtr* at, const Type* rt, uint required ) 3920 : Node(required), 3921 _type(rt), 3922 _adr_type(at), 3923 _barrier_data(0) 3924 { 3925 init_req(MemNode::Control, c ); 3926 init_req(MemNode::Memory , mem); 3927 init_req(MemNode::Address, adr); 3928 init_req(MemNode::ValueIn, val); 3929 init_class_id(Class_LoadStore); 3930 } 3931 3932 //------------------------------Value----------------------------------------- 3933 const Type* LoadStoreNode::Value(PhaseGVN* phase) const { 3934 // Either input is TOP ==> the result is TOP 3935 if (!in(MemNode::Control) || phase->type(in(MemNode::Control)) == Type::TOP) { 3936 return Type::TOP; 3937 } 3938 const Type* t = phase->type(in(MemNode::Memory)); 3939 if (t == Type::TOP) { 3940 return Type::TOP; 3941 } 3942 t = phase->type(in(MemNode::Address)); 3943 if (t == Type::TOP) { 3944 return Type::TOP; 3945 } 3946 t = phase->type(in(MemNode::ValueIn)); 3947 if (t == Type::TOP) { 3948 return Type::TOP; 3949 } 3950 return bottom_type(); 3951 } 3952 3953 uint LoadStoreNode::ideal_reg() const { 3954 return _type->ideal_reg(); 3955 } 3956 3957 // This method conservatively checks if the result of a LoadStoreNode is 3958 // used, that is, if it returns true, then it is definitely the case that 3959 // the result of the node is not needed. 3960 // For example, GetAndAdd can be matched into a lock_add instead of a 3961 // lock_xadd if the result of LoadStoreNode::result_not_used() is true 3962 bool LoadStoreNode::result_not_used() const { 3963 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3964 Node *x = fast_out(i); 3965 if (x->Opcode() == Op_SCMemProj) { 3966 continue; 3967 } 3968 if (x->bottom_type() == TypeTuple::MEMBAR && 3969 !x->is_Call() && 3970 x->Opcode() != Op_Blackhole) { 3971 continue; 3972 } 3973 return false; 3974 } 3975 return true; 3976 } 3977 3978 MemBarNode* LoadStoreNode::trailing_membar() const { 3979 MemBarNode* trailing = nullptr; 3980 for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) { 3981 Node* u = fast_out(i); 3982 if (u->is_MemBar()) { 3983 if (u->as_MemBar()->trailing_load_store()) { 3984 assert(u->Opcode() == Op_MemBarAcquire, ""); 3985 assert(trailing == nullptr, "only one"); 3986 trailing = u->as_MemBar(); 3987 #ifdef ASSERT 3988 Node* leading = trailing->leading_membar(); 3989 assert(support_IRIW_for_not_multiple_copy_atomic_cpu || leading->Opcode() == Op_MemBarRelease, "incorrect membar"); 3990 assert(leading->as_MemBar()->leading_load_store(), "incorrect membar pair"); 3991 assert(leading->as_MemBar()->trailing_membar() == trailing, "incorrect membar pair"); 3992 #endif 3993 } else { 3994 assert(u->as_MemBar()->standalone(), "wrong barrier kind"); 3995 } 3996 } 3997 } 3998 3999 return trailing; 4000 } 4001 4002 uint LoadStoreNode::size_of() const { return sizeof(*this); } 4003 4004 //============================================================================= 4005 //----------------------------------LoadStoreConditionalNode-------------------- 4006 LoadStoreConditionalNode::LoadStoreConditionalNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : LoadStoreNode(c, mem, adr, val, nullptr, TypeInt::BOOL, 5) { 4007 init_req(ExpectedIn, ex ); 4008 } 4009 4010 const Type* LoadStoreConditionalNode::Value(PhaseGVN* phase) const { 4011 // Either input is TOP ==> the result is TOP 4012 const Type* t = phase->type(in(ExpectedIn)); 4013 if (t == Type::TOP) { 4014 return Type::TOP; 4015 } 4016 return LoadStoreNode::Value(phase); 4017 } 4018 4019 //============================================================================= 4020 //-------------------------------adr_type-------------------------------------- 4021 const TypePtr* ClearArrayNode::adr_type() const { 4022 Node *adr = in(3); 4023 if (adr == nullptr) return nullptr; // node is dead 4024 return MemNode::calculate_adr_type(adr->bottom_type()); 4025 } 4026 4027 //------------------------------match_edge------------------------------------- 4028 // Do we Match on this edge index or not? Do not match memory 4029 uint ClearArrayNode::match_edge(uint idx) const { 4030 return idx > 1; 4031 } 4032 4033 //------------------------------Identity--------------------------------------- 4034 // Clearing a zero length array does nothing 4035 Node* ClearArrayNode::Identity(PhaseGVN* phase) { 4036 return phase->type(in(2))->higher_equal(TypeX::ZERO) ? in(1) : this; 4037 } 4038 4039 //------------------------------Idealize--------------------------------------- 4040 // Clearing a short array is faster with stores 4041 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) { 4042 // Already know this is a large node, do not try to ideal it 4043 if (_is_large) return nullptr; 4044 4045 const int unit = BytesPerLong; 4046 const TypeX* t = phase->type(in(2))->isa_intptr_t(); 4047 if (!t) return nullptr; 4048 if (!t->is_con()) return nullptr; 4049 intptr_t raw_count = t->get_con(); 4050 intptr_t size = raw_count; 4051 if (!Matcher::init_array_count_is_in_bytes) size *= unit; 4052 // Clearing nothing uses the Identity call. 4053 // Negative clears are possible on dead ClearArrays 4054 // (see jck test stmt114.stmt11402.val). 4055 if (size <= 0 || size % unit != 0) return nullptr; 4056 intptr_t count = size / unit; 4057 // Length too long; communicate this to matchers and assemblers. 4058 // Assemblers are responsible to produce fast hardware clears for it. 4059 if (size > InitArrayShortSize) { 4060 return new ClearArrayNode(in(0), in(1), in(2), in(3), true); 4061 } else if (size > 2 && Matcher::match_rule_supported_vector(Op_ClearArray, 4, T_LONG)) { 4062 return nullptr; 4063 } 4064 if (!IdealizeClearArrayNode) return nullptr; 4065 Node *mem = in(1); 4066 if( phase->type(mem)==Type::TOP ) return nullptr; 4067 Node *adr = in(3); 4068 const Type* at = phase->type(adr); 4069 if( at==Type::TOP ) return nullptr; 4070 const TypePtr* atp = at->isa_ptr(); 4071 // adjust atp to be the correct array element address type 4072 if (atp == nullptr) atp = TypePtr::BOTTOM; 4073 else atp = atp->add_offset(Type::OffsetBot); 4074 // Get base for derived pointer purposes 4075 if( adr->Opcode() != Op_AddP ) Unimplemented(); 4076 Node *base = adr->in(1); 4077 4078 Node *zero = phase->makecon(TypeLong::ZERO); 4079 Node *off = phase->MakeConX(BytesPerLong); 4080 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false); 4081 count--; 4082 while( count-- ) { 4083 mem = phase->transform(mem); 4084 adr = phase->transform(new AddPNode(base,adr,off)); 4085 mem = new StoreLNode(in(0),mem,adr,atp,zero,MemNode::unordered,false); 4086 } 4087 return mem; 4088 } 4089 4090 //----------------------------step_through---------------------------------- 4091 // Return allocation input memory edge if it is different instance 4092 // or itself if it is the one we are looking for. 4093 bool ClearArrayNode::step_through(Node** np, uint instance_id, PhaseValues* phase) { 4094 Node* n = *np; 4095 assert(n->is_ClearArray(), "sanity"); 4096 intptr_t offset; 4097 AllocateNode* alloc = AllocateNode::Ideal_allocation(n->in(3), phase, offset); 4098 // This method is called only before Allocate nodes are expanded 4099 // during macro nodes expansion. Before that ClearArray nodes are 4100 // only generated in PhaseMacroExpand::generate_arraycopy() (before 4101 // Allocate nodes are expanded) which follows allocations. 4102 assert(alloc != nullptr, "should have allocation"); 4103 if (alloc->_idx == instance_id) { 4104 // Can not bypass initialization of the instance we are looking for. 4105 return false; 4106 } 4107 // Otherwise skip it. 4108 InitializeNode* init = alloc->initialization(); 4109 if (init != nullptr) 4110 *np = init->in(TypeFunc::Memory); 4111 else 4112 *np = alloc->in(TypeFunc::Memory); 4113 return true; 4114 } 4115 4116 //----------------------------clear_memory------------------------------------- 4117 // Generate code to initialize object storage to zero. 4118 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 4119 intptr_t start_offset, 4120 Node* end_offset, 4121 PhaseGVN* phase) { 4122 intptr_t offset = start_offset; 4123 4124 int unit = BytesPerLong; 4125 if ((offset % unit) != 0) { 4126 Node* adr = new AddPNode(dest, dest, phase->MakeConX(offset)); 4127 adr = phase->transform(adr); 4128 const TypePtr* atp = TypeRawPtr::BOTTOM; 4129 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered); 4130 mem = phase->transform(mem); 4131 offset += BytesPerInt; 4132 } 4133 assert((offset % unit) == 0, ""); 4134 4135 // Initialize the remaining stuff, if any, with a ClearArray. 4136 return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase); 4137 } 4138 4139 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 4140 Node* start_offset, 4141 Node* end_offset, 4142 PhaseGVN* phase) { 4143 if (start_offset == end_offset) { 4144 // nothing to do 4145 return mem; 4146 } 4147 4148 int unit = BytesPerLong; 4149 Node* zbase = start_offset; 4150 Node* zend = end_offset; 4151 4152 // Scale to the unit required by the CPU: 4153 if (!Matcher::init_array_count_is_in_bytes) { 4154 Node* shift = phase->intcon(exact_log2(unit)); 4155 zbase = phase->transform(new URShiftXNode(zbase, shift) ); 4156 zend = phase->transform(new URShiftXNode(zend, shift) ); 4157 } 4158 4159 // Bulk clear double-words 4160 Node* zsize = phase->transform(new SubXNode(zend, zbase) ); 4161 Node* adr = phase->transform(new AddPNode(dest, dest, start_offset) ); 4162 mem = new ClearArrayNode(ctl, mem, zsize, adr, false); 4163 return phase->transform(mem); 4164 } 4165 4166 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest, 4167 intptr_t start_offset, 4168 intptr_t end_offset, 4169 PhaseGVN* phase) { 4170 if (start_offset == end_offset) { 4171 // nothing to do 4172 return mem; 4173 } 4174 4175 assert((end_offset % BytesPerInt) == 0, "odd end offset"); 4176 intptr_t done_offset = end_offset; 4177 if ((done_offset % BytesPerLong) != 0) { 4178 done_offset -= BytesPerInt; 4179 } 4180 if (done_offset > start_offset) { 4181 mem = clear_memory(ctl, mem, dest, 4182 start_offset, phase->MakeConX(done_offset), phase); 4183 } 4184 if (done_offset < end_offset) { // emit the final 32-bit store 4185 Node* adr = new AddPNode(dest, dest, phase->MakeConX(done_offset)); 4186 adr = phase->transform(adr); 4187 const TypePtr* atp = TypeRawPtr::BOTTOM; 4188 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT, MemNode::unordered); 4189 mem = phase->transform(mem); 4190 done_offset += BytesPerInt; 4191 } 4192 assert(done_offset == end_offset, ""); 4193 return mem; 4194 } 4195 4196 //============================================================================= 4197 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent) 4198 : MultiNode(TypeFunc::Parms + (precedent == nullptr? 0: 1)), 4199 _adr_type(C->get_adr_type(alias_idx)), _kind(Standalone) 4200 #ifdef ASSERT 4201 , _pair_idx(0) 4202 #endif 4203 { 4204 init_class_id(Class_MemBar); 4205 Node* top = C->top(); 4206 init_req(TypeFunc::I_O,top); 4207 init_req(TypeFunc::FramePtr,top); 4208 init_req(TypeFunc::ReturnAdr,top); 4209 if (precedent != nullptr) 4210 init_req(TypeFunc::Parms, precedent); 4211 } 4212 4213 //------------------------------cmp-------------------------------------------- 4214 uint MemBarNode::hash() const { return NO_HASH; } 4215 bool MemBarNode::cmp( const Node &n ) const { 4216 return (&n == this); // Always fail except on self 4217 } 4218 4219 //------------------------------make------------------------------------------- 4220 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) { 4221 switch (opcode) { 4222 case Op_MemBarAcquire: return new MemBarAcquireNode(C, atp, pn); 4223 case Op_LoadFence: return new LoadFenceNode(C, atp, pn); 4224 case Op_MemBarRelease: return new MemBarReleaseNode(C, atp, pn); 4225 case Op_StoreFence: return new StoreFenceNode(C, atp, pn); 4226 case Op_MemBarStoreStore: return new MemBarStoreStoreNode(C, atp, pn); 4227 case Op_StoreStoreFence: return new StoreStoreFenceNode(C, atp, pn); 4228 case Op_MemBarAcquireLock: return new MemBarAcquireLockNode(C, atp, pn); 4229 case Op_MemBarReleaseLock: return new MemBarReleaseLockNode(C, atp, pn); 4230 case Op_MemBarVolatile: return new MemBarVolatileNode(C, atp, pn); 4231 case Op_MemBarCPUOrder: return new MemBarCPUOrderNode(C, atp, pn); 4232 case Op_OnSpinWait: return new OnSpinWaitNode(C, atp, pn); 4233 case Op_Initialize: return new InitializeNode(C, atp, pn); 4234 default: ShouldNotReachHere(); return nullptr; 4235 } 4236 } 4237 4238 void MemBarNode::remove(PhaseIterGVN *igvn) { 4239 if (outcnt() != 2) { 4240 assert(Opcode() == Op_Initialize, "Only seen when there are no use of init memory"); 4241 assert(outcnt() == 1, "Only control then"); 4242 } 4243 if (trailing_store() || trailing_load_store()) { 4244 MemBarNode* leading = leading_membar(); 4245 if (leading != nullptr) { 4246 assert(leading->trailing_membar() == this, "inconsistent leading/trailing membars"); 4247 leading->remove(igvn); 4248 } 4249 } 4250 if (proj_out_or_null(TypeFunc::Memory) != nullptr) { 4251 igvn->replace_node(proj_out(TypeFunc::Memory), in(TypeFunc::Memory)); 4252 } 4253 if (proj_out_or_null(TypeFunc::Control) != nullptr) { 4254 igvn->replace_node(proj_out(TypeFunc::Control), in(TypeFunc::Control)); 4255 } 4256 } 4257 4258 //------------------------------Ideal------------------------------------------ 4259 // Return a node which is more "ideal" than the current node. Strip out 4260 // control copies 4261 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) { 4262 if (remove_dead_region(phase, can_reshape)) return this; 4263 // Don't bother trying to transform a dead node 4264 if (in(0) && in(0)->is_top()) { 4265 return nullptr; 4266 } 4267 4268 bool progress = false; 4269 // Eliminate volatile MemBars for scalar replaced objects. 4270 if (can_reshape && req() == (Precedent+1)) { 4271 bool eliminate = false; 4272 int opc = Opcode(); 4273 if ((opc == Op_MemBarAcquire || opc == Op_MemBarVolatile)) { 4274 // Volatile field loads and stores. 4275 Node* my_mem = in(MemBarNode::Precedent); 4276 // The MembarAquire may keep an unused LoadNode alive through the Precedent edge 4277 if ((my_mem != nullptr) && (opc == Op_MemBarAcquire) && (my_mem->outcnt() == 1)) { 4278 // if the Precedent is a decodeN and its input (a Load) is used at more than one place, 4279 // replace this Precedent (decodeN) with the Load instead. 4280 if ((my_mem->Opcode() == Op_DecodeN) && (my_mem->in(1)->outcnt() > 1)) { 4281 Node* load_node = my_mem->in(1); 4282 set_req(MemBarNode::Precedent, load_node); 4283 phase->is_IterGVN()->_worklist.push(my_mem); 4284 my_mem = load_node; 4285 } else { 4286 assert(my_mem->unique_out() == this, "sanity"); 4287 assert(!trailing_load_store(), "load store node can't be eliminated"); 4288 del_req(Precedent); 4289 phase->is_IterGVN()->_worklist.push(my_mem); // remove dead node later 4290 my_mem = nullptr; 4291 } 4292 progress = true; 4293 } 4294 if (my_mem != nullptr && my_mem->is_Mem()) { 4295 const TypeOopPtr* t_oop = my_mem->in(MemNode::Address)->bottom_type()->isa_oopptr(); 4296 // Check for scalar replaced object reference. 4297 if( t_oop != nullptr && t_oop->is_known_instance_field() && 4298 t_oop->offset() != Type::OffsetBot && 4299 t_oop->offset() != Type::OffsetTop) { 4300 eliminate = true; 4301 } 4302 } 4303 } else if (opc == Op_MemBarRelease || (UseStoreStoreForCtor && opc == Op_MemBarStoreStore)) { 4304 // Final field stores. 4305 Node* alloc = AllocateNode::Ideal_allocation(in(MemBarNode::Precedent)); 4306 if ((alloc != nullptr) && alloc->is_Allocate() && 4307 alloc->as_Allocate()->does_not_escape_thread()) { 4308 // The allocated object does not escape. 4309 eliminate = true; 4310 } 4311 } 4312 if (eliminate) { 4313 // Replace MemBar projections by its inputs. 4314 PhaseIterGVN* igvn = phase->is_IterGVN(); 4315 remove(igvn); 4316 // Must return either the original node (now dead) or a new node 4317 // (Do not return a top here, since that would break the uniqueness of top.) 4318 return new ConINode(TypeInt::ZERO); 4319 } 4320 } 4321 return progress ? this : nullptr; 4322 } 4323 4324 //------------------------------Value------------------------------------------ 4325 const Type* MemBarNode::Value(PhaseGVN* phase) const { 4326 if( !in(0) ) return Type::TOP; 4327 if( phase->type(in(0)) == Type::TOP ) 4328 return Type::TOP; 4329 return TypeTuple::MEMBAR; 4330 } 4331 4332 //------------------------------match------------------------------------------ 4333 // Construct projections for memory. 4334 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) { 4335 switch (proj->_con) { 4336 case TypeFunc::Control: 4337 case TypeFunc::Memory: 4338 return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj); 4339 } 4340 ShouldNotReachHere(); 4341 return nullptr; 4342 } 4343 4344 void MemBarNode::set_store_pair(MemBarNode* leading, MemBarNode* trailing) { 4345 trailing->_kind = TrailingStore; 4346 leading->_kind = LeadingStore; 4347 #ifdef ASSERT 4348 trailing->_pair_idx = leading->_idx; 4349 leading->_pair_idx = leading->_idx; 4350 #endif 4351 } 4352 4353 void MemBarNode::set_load_store_pair(MemBarNode* leading, MemBarNode* trailing) { 4354 trailing->_kind = TrailingLoadStore; 4355 leading->_kind = LeadingLoadStore; 4356 #ifdef ASSERT 4357 trailing->_pair_idx = leading->_idx; 4358 leading->_pair_idx = leading->_idx; 4359 #endif 4360 } 4361 4362 MemBarNode* MemBarNode::trailing_membar() const { 4363 ResourceMark rm; 4364 Node* trailing = (Node*)this; 4365 VectorSet seen; 4366 Node_Stack multis(0); 4367 do { 4368 Node* c = trailing; 4369 uint i = 0; 4370 do { 4371 trailing = nullptr; 4372 for (; i < c->outcnt(); i++) { 4373 Node* next = c->raw_out(i); 4374 if (next != c && next->is_CFG()) { 4375 if (c->is_MultiBranch()) { 4376 if (multis.node() == c) { 4377 multis.set_index(i+1); 4378 } else { 4379 multis.push(c, i+1); 4380 } 4381 } 4382 trailing = next; 4383 break; 4384 } 4385 } 4386 if (trailing != nullptr && !seen.test_set(trailing->_idx)) { 4387 break; 4388 } 4389 while (multis.size() > 0) { 4390 c = multis.node(); 4391 i = multis.index(); 4392 if (i < c->req()) { 4393 break; 4394 } 4395 multis.pop(); 4396 } 4397 } while (multis.size() > 0); 4398 } while (!trailing->is_MemBar() || !trailing->as_MemBar()->trailing()); 4399 4400 MemBarNode* mb = trailing->as_MemBar(); 4401 assert((mb->_kind == TrailingStore && _kind == LeadingStore) || 4402 (mb->_kind == TrailingLoadStore && _kind == LeadingLoadStore), "bad trailing membar"); 4403 assert(mb->_pair_idx == _pair_idx, "bad trailing membar"); 4404 return mb; 4405 } 4406 4407 MemBarNode* MemBarNode::leading_membar() const { 4408 ResourceMark rm; 4409 VectorSet seen; 4410 Node_Stack regions(0); 4411 Node* leading = in(0); 4412 while (leading != nullptr && (!leading->is_MemBar() || !leading->as_MemBar()->leading())) { 4413 while (leading == nullptr || leading->is_top() || seen.test_set(leading->_idx)) { 4414 leading = nullptr; 4415 while (regions.size() > 0 && leading == nullptr) { 4416 Node* r = regions.node(); 4417 uint i = regions.index(); 4418 if (i < r->req()) { 4419 leading = r->in(i); 4420 regions.set_index(i+1); 4421 } else { 4422 regions.pop(); 4423 } 4424 } 4425 if (leading == nullptr) { 4426 assert(regions.size() == 0, "all paths should have been tried"); 4427 return nullptr; 4428 } 4429 } 4430 if (leading->is_Region()) { 4431 regions.push(leading, 2); 4432 leading = leading->in(1); 4433 } else { 4434 leading = leading->in(0); 4435 } 4436 } 4437 #ifdef ASSERT 4438 Unique_Node_List wq; 4439 wq.push((Node*)this); 4440 uint found = 0; 4441 for (uint i = 0; i < wq.size(); i++) { 4442 Node* n = wq.at(i); 4443 if (n->is_Region()) { 4444 for (uint j = 1; j < n->req(); j++) { 4445 Node* in = n->in(j); 4446 if (in != nullptr && !in->is_top()) { 4447 wq.push(in); 4448 } 4449 } 4450 } else { 4451 if (n->is_MemBar() && n->as_MemBar()->leading()) { 4452 assert(n == leading, "consistency check failed"); 4453 found++; 4454 } else { 4455 Node* in = n->in(0); 4456 if (in != nullptr && !in->is_top()) { 4457 wq.push(in); 4458 } 4459 } 4460 } 4461 } 4462 assert(found == 1 || (found == 0 && leading == nullptr), "consistency check failed"); 4463 #endif 4464 if (leading == nullptr) { 4465 return nullptr; 4466 } 4467 MemBarNode* mb = leading->as_MemBar(); 4468 assert((mb->_kind == LeadingStore && _kind == TrailingStore) || 4469 (mb->_kind == LeadingLoadStore && _kind == TrailingLoadStore), "bad leading membar"); 4470 assert(mb->_pair_idx == _pair_idx, "bad leading membar"); 4471 return mb; 4472 } 4473 4474 4475 //===========================InitializeNode==================================== 4476 // SUMMARY: 4477 // This node acts as a memory barrier on raw memory, after some raw stores. 4478 // The 'cooked' oop value feeds from the Initialize, not the Allocation. 4479 // The Initialize can 'capture' suitably constrained stores as raw inits. 4480 // It can coalesce related raw stores into larger units (called 'tiles'). 4481 // It can avoid zeroing new storage for memory units which have raw inits. 4482 // At macro-expansion, it is marked 'complete', and does not optimize further. 4483 // 4484 // EXAMPLE: 4485 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine. 4486 // ctl = incoming control; mem* = incoming memory 4487 // (Note: A star * on a memory edge denotes I/O and other standard edges.) 4488 // First allocate uninitialized memory and fill in the header: 4489 // alloc = (Allocate ctl mem* 16 #short[].klass ...) 4490 // ctl := alloc.Control; mem* := alloc.Memory* 4491 // rawmem = alloc.Memory; rawoop = alloc.RawAddress 4492 // Then initialize to zero the non-header parts of the raw memory block: 4493 // init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress) 4494 // ctl := init.Control; mem.SLICE(#short[*]) := init.Memory 4495 // After the initialize node executes, the object is ready for service: 4496 // oop := (CheckCastPP init.Control alloc.RawAddress #short[]) 4497 // Suppose its body is immediately initialized as {1,2}: 4498 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1) 4499 // store2 = (StoreC init.Control store1 (+ oop 14) 2) 4500 // mem.SLICE(#short[*]) := store2 4501 // 4502 // DETAILS: 4503 // An InitializeNode collects and isolates object initialization after 4504 // an AllocateNode and before the next possible safepoint. As a 4505 // memory barrier (MemBarNode), it keeps critical stores from drifting 4506 // down past any safepoint or any publication of the allocation. 4507 // Before this barrier, a newly-allocated object may have uninitialized bits. 4508 // After this barrier, it may be treated as a real oop, and GC is allowed. 4509 // 4510 // The semantics of the InitializeNode include an implicit zeroing of 4511 // the new object from object header to the end of the object. 4512 // (The object header and end are determined by the AllocateNode.) 4513 // 4514 // Certain stores may be added as direct inputs to the InitializeNode. 4515 // These stores must update raw memory, and they must be to addresses 4516 // derived from the raw address produced by AllocateNode, and with 4517 // a constant offset. They must be ordered by increasing offset. 4518 // The first one is at in(RawStores), the last at in(req()-1). 4519 // Unlike most memory operations, they are not linked in a chain, 4520 // but are displayed in parallel as users of the rawmem output of 4521 // the allocation. 4522 // 4523 // (See comments in InitializeNode::capture_store, which continue 4524 // the example given above.) 4525 // 4526 // When the associated Allocate is macro-expanded, the InitializeNode 4527 // may be rewritten to optimize collected stores. A ClearArrayNode 4528 // may also be created at that point to represent any required zeroing. 4529 // The InitializeNode is then marked 'complete', prohibiting further 4530 // capturing of nearby memory operations. 4531 // 4532 // During macro-expansion, all captured initializations which store 4533 // constant values of 32 bits or smaller are coalesced (if advantageous) 4534 // into larger 'tiles' 32 or 64 bits. This allows an object to be 4535 // initialized in fewer memory operations. Memory words which are 4536 // covered by neither tiles nor non-constant stores are pre-zeroed 4537 // by explicit stores of zero. (The code shape happens to do all 4538 // zeroing first, then all other stores, with both sequences occurring 4539 // in order of ascending offsets.) 4540 // 4541 // Alternatively, code may be inserted between an AllocateNode and its 4542 // InitializeNode, to perform arbitrary initialization of the new object. 4543 // E.g., the object copying intrinsics insert complex data transfers here. 4544 // The initialization must then be marked as 'complete' disable the 4545 // built-in zeroing semantics and the collection of initializing stores. 4546 // 4547 // While an InitializeNode is incomplete, reads from the memory state 4548 // produced by it are optimizable if they match the control edge and 4549 // new oop address associated with the allocation/initialization. 4550 // They return a stored value (if the offset matches) or else zero. 4551 // A write to the memory state, if it matches control and address, 4552 // and if it is to a constant offset, may be 'captured' by the 4553 // InitializeNode. It is cloned as a raw memory operation and rewired 4554 // inside the initialization, to the raw oop produced by the allocation. 4555 // Operations on addresses which are provably distinct (e.g., to 4556 // other AllocateNodes) are allowed to bypass the initialization. 4557 // 4558 // The effect of all this is to consolidate object initialization 4559 // (both arrays and non-arrays, both piecewise and bulk) into a 4560 // single location, where it can be optimized as a unit. 4561 // 4562 // Only stores with an offset less than TrackedInitializationLimit words 4563 // will be considered for capture by an InitializeNode. This puts a 4564 // reasonable limit on the complexity of optimized initializations. 4565 4566 //---------------------------InitializeNode------------------------------------ 4567 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop) 4568 : MemBarNode(C, adr_type, rawoop), 4569 _is_complete(Incomplete), _does_not_escape(false) 4570 { 4571 init_class_id(Class_Initialize); 4572 4573 assert(adr_type == Compile::AliasIdxRaw, "only valid atp"); 4574 assert(in(RawAddress) == rawoop, "proper init"); 4575 // Note: allocation() can be null, for secondary initialization barriers 4576 } 4577 4578 // Since this node is not matched, it will be processed by the 4579 // register allocator. Declare that there are no constraints 4580 // on the allocation of the RawAddress edge. 4581 const RegMask &InitializeNode::in_RegMask(uint idx) const { 4582 // This edge should be set to top, by the set_complete. But be conservative. 4583 if (idx == InitializeNode::RawAddress) 4584 return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]); 4585 return RegMask::Empty; 4586 } 4587 4588 Node* InitializeNode::memory(uint alias_idx) { 4589 Node* mem = in(Memory); 4590 if (mem->is_MergeMem()) { 4591 return mem->as_MergeMem()->memory_at(alias_idx); 4592 } else { 4593 // incoming raw memory is not split 4594 return mem; 4595 } 4596 } 4597 4598 bool InitializeNode::is_non_zero() { 4599 if (is_complete()) return false; 4600 remove_extra_zeroes(); 4601 return (req() > RawStores); 4602 } 4603 4604 void InitializeNode::set_complete(PhaseGVN* phase) { 4605 assert(!is_complete(), "caller responsibility"); 4606 _is_complete = Complete; 4607 4608 // After this node is complete, it contains a bunch of 4609 // raw-memory initializations. There is no need for 4610 // it to have anything to do with non-raw memory effects. 4611 // Therefore, tell all non-raw users to re-optimize themselves, 4612 // after skipping the memory effects of this initialization. 4613 PhaseIterGVN* igvn = phase->is_IterGVN(); 4614 if (igvn) igvn->add_users_to_worklist(this); 4615 } 4616 4617 // convenience function 4618 // return false if the init contains any stores already 4619 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) { 4620 InitializeNode* init = initialization(); 4621 if (init == nullptr || init->is_complete()) return false; 4622 init->remove_extra_zeroes(); 4623 // for now, if this allocation has already collected any inits, bail: 4624 if (init->is_non_zero()) return false; 4625 init->set_complete(phase); 4626 return true; 4627 } 4628 4629 void InitializeNode::remove_extra_zeroes() { 4630 if (req() == RawStores) return; 4631 Node* zmem = zero_memory(); 4632 uint fill = RawStores; 4633 for (uint i = fill; i < req(); i++) { 4634 Node* n = in(i); 4635 if (n->is_top() || n == zmem) continue; // skip 4636 if (fill < i) set_req(fill, n); // compact 4637 ++fill; 4638 } 4639 // delete any empty spaces created: 4640 while (fill < req()) { 4641 del_req(fill); 4642 } 4643 } 4644 4645 // Helper for remembering which stores go with which offsets. 4646 intptr_t InitializeNode::get_store_offset(Node* st, PhaseValues* phase) { 4647 if (!st->is_Store()) return -1; // can happen to dead code via subsume_node 4648 intptr_t offset = -1; 4649 Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address), 4650 phase, offset); 4651 if (base == nullptr) return -1; // something is dead, 4652 if (offset < 0) return -1; // dead, dead 4653 return offset; 4654 } 4655 4656 // Helper for proving that an initialization expression is 4657 // "simple enough" to be folded into an object initialization. 4658 // Attempts to prove that a store's initial value 'n' can be captured 4659 // within the initialization without creating a vicious cycle, such as: 4660 // { Foo p = new Foo(); p.next = p; } 4661 // True for constants and parameters and small combinations thereof. 4662 bool InitializeNode::detect_init_independence(Node* value, PhaseGVN* phase) { 4663 ResourceMark rm; 4664 Unique_Node_List worklist; 4665 worklist.push(value); 4666 4667 uint complexity_limit = 20; 4668 for (uint j = 0; j < worklist.size(); j++) { 4669 if (j >= complexity_limit) { 4670 return false; // Bail out if processed too many nodes 4671 } 4672 4673 Node* n = worklist.at(j); 4674 if (n == nullptr) continue; // (can this really happen?) 4675 if (n->is_Proj()) n = n->in(0); 4676 if (n == this) return false; // found a cycle 4677 if (n->is_Con()) continue; 4678 if (n->is_Start()) continue; // params, etc., are OK 4679 if (n->is_Root()) continue; // even better 4680 4681 // There cannot be any dependency if 'n' is a CFG node that dominates the current allocation 4682 if (n->is_CFG() && phase->is_dominator(n, allocation())) { 4683 continue; 4684 } 4685 4686 Node* ctl = n->in(0); 4687 if (ctl != nullptr && !ctl->is_top()) { 4688 if (ctl->is_Proj()) ctl = ctl->in(0); 4689 if (ctl == this) return false; 4690 4691 // If we already know that the enclosing memory op is pinned right after 4692 // the init, then any control flow that the store has picked up 4693 // must have preceded the init, or else be equal to the init. 4694 // Even after loop optimizations (which might change control edges) 4695 // a store is never pinned *before* the availability of its inputs. 4696 if (!MemNode::all_controls_dominate(n, this)) { 4697 return false; // failed to prove a good control 4698 } 4699 } 4700 4701 // Check data edges for possible dependencies on 'this'. 4702 for (uint i = 1; i < n->req(); i++) { 4703 Node* m = n->in(i); 4704 if (m == nullptr || m == n || m->is_top()) continue; 4705 4706 // Only process data inputs once 4707 worklist.push(m); 4708 } 4709 } 4710 4711 return true; 4712 } 4713 4714 // Here are all the checks a Store must pass before it can be moved into 4715 // an initialization. Returns zero if a check fails. 4716 // On success, returns the (constant) offset to which the store applies, 4717 // within the initialized memory. 4718 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseGVN* phase, bool can_reshape) { 4719 const int FAIL = 0; 4720 if (st->req() != MemNode::ValueIn + 1) 4721 return FAIL; // an inscrutable StoreNode (card mark?) 4722 Node* ctl = st->in(MemNode::Control); 4723 if (!(ctl != nullptr && ctl->is_Proj() && ctl->in(0) == this)) 4724 return FAIL; // must be unconditional after the initialization 4725 Node* mem = st->in(MemNode::Memory); 4726 if (!(mem->is_Proj() && mem->in(0) == this)) 4727 return FAIL; // must not be preceded by other stores 4728 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4729 if ((st->Opcode() == Op_StoreP || st->Opcode() == Op_StoreN) && 4730 !bs->can_initialize_object(st)) { 4731 return FAIL; 4732 } 4733 Node* adr = st->in(MemNode::Address); 4734 intptr_t offset; 4735 AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset); 4736 if (alloc == nullptr) 4737 return FAIL; // inscrutable address 4738 if (alloc != allocation()) 4739 return FAIL; // wrong allocation! (store needs to float up) 4740 int size_in_bytes = st->memory_size(); 4741 if ((size_in_bytes != 0) && (offset % size_in_bytes) != 0) { 4742 return FAIL; // mismatched access 4743 } 4744 Node* val = st->in(MemNode::ValueIn); 4745 4746 if (!detect_init_independence(val, phase)) 4747 return FAIL; // stored value must be 'simple enough' 4748 4749 // The Store can be captured only if nothing after the allocation 4750 // and before the Store is using the memory location that the store 4751 // overwrites. 4752 bool failed = false; 4753 // If is_complete_with_arraycopy() is true the shape of the graph is 4754 // well defined and is safe so no need for extra checks. 4755 if (!is_complete_with_arraycopy()) { 4756 // We are going to look at each use of the memory state following 4757 // the allocation to make sure nothing reads the memory that the 4758 // Store writes. 4759 const TypePtr* t_adr = phase->type(adr)->isa_ptr(); 4760 int alias_idx = phase->C->get_alias_index(t_adr); 4761 ResourceMark rm; 4762 Unique_Node_List mems; 4763 mems.push(mem); 4764 Node* unique_merge = nullptr; 4765 for (uint next = 0; next < mems.size(); ++next) { 4766 Node *m = mems.at(next); 4767 for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) { 4768 Node *n = m->fast_out(j); 4769 if (n->outcnt() == 0) { 4770 continue; 4771 } 4772 if (n == st) { 4773 continue; 4774 } else if (n->in(0) != nullptr && n->in(0) != ctl) { 4775 // If the control of this use is different from the control 4776 // of the Store which is right after the InitializeNode then 4777 // this node cannot be between the InitializeNode and the 4778 // Store. 4779 continue; 4780 } else if (n->is_MergeMem()) { 4781 if (n->as_MergeMem()->memory_at(alias_idx) == m) { 4782 // We can hit a MergeMemNode (that will likely go away 4783 // later) that is a direct use of the memory state 4784 // following the InitializeNode on the same slice as the 4785 // store node that we'd like to capture. We need to check 4786 // the uses of the MergeMemNode. 4787 mems.push(n); 4788 } 4789 } else if (n->is_Mem()) { 4790 Node* other_adr = n->in(MemNode::Address); 4791 if (other_adr == adr) { 4792 failed = true; 4793 break; 4794 } else { 4795 const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr(); 4796 if (other_t_adr != nullptr) { 4797 int other_alias_idx = phase->C->get_alias_index(other_t_adr); 4798 if (other_alias_idx == alias_idx) { 4799 // A load from the same memory slice as the store right 4800 // after the InitializeNode. We check the control of the 4801 // object/array that is loaded from. If it's the same as 4802 // the store control then we cannot capture the store. 4803 assert(!n->is_Store(), "2 stores to same slice on same control?"); 4804 Node* base = other_adr; 4805 assert(base->is_AddP(), "should be addp but is %s", base->Name()); 4806 base = base->in(AddPNode::Base); 4807 if (base != nullptr) { 4808 base = base->uncast(); 4809 if (base->is_Proj() && base->in(0) == alloc) { 4810 failed = true; 4811 break; 4812 } 4813 } 4814 } 4815 } 4816 } 4817 } else { 4818 failed = true; 4819 break; 4820 } 4821 } 4822 } 4823 } 4824 if (failed) { 4825 if (!can_reshape) { 4826 // We decided we couldn't capture the store during parsing. We 4827 // should try again during the next IGVN once the graph is 4828 // cleaner. 4829 phase->C->record_for_igvn(st); 4830 } 4831 return FAIL; 4832 } 4833 4834 return offset; // success 4835 } 4836 4837 // Find the captured store in(i) which corresponds to the range 4838 // [start..start+size) in the initialized object. 4839 // If there is one, return its index i. If there isn't, return the 4840 // negative of the index where it should be inserted. 4841 // Return 0 if the queried range overlaps an initialization boundary 4842 // or if dead code is encountered. 4843 // If size_in_bytes is zero, do not bother with overlap checks. 4844 int InitializeNode::captured_store_insertion_point(intptr_t start, 4845 int size_in_bytes, 4846 PhaseValues* phase) { 4847 const int FAIL = 0, MAX_STORE = MAX2(BytesPerLong, (int)MaxVectorSize); 4848 4849 if (is_complete()) 4850 return FAIL; // arraycopy got here first; punt 4851 4852 assert(allocation() != nullptr, "must be present"); 4853 4854 // no negatives, no header fields: 4855 if (start < (intptr_t) allocation()->minimum_header_size()) return FAIL; 4856 4857 // after a certain size, we bail out on tracking all the stores: 4858 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize); 4859 if (start >= ti_limit) return FAIL; 4860 4861 for (uint i = InitializeNode::RawStores, limit = req(); ; ) { 4862 if (i >= limit) return -(int)i; // not found; here is where to put it 4863 4864 Node* st = in(i); 4865 intptr_t st_off = get_store_offset(st, phase); 4866 if (st_off < 0) { 4867 if (st != zero_memory()) { 4868 return FAIL; // bail out if there is dead garbage 4869 } 4870 } else if (st_off > start) { 4871 // ...we are done, since stores are ordered 4872 if (st_off < start + size_in_bytes) { 4873 return FAIL; // the next store overlaps 4874 } 4875 return -(int)i; // not found; here is where to put it 4876 } else if (st_off < start) { 4877 assert(st->as_Store()->memory_size() <= MAX_STORE, ""); 4878 if (size_in_bytes != 0 && 4879 start < st_off + MAX_STORE && 4880 start < st_off + st->as_Store()->memory_size()) { 4881 return FAIL; // the previous store overlaps 4882 } 4883 } else { 4884 if (size_in_bytes != 0 && 4885 st->as_Store()->memory_size() != size_in_bytes) { 4886 return FAIL; // mismatched store size 4887 } 4888 return i; 4889 } 4890 4891 ++i; 4892 } 4893 } 4894 4895 // Look for a captured store which initializes at the offset 'start' 4896 // with the given size. If there is no such store, and no other 4897 // initialization interferes, then return zero_memory (the memory 4898 // projection of the AllocateNode). 4899 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes, 4900 PhaseValues* phase) { 4901 assert(stores_are_sane(phase), ""); 4902 int i = captured_store_insertion_point(start, size_in_bytes, phase); 4903 if (i == 0) { 4904 return nullptr; // something is dead 4905 } else if (i < 0) { 4906 return zero_memory(); // just primordial zero bits here 4907 } else { 4908 Node* st = in(i); // here is the store at this position 4909 assert(get_store_offset(st->as_Store(), phase) == start, "sanity"); 4910 return st; 4911 } 4912 } 4913 4914 // Create, as a raw pointer, an address within my new object at 'offset'. 4915 Node* InitializeNode::make_raw_address(intptr_t offset, 4916 PhaseGVN* phase) { 4917 Node* addr = in(RawAddress); 4918 if (offset != 0) { 4919 Compile* C = phase->C; 4920 addr = phase->transform( new AddPNode(C->top(), addr, 4921 phase->MakeConX(offset)) ); 4922 } 4923 return addr; 4924 } 4925 4926 // Clone the given store, converting it into a raw store 4927 // initializing a field or element of my new object. 4928 // Caller is responsible for retiring the original store, 4929 // with subsume_node or the like. 4930 // 4931 // From the example above InitializeNode::InitializeNode, 4932 // here are the old stores to be captured: 4933 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1) 4934 // store2 = (StoreC init.Control store1 (+ oop 14) 2) 4935 // 4936 // Here is the changed code; note the extra edges on init: 4937 // alloc = (Allocate ...) 4938 // rawoop = alloc.RawAddress 4939 // rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1) 4940 // rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2) 4941 // init = (Initialize alloc.Control alloc.Memory rawoop 4942 // rawstore1 rawstore2) 4943 // 4944 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start, 4945 PhaseGVN* phase, bool can_reshape) { 4946 assert(stores_are_sane(phase), ""); 4947 4948 if (start < 0) return nullptr; 4949 assert(can_capture_store(st, phase, can_reshape) == start, "sanity"); 4950 4951 Compile* C = phase->C; 4952 int size_in_bytes = st->memory_size(); 4953 int i = captured_store_insertion_point(start, size_in_bytes, phase); 4954 if (i == 0) return nullptr; // bail out 4955 Node* prev_mem = nullptr; // raw memory for the captured store 4956 if (i > 0) { 4957 prev_mem = in(i); // there is a pre-existing store under this one 4958 set_req(i, C->top()); // temporarily disconnect it 4959 // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect. 4960 } else { 4961 i = -i; // no pre-existing store 4962 prev_mem = zero_memory(); // a slice of the newly allocated object 4963 if (i > InitializeNode::RawStores && in(i-1) == prev_mem) 4964 set_req(--i, C->top()); // reuse this edge; it has been folded away 4965 else 4966 ins_req(i, C->top()); // build a new edge 4967 } 4968 Node* new_st = st->clone(); 4969 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2(); 4970 new_st->set_req(MemNode::Control, in(Control)); 4971 new_st->set_req(MemNode::Memory, prev_mem); 4972 new_st->set_req(MemNode::Address, make_raw_address(start, phase)); 4973 bs->eliminate_gc_barrier_data(new_st); 4974 new_st = phase->transform(new_st); 4975 4976 // At this point, new_st might have swallowed a pre-existing store 4977 // at the same offset, or perhaps new_st might have disappeared, 4978 // if it redundantly stored the same value (or zero to fresh memory). 4979 4980 // In any case, wire it in: 4981 PhaseIterGVN* igvn = phase->is_IterGVN(); 4982 if (igvn) { 4983 igvn->rehash_node_delayed(this); 4984 } 4985 set_req(i, new_st); 4986 4987 // The caller may now kill the old guy. 4988 DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase)); 4989 assert(check_st == new_st || check_st == nullptr, "must be findable"); 4990 assert(!is_complete(), ""); 4991 return new_st; 4992 } 4993 4994 static bool store_constant(jlong* tiles, int num_tiles, 4995 intptr_t st_off, int st_size, 4996 jlong con) { 4997 if ((st_off & (st_size-1)) != 0) 4998 return false; // strange store offset (assume size==2**N) 4999 address addr = (address)tiles + st_off; 5000 assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob"); 5001 switch (st_size) { 5002 case sizeof(jbyte): *(jbyte*) addr = (jbyte) con; break; 5003 case sizeof(jchar): *(jchar*) addr = (jchar) con; break; 5004 case sizeof(jint): *(jint*) addr = (jint) con; break; 5005 case sizeof(jlong): *(jlong*) addr = (jlong) con; break; 5006 default: return false; // strange store size (detect size!=2**N here) 5007 } 5008 return true; // return success to caller 5009 } 5010 5011 // Coalesce subword constants into int constants and possibly 5012 // into long constants. The goal, if the CPU permits, 5013 // is to initialize the object with a small number of 64-bit tiles. 5014 // Also, convert floating-point constants to bit patterns. 5015 // Non-constants are not relevant to this pass. 5016 // 5017 // In terms of the running example on InitializeNode::InitializeNode 5018 // and InitializeNode::capture_store, here is the transformation 5019 // of rawstore1 and rawstore2 into rawstore12: 5020 // alloc = (Allocate ...) 5021 // rawoop = alloc.RawAddress 5022 // tile12 = 0x00010002 5023 // rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12) 5024 // init = (Initialize alloc.Control alloc.Memory rawoop rawstore12) 5025 // 5026 void 5027 InitializeNode::coalesce_subword_stores(intptr_t header_size, 5028 Node* size_in_bytes, 5029 PhaseGVN* phase) { 5030 Compile* C = phase->C; 5031 5032 assert(stores_are_sane(phase), ""); 5033 // Note: After this pass, they are not completely sane, 5034 // since there may be some overlaps. 5035 5036 int old_subword = 0, old_long = 0, new_int = 0, new_long = 0; 5037 5038 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize); 5039 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit); 5040 size_limit = MIN2(size_limit, ti_limit); 5041 size_limit = align_up(size_limit, BytesPerLong); 5042 int num_tiles = size_limit / BytesPerLong; 5043 5044 // allocate space for the tile map: 5045 const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small 5046 jlong tiles_buf[small_len]; 5047 Node* nodes_buf[small_len]; 5048 jlong inits_buf[small_len]; 5049 jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0] 5050 : NEW_RESOURCE_ARRAY(jlong, num_tiles)); 5051 Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0] 5052 : NEW_RESOURCE_ARRAY(Node*, num_tiles)); 5053 jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0] 5054 : NEW_RESOURCE_ARRAY(jlong, num_tiles)); 5055 // tiles: exact bitwise model of all primitive constants 5056 // nodes: last constant-storing node subsumed into the tiles model 5057 // inits: which bytes (in each tile) are touched by any initializations 5058 5059 //// Pass A: Fill in the tile model with any relevant stores. 5060 5061 Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles); 5062 Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles); 5063 Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles); 5064 Node* zmem = zero_memory(); // initially zero memory state 5065 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) { 5066 Node* st = in(i); 5067 intptr_t st_off = get_store_offset(st, phase); 5068 5069 // Figure out the store's offset and constant value: 5070 if (st_off < header_size) continue; //skip (ignore header) 5071 if (st->in(MemNode::Memory) != zmem) continue; //skip (odd store chain) 5072 int st_size = st->as_Store()->memory_size(); 5073 if (st_off + st_size > size_limit) break; 5074 5075 // Record which bytes are touched, whether by constant or not. 5076 if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1)) 5077 continue; // skip (strange store size) 5078 5079 const Type* val = phase->type(st->in(MemNode::ValueIn)); 5080 if (!val->singleton()) continue; //skip (non-con store) 5081 BasicType type = val->basic_type(); 5082 5083 jlong con = 0; 5084 switch (type) { 5085 case T_INT: con = val->is_int()->get_con(); break; 5086 case T_LONG: con = val->is_long()->get_con(); break; 5087 case T_FLOAT: con = jint_cast(val->getf()); break; 5088 case T_DOUBLE: con = jlong_cast(val->getd()); break; 5089 default: continue; //skip (odd store type) 5090 } 5091 5092 if (type == T_LONG && Matcher::isSimpleConstant64(con) && 5093 st->Opcode() == Op_StoreL) { 5094 continue; // This StoreL is already optimal. 5095 } 5096 5097 // Store down the constant. 5098 store_constant(tiles, num_tiles, st_off, st_size, con); 5099 5100 intptr_t j = st_off >> LogBytesPerLong; 5101 5102 if (type == T_INT && st_size == BytesPerInt 5103 && (st_off & BytesPerInt) == BytesPerInt) { 5104 jlong lcon = tiles[j]; 5105 if (!Matcher::isSimpleConstant64(lcon) && 5106 st->Opcode() == Op_StoreI) { 5107 // This StoreI is already optimal by itself. 5108 jint* intcon = (jint*) &tiles[j]; 5109 intcon[1] = 0; // undo the store_constant() 5110 5111 // If the previous store is also optimal by itself, back up and 5112 // undo the action of the previous loop iteration... if we can. 5113 // But if we can't, just let the previous half take care of itself. 5114 st = nodes[j]; 5115 st_off -= BytesPerInt; 5116 con = intcon[0]; 5117 if (con != 0 && st != nullptr && st->Opcode() == Op_StoreI) { 5118 assert(st_off >= header_size, "still ignoring header"); 5119 assert(get_store_offset(st, phase) == st_off, "must be"); 5120 assert(in(i-1) == zmem, "must be"); 5121 DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn))); 5122 assert(con == tcon->is_int()->get_con(), "must be"); 5123 // Undo the effects of the previous loop trip, which swallowed st: 5124 intcon[0] = 0; // undo store_constant() 5125 set_req(i-1, st); // undo set_req(i, zmem) 5126 nodes[j] = nullptr; // undo nodes[j] = st 5127 --old_subword; // undo ++old_subword 5128 } 5129 continue; // This StoreI is already optimal. 5130 } 5131 } 5132 5133 // This store is not needed. 5134 set_req(i, zmem); 5135 nodes[j] = st; // record for the moment 5136 if (st_size < BytesPerLong) // something has changed 5137 ++old_subword; // includes int/float, but who's counting... 5138 else ++old_long; 5139 } 5140 5141 if ((old_subword + old_long) == 0) 5142 return; // nothing more to do 5143 5144 //// Pass B: Convert any non-zero tiles into optimal constant stores. 5145 // Be sure to insert them before overlapping non-constant stores. 5146 // (E.g., byte[] x = { 1,2,y,4 } => x[int 0] = 0x01020004, x[2]=y.) 5147 for (int j = 0; j < num_tiles; j++) { 5148 jlong con = tiles[j]; 5149 jlong init = inits[j]; 5150 if (con == 0) continue; 5151 jint con0, con1; // split the constant, address-wise 5152 jint init0, init1; // split the init map, address-wise 5153 { union { jlong con; jint intcon[2]; } u; 5154 u.con = con; 5155 con0 = u.intcon[0]; 5156 con1 = u.intcon[1]; 5157 u.con = init; 5158 init0 = u.intcon[0]; 5159 init1 = u.intcon[1]; 5160 } 5161 5162 Node* old = nodes[j]; 5163 assert(old != nullptr, "need the prior store"); 5164 intptr_t offset = (j * BytesPerLong); 5165 5166 bool split = !Matcher::isSimpleConstant64(con); 5167 5168 if (offset < header_size) { 5169 assert(offset + BytesPerInt >= header_size, "second int counts"); 5170 assert(*(jint*)&tiles[j] == 0, "junk in header"); 5171 split = true; // only the second word counts 5172 // Example: int a[] = { 42 ... } 5173 } else if (con0 == 0 && init0 == -1) { 5174 split = true; // first word is covered by full inits 5175 // Example: int a[] = { ... foo(), 42 ... } 5176 } else if (con1 == 0 && init1 == -1) { 5177 split = true; // second word is covered by full inits 5178 // Example: int a[] = { ... 42, foo() ... } 5179 } 5180 5181 // Here's a case where init0 is neither 0 nor -1: 5182 // byte a[] = { ... 0,0,foo(),0, 0,0,0,42 ... } 5183 // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF. 5184 // In this case the tile is not split; it is (jlong)42. 5185 // The big tile is stored down, and then the foo() value is inserted. 5186 // (If there were foo(),foo() instead of foo(),0, init0 would be -1.) 5187 5188 Node* ctl = old->in(MemNode::Control); 5189 Node* adr = make_raw_address(offset, phase); 5190 const TypePtr* atp = TypeRawPtr::BOTTOM; 5191 5192 // One or two coalesced stores to plop down. 5193 Node* st[2]; 5194 intptr_t off[2]; 5195 int nst = 0; 5196 if (!split) { 5197 ++new_long; 5198 off[nst] = offset; 5199 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 5200 phase->longcon(con), T_LONG, MemNode::unordered); 5201 } else { 5202 // Omit either if it is a zero. 5203 if (con0 != 0) { 5204 ++new_int; 5205 off[nst] = offset; 5206 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 5207 phase->intcon(con0), T_INT, MemNode::unordered); 5208 } 5209 if (con1 != 0) { 5210 ++new_int; 5211 offset += BytesPerInt; 5212 adr = make_raw_address(offset, phase); 5213 off[nst] = offset; 5214 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp, 5215 phase->intcon(con1), T_INT, MemNode::unordered); 5216 } 5217 } 5218 5219 // Insert second store first, then the first before the second. 5220 // Insert each one just before any overlapping non-constant stores. 5221 while (nst > 0) { 5222 Node* st1 = st[--nst]; 5223 C->copy_node_notes_to(st1, old); 5224 st1 = phase->transform(st1); 5225 offset = off[nst]; 5226 assert(offset >= header_size, "do not smash header"); 5227 int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase); 5228 guarantee(ins_idx != 0, "must re-insert constant store"); 5229 if (ins_idx < 0) ins_idx = -ins_idx; // never overlap 5230 if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem) 5231 set_req(--ins_idx, st1); 5232 else 5233 ins_req(ins_idx, st1); 5234 } 5235 } 5236 5237 if (PrintCompilation && WizardMode) 5238 tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long", 5239 old_subword, old_long, new_int, new_long); 5240 if (C->log() != nullptr) 5241 C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'", 5242 old_subword, old_long, new_int, new_long); 5243 5244 // Clean up any remaining occurrences of zmem: 5245 remove_extra_zeroes(); 5246 } 5247 5248 // Explore forward from in(start) to find the first fully initialized 5249 // word, and return its offset. Skip groups of subword stores which 5250 // together initialize full words. If in(start) is itself part of a 5251 // fully initialized word, return the offset of in(start). If there 5252 // are no following full-word stores, or if something is fishy, return 5253 // a negative value. 5254 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) { 5255 int int_map = 0; 5256 intptr_t int_map_off = 0; 5257 const int FULL_MAP = right_n_bits(BytesPerInt); // the int_map we hope for 5258 5259 for (uint i = start, limit = req(); i < limit; i++) { 5260 Node* st = in(i); 5261 5262 intptr_t st_off = get_store_offset(st, phase); 5263 if (st_off < 0) break; // return conservative answer 5264 5265 int st_size = st->as_Store()->memory_size(); 5266 if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) { 5267 return st_off; // we found a complete word init 5268 } 5269 5270 // update the map: 5271 5272 intptr_t this_int_off = align_down(st_off, BytesPerInt); 5273 if (this_int_off != int_map_off) { 5274 // reset the map: 5275 int_map = 0; 5276 int_map_off = this_int_off; 5277 } 5278 5279 int subword_off = st_off - this_int_off; 5280 int_map |= right_n_bits(st_size) << subword_off; 5281 if ((int_map & FULL_MAP) == FULL_MAP) { 5282 return this_int_off; // we found a complete word init 5283 } 5284 5285 // Did this store hit or cross the word boundary? 5286 intptr_t next_int_off = align_down(st_off + st_size, BytesPerInt); 5287 if (next_int_off == this_int_off + BytesPerInt) { 5288 // We passed the current int, without fully initializing it. 5289 int_map_off = next_int_off; 5290 int_map >>= BytesPerInt; 5291 } else if (next_int_off > this_int_off + BytesPerInt) { 5292 // We passed the current and next int. 5293 return this_int_off + BytesPerInt; 5294 } 5295 } 5296 5297 return -1; 5298 } 5299 5300 5301 // Called when the associated AllocateNode is expanded into CFG. 5302 // At this point, we may perform additional optimizations. 5303 // Linearize the stores by ascending offset, to make memory 5304 // activity as coherent as possible. 5305 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr, 5306 intptr_t header_size, 5307 Node* size_in_bytes, 5308 PhaseIterGVN* phase) { 5309 assert(!is_complete(), "not already complete"); 5310 assert(stores_are_sane(phase), ""); 5311 assert(allocation() != nullptr, "must be present"); 5312 5313 remove_extra_zeroes(); 5314 5315 if (ReduceFieldZeroing || ReduceBulkZeroing) 5316 // reduce instruction count for common initialization patterns 5317 coalesce_subword_stores(header_size, size_in_bytes, phase); 5318 5319 Node* zmem = zero_memory(); // initially zero memory state 5320 Node* inits = zmem; // accumulating a linearized chain of inits 5321 #ifdef ASSERT 5322 intptr_t first_offset = allocation()->minimum_header_size(); 5323 intptr_t last_init_off = first_offset; // previous init offset 5324 intptr_t last_init_end = first_offset; // previous init offset+size 5325 intptr_t last_tile_end = first_offset; // previous tile offset+size 5326 #endif 5327 intptr_t zeroes_done = header_size; 5328 5329 bool do_zeroing = true; // we might give up if inits are very sparse 5330 int big_init_gaps = 0; // how many large gaps have we seen? 5331 5332 if (UseTLAB && ZeroTLAB) do_zeroing = false; 5333 if (!ReduceFieldZeroing && !ReduceBulkZeroing) do_zeroing = false; 5334 5335 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) { 5336 Node* st = in(i); 5337 intptr_t st_off = get_store_offset(st, phase); 5338 if (st_off < 0) 5339 break; // unknown junk in the inits 5340 if (st->in(MemNode::Memory) != zmem) 5341 break; // complicated store chains somehow in list 5342 5343 int st_size = st->as_Store()->memory_size(); 5344 intptr_t next_init_off = st_off + st_size; 5345 5346 if (do_zeroing && zeroes_done < next_init_off) { 5347 // See if this store needs a zero before it or under it. 5348 intptr_t zeroes_needed = st_off; 5349 5350 if (st_size < BytesPerInt) { 5351 // Look for subword stores which only partially initialize words. 5352 // If we find some, we must lay down some word-level zeroes first, 5353 // underneath the subword stores. 5354 // 5355 // Examples: 5356 // byte[] a = { p,q,r,s } => a[0]=p,a[1]=q,a[2]=r,a[3]=s 5357 // byte[] a = { x,y,0,0 } => a[0..3] = 0, a[0]=x,a[1]=y 5358 // byte[] a = { 0,0,z,0 } => a[0..3] = 0, a[2]=z 5359 // 5360 // Note: coalesce_subword_stores may have already done this, 5361 // if it was prompted by constant non-zero subword initializers. 5362 // But this case can still arise with non-constant stores. 5363 5364 intptr_t next_full_store = find_next_fullword_store(i, phase); 5365 5366 // In the examples above: 5367 // in(i) p q r s x y z 5368 // st_off 12 13 14 15 12 13 14 5369 // st_size 1 1 1 1 1 1 1 5370 // next_full_s. 12 16 16 16 16 16 16 5371 // z's_done 12 16 16 16 12 16 12 5372 // z's_needed 12 16 16 16 16 16 16 5373 // zsize 0 0 0 0 4 0 4 5374 if (next_full_store < 0) { 5375 // Conservative tack: Zero to end of current word. 5376 zeroes_needed = align_up(zeroes_needed, BytesPerInt); 5377 } else { 5378 // Zero to beginning of next fully initialized word. 5379 // Or, don't zero at all, if we are already in that word. 5380 assert(next_full_store >= zeroes_needed, "must go forward"); 5381 assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary"); 5382 zeroes_needed = next_full_store; 5383 } 5384 } 5385 5386 if (zeroes_needed > zeroes_done) { 5387 intptr_t zsize = zeroes_needed - zeroes_done; 5388 // Do some incremental zeroing on rawmem, in parallel with inits. 5389 zeroes_done = align_down(zeroes_done, BytesPerInt); 5390 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr, 5391 zeroes_done, zeroes_needed, 5392 phase); 5393 zeroes_done = zeroes_needed; 5394 if (zsize > InitArrayShortSize && ++big_init_gaps > 2) 5395 do_zeroing = false; // leave the hole, next time 5396 } 5397 } 5398 5399 // Collect the store and move on: 5400 phase->replace_input_of(st, MemNode::Memory, inits); 5401 inits = st; // put it on the linearized chain 5402 set_req(i, zmem); // unhook from previous position 5403 5404 if (zeroes_done == st_off) 5405 zeroes_done = next_init_off; 5406 5407 assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any"); 5408 5409 #ifdef ASSERT 5410 // Various order invariants. Weaker than stores_are_sane because 5411 // a large constant tile can be filled in by smaller non-constant stores. 5412 assert(st_off >= last_init_off, "inits do not reverse"); 5413 last_init_off = st_off; 5414 const Type* val = nullptr; 5415 if (st_size >= BytesPerInt && 5416 (val = phase->type(st->in(MemNode::ValueIn)))->singleton() && 5417 (int)val->basic_type() < (int)T_OBJECT) { 5418 assert(st_off >= last_tile_end, "tiles do not overlap"); 5419 assert(st_off >= last_init_end, "tiles do not overwrite inits"); 5420 last_tile_end = MAX2(last_tile_end, next_init_off); 5421 } else { 5422 intptr_t st_tile_end = align_up(next_init_off, BytesPerLong); 5423 assert(st_tile_end >= last_tile_end, "inits stay with tiles"); 5424 assert(st_off >= last_init_end, "inits do not overlap"); 5425 last_init_end = next_init_off; // it's a non-tile 5426 } 5427 #endif //ASSERT 5428 } 5429 5430 remove_extra_zeroes(); // clear out all the zmems left over 5431 add_req(inits); 5432 5433 if (!(UseTLAB && ZeroTLAB)) { 5434 // If anything remains to be zeroed, zero it all now. 5435 zeroes_done = align_down(zeroes_done, BytesPerInt); 5436 // if it is the last unused 4 bytes of an instance, forget about it 5437 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint); 5438 if (zeroes_done + BytesPerLong >= size_limit) { 5439 AllocateNode* alloc = allocation(); 5440 assert(alloc != nullptr, "must be present"); 5441 if (alloc != nullptr && alloc->Opcode() == Op_Allocate) { 5442 Node* klass_node = alloc->in(AllocateNode::KlassNode); 5443 ciKlass* k = phase->type(klass_node)->is_instklassptr()->instance_klass(); 5444 if (zeroes_done == k->layout_helper()) 5445 zeroes_done = size_limit; 5446 } 5447 } 5448 if (zeroes_done < size_limit) { 5449 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr, 5450 zeroes_done, size_in_bytes, phase); 5451 } 5452 } 5453 5454 set_complete(phase); 5455 return rawmem; 5456 } 5457 5458 5459 #ifdef ASSERT 5460 bool InitializeNode::stores_are_sane(PhaseValues* phase) { 5461 if (is_complete()) 5462 return true; // stores could be anything at this point 5463 assert(allocation() != nullptr, "must be present"); 5464 intptr_t last_off = allocation()->minimum_header_size(); 5465 for (uint i = InitializeNode::RawStores; i < req(); i++) { 5466 Node* st = in(i); 5467 intptr_t st_off = get_store_offset(st, phase); 5468 if (st_off < 0) continue; // ignore dead garbage 5469 if (last_off > st_off) { 5470 tty->print_cr("*** bad store offset at %d: %zd > %zd", i, last_off, st_off); 5471 this->dump(2); 5472 assert(false, "ascending store offsets"); 5473 return false; 5474 } 5475 last_off = st_off + st->as_Store()->memory_size(); 5476 } 5477 return true; 5478 } 5479 #endif //ASSERT 5480 5481 5482 5483 5484 //============================MergeMemNode===================================== 5485 // 5486 // SEMANTICS OF MEMORY MERGES: A MergeMem is a memory state assembled from several 5487 // contributing store or call operations. Each contributor provides the memory 5488 // state for a particular "alias type" (see Compile::alias_type). For example, 5489 // if a MergeMem has an input X for alias category #6, then any memory reference 5490 // to alias category #6 may use X as its memory state input, as an exact equivalent 5491 // to using the MergeMem as a whole. 5492 // Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p) 5493 // 5494 // (Here, the <N> notation gives the index of the relevant adr_type.) 5495 // 5496 // In one special case (and more cases in the future), alias categories overlap. 5497 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory 5498 // states. Therefore, if a MergeMem has only one contributing input W for Bot, 5499 // it is exactly equivalent to that state W: 5500 // MergeMem(<Bot>: W) <==> W 5501 // 5502 // Usually, the merge has more than one input. In that case, where inputs 5503 // overlap (i.e., one is Bot), the narrower alias type determines the memory 5504 // state for that type, and the wider alias type (Bot) fills in everywhere else: 5505 // Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p) 5506 // Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p) 5507 // 5508 // A merge can take a "wide" memory state as one of its narrow inputs. 5509 // This simply means that the merge observes out only the relevant parts of 5510 // the wide input. That is, wide memory states arriving at narrow merge inputs 5511 // are implicitly "filtered" or "sliced" as necessary. (This is rare.) 5512 // 5513 // These rules imply that MergeMem nodes may cascade (via their <Bot> links), 5514 // and that memory slices "leak through": 5515 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y) 5516 // 5517 // But, in such a cascade, repeated memory slices can "block the leak": 5518 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y') 5519 // 5520 // In the last example, Y is not part of the combined memory state of the 5521 // outermost MergeMem. The system must, of course, prevent unschedulable 5522 // memory states from arising, so you can be sure that the state Y is somehow 5523 // a precursor to state Y'. 5524 // 5525 // 5526 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array 5527 // of each MergeMemNode array are exactly the numerical alias indexes, including 5528 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw. The functions 5529 // Compile::alias_type (and kin) produce and manage these indexes. 5530 // 5531 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node. 5532 // (Note that this provides quick access to the top node inside MergeMem methods, 5533 // without the need to reach out via TLS to Compile::current.) 5534 // 5535 // As a consequence of what was just described, a MergeMem that represents a full 5536 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state, 5537 // containing all alias categories. 5538 // 5539 // MergeMem nodes never (?) have control inputs, so in(0) is null. 5540 // 5541 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either 5542 // a memory state for the alias type <N>, or else the top node, meaning that 5543 // there is no particular input for that alias type. Note that the length of 5544 // a MergeMem is variable, and may be extended at any time to accommodate new 5545 // memory states at larger alias indexes. When merges grow, they are of course 5546 // filled with "top" in the unused in() positions. 5547 // 5548 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable. 5549 // (Top was chosen because it works smoothly with passes like GCM.) 5550 // 5551 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM. (It is 5552 // the type of random VM bits like TLS references.) Since it is always the 5553 // first non-Bot memory slice, some low-level loops use it to initialize an 5554 // index variable: for (i = AliasIdxRaw; i < req(); i++). 5555 // 5556 // 5557 // ACCESSORS: There is a special accessor MergeMemNode::base_memory which returns 5558 // the distinguished "wide" state. The accessor MergeMemNode::memory_at(N) returns 5559 // the memory state for alias type <N>, or (if there is no particular slice at <N>, 5560 // it returns the base memory. To prevent bugs, memory_at does not accept <Top> 5561 // or <Bot> indexes. The iterator MergeMemStream provides robust iteration over 5562 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited. 5563 // 5564 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't 5565 // really that different from the other memory inputs. An abbreviation called 5566 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy. 5567 // 5568 // 5569 // PARTIAL MEMORY STATES: During optimization, MergeMem nodes may arise that represent 5570 // partial memory states. When a Phi splits through a MergeMem, the copy of the Phi 5571 // that "emerges though" the base memory will be marked as excluding the alias types 5572 // of the other (narrow-memory) copies which "emerged through" the narrow edges: 5573 // 5574 // Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y)) 5575 // ==Ideal=> MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y)) 5576 // 5577 // This strange "subtraction" effect is necessary to ensure IGVN convergence. 5578 // (It is currently unimplemented.) As you can see, the resulting merge is 5579 // actually a disjoint union of memory states, rather than an overlay. 5580 // 5581 5582 //------------------------------MergeMemNode----------------------------------- 5583 Node* MergeMemNode::make_empty_memory() { 5584 Node* empty_memory = (Node*) Compile::current()->top(); 5585 assert(empty_memory->is_top(), "correct sentinel identity"); 5586 return empty_memory; 5587 } 5588 5589 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) { 5590 init_class_id(Class_MergeMem); 5591 // all inputs are nullified in Node::Node(int) 5592 // set_input(0, nullptr); // no control input 5593 5594 // Initialize the edges uniformly to top, for starters. 5595 Node* empty_mem = make_empty_memory(); 5596 for (uint i = Compile::AliasIdxTop; i < req(); i++) { 5597 init_req(i,empty_mem); 5598 } 5599 assert(empty_memory() == empty_mem, ""); 5600 5601 if( new_base != nullptr && new_base->is_MergeMem() ) { 5602 MergeMemNode* mdef = new_base->as_MergeMem(); 5603 assert(mdef->empty_memory() == empty_mem, "consistent sentinels"); 5604 for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) { 5605 mms.set_memory(mms.memory2()); 5606 } 5607 assert(base_memory() == mdef->base_memory(), ""); 5608 } else { 5609 set_base_memory(new_base); 5610 } 5611 } 5612 5613 // Make a new, untransformed MergeMem with the same base as 'mem'. 5614 // If mem is itself a MergeMem, populate the result with the same edges. 5615 MergeMemNode* MergeMemNode::make(Node* mem) { 5616 return new MergeMemNode(mem); 5617 } 5618 5619 //------------------------------cmp-------------------------------------------- 5620 uint MergeMemNode::hash() const { return NO_HASH; } 5621 bool MergeMemNode::cmp( const Node &n ) const { 5622 return (&n == this); // Always fail except on self 5623 } 5624 5625 //------------------------------Identity--------------------------------------- 5626 Node* MergeMemNode::Identity(PhaseGVN* phase) { 5627 // Identity if this merge point does not record any interesting memory 5628 // disambiguations. 5629 Node* base_mem = base_memory(); 5630 Node* empty_mem = empty_memory(); 5631 if (base_mem != empty_mem) { // Memory path is not dead? 5632 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5633 Node* mem = in(i); 5634 if (mem != empty_mem && mem != base_mem) { 5635 return this; // Many memory splits; no change 5636 } 5637 } 5638 } 5639 return base_mem; // No memory splits; ID on the one true input 5640 } 5641 5642 //------------------------------Ideal------------------------------------------ 5643 // This method is invoked recursively on chains of MergeMem nodes 5644 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) { 5645 // Remove chain'd MergeMems 5646 // 5647 // This is delicate, because the each "in(i)" (i >= Raw) is interpreted 5648 // relative to the "in(Bot)". Since we are patching both at the same time, 5649 // we have to be careful to read each "in(i)" relative to the old "in(Bot)", 5650 // but rewrite each "in(i)" relative to the new "in(Bot)". 5651 Node *progress = nullptr; 5652 5653 5654 Node* old_base = base_memory(); 5655 Node* empty_mem = empty_memory(); 5656 if (old_base == empty_mem) 5657 return nullptr; // Dead memory path. 5658 5659 MergeMemNode* old_mbase; 5660 if (old_base != nullptr && old_base->is_MergeMem()) 5661 old_mbase = old_base->as_MergeMem(); 5662 else 5663 old_mbase = nullptr; 5664 Node* new_base = old_base; 5665 5666 // simplify stacked MergeMems in base memory 5667 if (old_mbase) new_base = old_mbase->base_memory(); 5668 5669 // the base memory might contribute new slices beyond my req() 5670 if (old_mbase) grow_to_match(old_mbase); 5671 5672 // Note: We do not call verify_sparse on entry, because inputs 5673 // can normalize to the base_memory via subsume_node or similar 5674 // mechanisms. This method repairs that damage. 5675 5676 assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels"); 5677 5678 // Look at each slice. 5679 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5680 Node* old_in = in(i); 5681 // calculate the old memory value 5682 Node* old_mem = old_in; 5683 if (old_mem == empty_mem) old_mem = old_base; 5684 assert(old_mem == memory_at(i), ""); 5685 5686 // maybe update (reslice) the old memory value 5687 5688 // simplify stacked MergeMems 5689 Node* new_mem = old_mem; 5690 MergeMemNode* old_mmem; 5691 if (old_mem != nullptr && old_mem->is_MergeMem()) 5692 old_mmem = old_mem->as_MergeMem(); 5693 else 5694 old_mmem = nullptr; 5695 if (old_mmem == this) { 5696 // This can happen if loops break up and safepoints disappear. 5697 // A merge of BotPtr (default) with a RawPtr memory derived from a 5698 // safepoint can be rewritten to a merge of the same BotPtr with 5699 // the BotPtr phi coming into the loop. If that phi disappears 5700 // also, we can end up with a self-loop of the mergemem. 5701 // In general, if loops degenerate and memory effects disappear, 5702 // a mergemem can be left looking at itself. This simply means 5703 // that the mergemem's default should be used, since there is 5704 // no longer any apparent effect on this slice. 5705 // Note: If a memory slice is a MergeMem cycle, it is unreachable 5706 // from start. Update the input to TOP. 5707 new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base; 5708 } 5709 else if (old_mmem != nullptr) { 5710 new_mem = old_mmem->memory_at(i); 5711 } 5712 // else preceding memory was not a MergeMem 5713 5714 // maybe store down a new value 5715 Node* new_in = new_mem; 5716 if (new_in == new_base) new_in = empty_mem; 5717 5718 if (new_in != old_in) { 5719 // Warning: Do not combine this "if" with the previous "if" 5720 // A memory slice might have be be rewritten even if it is semantically 5721 // unchanged, if the base_memory value has changed. 5722 set_req_X(i, new_in, phase); 5723 progress = this; // Report progress 5724 } 5725 } 5726 5727 if (new_base != old_base) { 5728 set_req_X(Compile::AliasIdxBot, new_base, phase); 5729 // Don't use set_base_memory(new_base), because we need to update du. 5730 assert(base_memory() == new_base, ""); 5731 progress = this; 5732 } 5733 5734 if( base_memory() == this ) { 5735 // a self cycle indicates this memory path is dead 5736 set_req(Compile::AliasIdxBot, empty_mem); 5737 } 5738 5739 // Resolve external cycles by calling Ideal on a MergeMem base_memory 5740 // Recursion must occur after the self cycle check above 5741 if( base_memory()->is_MergeMem() ) { 5742 MergeMemNode *new_mbase = base_memory()->as_MergeMem(); 5743 Node *m = phase->transform(new_mbase); // Rollup any cycles 5744 if( m != nullptr && 5745 (m->is_top() || 5746 (m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem)) ) { 5747 // propagate rollup of dead cycle to self 5748 set_req(Compile::AliasIdxBot, empty_mem); 5749 } 5750 } 5751 5752 if( base_memory() == empty_mem ) { 5753 progress = this; 5754 // Cut inputs during Parse phase only. 5755 // During Optimize phase a dead MergeMem node will be subsumed by Top. 5756 if( !can_reshape ) { 5757 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5758 if( in(i) != empty_mem ) { set_req(i, empty_mem); } 5759 } 5760 } 5761 } 5762 5763 if( !progress && base_memory()->is_Phi() && can_reshape ) { 5764 // Check if PhiNode::Ideal's "Split phis through memory merges" 5765 // transform should be attempted. Look for this->phi->this cycle. 5766 uint merge_width = req(); 5767 if (merge_width > Compile::AliasIdxRaw) { 5768 PhiNode* phi = base_memory()->as_Phi(); 5769 for( uint i = 1; i < phi->req(); ++i ) {// For all paths in 5770 if (phi->in(i) == this) { 5771 phase->is_IterGVN()->_worklist.push(phi); 5772 break; 5773 } 5774 } 5775 } 5776 } 5777 5778 assert(progress || verify_sparse(), "please, no dups of base"); 5779 return progress; 5780 } 5781 5782 //-------------------------set_base_memory------------------------------------- 5783 void MergeMemNode::set_base_memory(Node *new_base) { 5784 Node* empty_mem = empty_memory(); 5785 set_req(Compile::AliasIdxBot, new_base); 5786 assert(memory_at(req()) == new_base, "must set default memory"); 5787 // Clear out other occurrences of new_base: 5788 if (new_base != empty_mem) { 5789 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5790 if (in(i) == new_base) set_req(i, empty_mem); 5791 } 5792 } 5793 } 5794 5795 //------------------------------out_RegMask------------------------------------ 5796 const RegMask &MergeMemNode::out_RegMask() const { 5797 return RegMask::Empty; 5798 } 5799 5800 //------------------------------dump_spec-------------------------------------- 5801 #ifndef PRODUCT 5802 void MergeMemNode::dump_spec(outputStream *st) const { 5803 st->print(" {"); 5804 Node* base_mem = base_memory(); 5805 for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) { 5806 Node* mem = (in(i) != nullptr) ? memory_at(i) : base_mem; 5807 if (mem == base_mem) { st->print(" -"); continue; } 5808 st->print( " N%d:", mem->_idx ); 5809 Compile::current()->get_adr_type(i)->dump_on(st); 5810 } 5811 st->print(" }"); 5812 } 5813 #endif // !PRODUCT 5814 5815 5816 #ifdef ASSERT 5817 static bool might_be_same(Node* a, Node* b) { 5818 if (a == b) return true; 5819 if (!(a->is_Phi() || b->is_Phi())) return false; 5820 // phis shift around during optimization 5821 return true; // pretty stupid... 5822 } 5823 5824 // verify a narrow slice (either incoming or outgoing) 5825 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) { 5826 if (!VerifyAliases) return; // don't bother to verify unless requested 5827 if (VMError::is_error_reported()) return; // muzzle asserts when debugging an error 5828 if (Node::in_dump()) return; // muzzle asserts when printing 5829 assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel"); 5830 assert(n != nullptr, ""); 5831 // Elide intervening MergeMem's 5832 while (n->is_MergeMem()) { 5833 n = n->as_MergeMem()->memory_at(alias_idx); 5834 } 5835 Compile* C = Compile::current(); 5836 const TypePtr* n_adr_type = n->adr_type(); 5837 if (n == m->empty_memory()) { 5838 // Implicit copy of base_memory() 5839 } else if (n_adr_type != TypePtr::BOTTOM) { 5840 assert(n_adr_type != nullptr, "new memory must have a well-defined adr_type"); 5841 assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice"); 5842 } else { 5843 // A few places like make_runtime_call "know" that VM calls are narrow, 5844 // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM. 5845 bool expected_wide_mem = false; 5846 if (n == m->base_memory()) { 5847 expected_wide_mem = true; 5848 } else if (alias_idx == Compile::AliasIdxRaw || 5849 n == m->memory_at(Compile::AliasIdxRaw)) { 5850 expected_wide_mem = true; 5851 } else if (!C->alias_type(alias_idx)->is_rewritable()) { 5852 // memory can "leak through" calls on channels that 5853 // are write-once. Allow this also. 5854 expected_wide_mem = true; 5855 } 5856 assert(expected_wide_mem, "expected narrow slice replacement"); 5857 } 5858 } 5859 #else // !ASSERT 5860 #define verify_memory_slice(m,i,n) (void)(0) // PRODUCT version is no-op 5861 #endif 5862 5863 5864 //-----------------------------memory_at--------------------------------------- 5865 Node* MergeMemNode::memory_at(uint alias_idx) const { 5866 assert(alias_idx >= Compile::AliasIdxRaw || 5867 (alias_idx == Compile::AliasIdxBot && !Compile::current()->do_aliasing()), 5868 "must avoid base_memory and AliasIdxTop"); 5869 5870 // Otherwise, it is a narrow slice. 5871 Node* n = alias_idx < req() ? in(alias_idx) : empty_memory(); 5872 if (is_empty_memory(n)) { 5873 // the array is sparse; empty slots are the "top" node 5874 n = base_memory(); 5875 assert(Node::in_dump() 5876 || n == nullptr || n->bottom_type() == Type::TOP 5877 || n->adr_type() == nullptr // address is TOP 5878 || n->adr_type() == TypePtr::BOTTOM 5879 || n->adr_type() == TypeRawPtr::BOTTOM 5880 || !Compile::current()->do_aliasing(), 5881 "must be a wide memory"); 5882 // do_aliasing == false if we are organizing the memory states manually. 5883 // See verify_memory_slice for comments on TypeRawPtr::BOTTOM. 5884 } else { 5885 // make sure the stored slice is sane 5886 #ifdef ASSERT 5887 if (VMError::is_error_reported() || Node::in_dump()) { 5888 } else if (might_be_same(n, base_memory())) { 5889 // Give it a pass: It is a mostly harmless repetition of the base. 5890 // This can arise normally from node subsumption during optimization. 5891 } else { 5892 verify_memory_slice(this, alias_idx, n); 5893 } 5894 #endif 5895 } 5896 return n; 5897 } 5898 5899 //---------------------------set_memory_at------------------------------------- 5900 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) { 5901 verify_memory_slice(this, alias_idx, n); 5902 Node* empty_mem = empty_memory(); 5903 if (n == base_memory()) n = empty_mem; // collapse default 5904 uint need_req = alias_idx+1; 5905 if (req() < need_req) { 5906 if (n == empty_mem) return; // already the default, so do not grow me 5907 // grow the sparse array 5908 do { 5909 add_req(empty_mem); 5910 } while (req() < need_req); 5911 } 5912 set_req( alias_idx, n ); 5913 } 5914 5915 5916 5917 //--------------------------iteration_setup------------------------------------ 5918 void MergeMemNode::iteration_setup(const MergeMemNode* other) { 5919 if (other != nullptr) { 5920 grow_to_match(other); 5921 // invariant: the finite support of mm2 is within mm->req() 5922 #ifdef ASSERT 5923 for (uint i = req(); i < other->req(); i++) { 5924 assert(other->is_empty_memory(other->in(i)), "slice left uncovered"); 5925 } 5926 #endif 5927 } 5928 // Replace spurious copies of base_memory by top. 5929 Node* base_mem = base_memory(); 5930 if (base_mem != nullptr && !base_mem->is_top()) { 5931 for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) { 5932 if (in(i) == base_mem) 5933 set_req(i, empty_memory()); 5934 } 5935 } 5936 } 5937 5938 //---------------------------grow_to_match------------------------------------- 5939 void MergeMemNode::grow_to_match(const MergeMemNode* other) { 5940 Node* empty_mem = empty_memory(); 5941 assert(other->is_empty_memory(empty_mem), "consistent sentinels"); 5942 // look for the finite support of the other memory 5943 for (uint i = other->req(); --i >= req(); ) { 5944 if (other->in(i) != empty_mem) { 5945 uint new_len = i+1; 5946 while (req() < new_len) add_req(empty_mem); 5947 break; 5948 } 5949 } 5950 } 5951 5952 //---------------------------verify_sparse------------------------------------- 5953 #ifndef PRODUCT 5954 bool MergeMemNode::verify_sparse() const { 5955 assert(is_empty_memory(make_empty_memory()), "sane sentinel"); 5956 Node* base_mem = base_memory(); 5957 // The following can happen in degenerate cases, since empty==top. 5958 if (is_empty_memory(base_mem)) return true; 5959 for (uint i = Compile::AliasIdxRaw; i < req(); i++) { 5960 assert(in(i) != nullptr, "sane slice"); 5961 if (in(i) == base_mem) return false; // should have been the sentinel value! 5962 } 5963 return true; 5964 } 5965 5966 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) { 5967 Node* n; 5968 n = mm->in(idx); 5969 if (mem == n) return true; // might be empty_memory() 5970 n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx); 5971 if (mem == n) return true; 5972 return false; 5973 } 5974 #endif // !PRODUCT