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