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