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