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