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