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