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