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