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