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