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