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