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