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