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