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