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