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