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