1 /*
2 * Copyright 1997-2007 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
24
25 // Portions of code courtesy of Clifford Click
26
27 // Optimization - Graph Style
28
29 #include "incls/_precompiled.incl"
30 #include "incls/_memnode.cpp.incl"
31
32 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st);
33
34 //=============================================================================
35 uint MemNode::size_of() const { return sizeof(*this); }
36
37 const TypePtr *MemNode::adr_type() const {
38 Node* adr = in(Address);
39 const TypePtr* cross_check = NULL;
40 DEBUG_ONLY(cross_check = _adr_type);
41 return calculate_adr_type(adr->bottom_type(), cross_check);
42 }
43
44 #ifndef PRODUCT
45 void MemNode::dump_spec(outputStream *st) const {
46 if (in(Address) == NULL) return; // node is dead
47 #ifndef ASSERT
48 // fake the missing field
49 const TypePtr* _adr_type = NULL;
50 if (in(Address) != NULL)
51 _adr_type = in(Address)->bottom_type()->isa_ptr();
52 #endif
53 dump_adr_type(this, _adr_type, st);
54
55 Compile* C = Compile::current();
56 if( C->alias_type(_adr_type)->is_volatile() )
57 st->print(" Volatile!");
58 }
59
60 void MemNode::dump_adr_type(const Node* mem, const TypePtr* adr_type, outputStream *st) {
61 st->print(" @");
62 if (adr_type == NULL) {
63 st->print("NULL");
64 } else {
65 adr_type->dump_on(st);
66 Compile* C = Compile::current();
67 Compile::AliasType* atp = NULL;
68 if (C->have_alias_type(adr_type)) atp = C->alias_type(adr_type);
69 if (atp == NULL)
70 st->print(", idx=?\?;");
71 else if (atp->index() == Compile::AliasIdxBot)
72 st->print(", idx=Bot;");
73 else if (atp->index() == Compile::AliasIdxTop)
74 st->print(", idx=Top;");
75 else if (atp->index() == Compile::AliasIdxRaw)
76 st->print(", idx=Raw;");
77 else {
78 ciField* field = atp->field();
79 if (field) {
80 st->print(", name=");
81 field->print_name_on(st);
82 }
83 st->print(", idx=%d;", atp->index());
84 }
85 }
86 }
87
88 extern void print_alias_types();
89
90 #endif
91
92 Node *MemNode::optimize_simple_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
93 const TypeOopPtr *tinst = t_adr->isa_oopptr();
94 if (tinst == NULL || !tinst->is_instance_field())
95 return mchain; // don't try to optimize non-instance types
96 uint instance_id = tinst->instance_id();
97 Node *prev = NULL;
98 Node *result = mchain;
99 while (prev != result) {
100 prev = result;
101 // skip over a call which does not affect this memory slice
102 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
103 Node *proj_in = result->in(0);
104 if (proj_in->is_Call()) {
105 CallNode *call = proj_in->as_Call();
106 if (!call->may_modify(t_adr, phase)) {
107 result = call->in(TypeFunc::Memory);
108 }
109 } else if (proj_in->is_Initialize()) {
110 AllocateNode* alloc = proj_in->as_Initialize()->allocation();
111 // Stop if this is the initialization for the object instance which
112 // which contains this memory slice, otherwise skip over it.
113 if (alloc != NULL && alloc->_idx != instance_id) {
114 result = proj_in->in(TypeFunc::Memory);
115 }
116 } else if (proj_in->is_MemBar()) {
117 result = proj_in->in(TypeFunc::Memory);
118 }
119 } else if (result->is_MergeMem()) {
120 result = step_through_mergemem(phase, result->as_MergeMem(), t_adr, NULL, tty);
121 }
122 }
123 return result;
124 }
125
126 Node *MemNode::optimize_memory_chain(Node *mchain, const TypePtr *t_adr, PhaseGVN *phase) {
127 const TypeOopPtr *t_oop = t_adr->isa_oopptr();
128 bool is_instance = (t_oop != NULL) && t_oop->is_instance_field();
129 PhaseIterGVN *igvn = phase->is_IterGVN();
130 Node *result = mchain;
131 result = optimize_simple_memory_chain(result, t_adr, phase);
132 if (is_instance && igvn != NULL && result->is_Phi()) {
133 PhiNode *mphi = result->as_Phi();
134 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
135 const TypePtr *t = mphi->adr_type();
136 if (t == TypePtr::BOTTOM || t == TypeRawPtr::BOTTOM) {
137 // clone the Phi with our address type
138 result = mphi->split_out_instance(t_adr, igvn);
139 } else {
140 assert(phase->C->get_alias_index(t) == phase->C->get_alias_index(t_adr), "correct memory chain");
141 }
142 }
143 return result;
144 }
145
146 static Node *step_through_mergemem(PhaseGVN *phase, MergeMemNode *mmem, const TypePtr *tp, const TypePtr *adr_check, outputStream *st) {
147 uint alias_idx = phase->C->get_alias_index(tp);
148 Node *mem = mmem;
149 #ifdef ASSERT
150 {
151 // Check that current type is consistent with the alias index used during graph construction
152 assert(alias_idx >= Compile::AliasIdxRaw, "must not be a bad alias_idx");
153 bool consistent = adr_check == NULL || adr_check->empty() ||
154 phase->C->must_alias(adr_check, alias_idx );
155 // Sometimes dead array references collapse to a[-1], a[-2], or a[-3]
156 if( !consistent && adr_check != NULL && !adr_check->empty() &&
157 tp->isa_aryptr() && tp->offset() == Type::OffsetBot &&
158 adr_check->isa_aryptr() && adr_check->offset() != Type::OffsetBot &&
159 ( adr_check->offset() == arrayOopDesc::length_offset_in_bytes() ||
160 adr_check->offset() == oopDesc::klass_offset_in_bytes() ||
161 adr_check->offset() == oopDesc::mark_offset_in_bytes() ) ) {
162 // don't assert if it is dead code.
163 consistent = true;
164 }
165 if( !consistent ) {
166 st->print("alias_idx==%d, adr_check==", alias_idx);
167 if( adr_check == NULL ) {
168 st->print("NULL");
169 } else {
170 adr_check->dump();
171 }
172 st->cr();
173 print_alias_types();
174 assert(consistent, "adr_check must match alias idx");
175 }
176 }
177 #endif
178 // TypeInstPtr::NOTNULL+any is an OOP with unknown offset - generally
179 // means an array I have not precisely typed yet. Do not do any
180 // alias stuff with it any time soon.
181 const TypeOopPtr *tinst = tp->isa_oopptr();
182 if( tp->base() != Type::AnyPtr &&
183 !(tinst &&
184 tinst->klass()->is_java_lang_Object() &&
185 tinst->offset() == Type::OffsetBot) ) {
186 // compress paths and change unreachable cycles to TOP
187 // If not, we can update the input infinitely along a MergeMem cycle
188 // Equivalent code in PhiNode::Ideal
189 Node* m = phase->transform(mmem);
190 // If tranformed to a MergeMem, get the desired slice
191 // Otherwise the returned node represents memory for every slice
192 mem = (m->is_MergeMem())? m->as_MergeMem()->memory_at(alias_idx) : m;
193 // Update input if it is progress over what we have now
194 }
195 return mem;
196 }
197
198 //--------------------------Ideal_common---------------------------------------
199 // Look for degenerate control and memory inputs. Bypass MergeMem inputs.
200 // Unhook non-raw memories from complete (macro-expanded) initializations.
201 Node *MemNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
202 // If our control input is a dead region, kill all below the region
203 Node *ctl = in(MemNode::Control);
204 if (ctl && remove_dead_region(phase, can_reshape))
205 return this;
206
207 // Ignore if memory is dead, or self-loop
208 Node *mem = in(MemNode::Memory);
209 if( phase->type( mem ) == Type::TOP ) return NodeSentinel; // caller will return NULL
210 assert( mem != this, "dead loop in MemNode::Ideal" );
211
212 Node *address = in(MemNode::Address);
213 const Type *t_adr = phase->type( address );
214 if( t_adr == Type::TOP ) return NodeSentinel; // caller will return NULL
215
216 // Avoid independent memory operations
217 Node* old_mem = mem;
218
219 // The code which unhooks non-raw memories from complete (macro-expanded)
220 // initializations was removed. After macro-expansion all stores catched
221 // by Initialize node became raw stores and there is no information
222 // which memory slices they modify. So it is unsafe to move any memory
223 // operation above these stores. Also in most cases hooked non-raw memories
224 // were already unhooked by using information from detect_ptr_independence()
225 // and find_previous_store().
226
227 if (mem->is_MergeMem()) {
228 MergeMemNode* mmem = mem->as_MergeMem();
229 const TypePtr *tp = t_adr->is_ptr();
230
231 mem = step_through_mergemem(phase, mmem, tp, adr_type(), tty);
232 }
233
234 if (mem != old_mem) {
235 set_req(MemNode::Memory, mem);
236 return this;
237 }
238
239 // let the subclass continue analyzing...
240 return NULL;
241 }
242
243 // Helper function for proving some simple control dominations.
244 // Attempt to prove that all control inputs of 'dom' dominate 'sub'.
245 // Already assumes that 'dom' is available at 'sub', and that 'sub'
246 // is not a constant (dominated by the method's StartNode).
247 // Used by MemNode::find_previous_store to prove that the
248 // control input of a memory operation predates (dominates)
249 // an allocation it wants to look past.
250 bool MemNode::all_controls_dominate(Node* dom, Node* sub) {
251 if (dom == NULL || dom->is_top() || sub == NULL || sub->is_top())
252 return false; // Conservative answer for dead code
253
254 // Check 'dom'.
255 dom = dom->find_exact_control(dom);
256 if (dom == NULL || dom->is_top())
257 return false; // Conservative answer for dead code
258
259 if (dom->is_Con() || dom->is_Start() || dom->is_Root() || dom == sub)
260 return true;
261
262 // 'dom' dominates 'sub' if its control edge and control edges
263 // of all its inputs dominate or equal to sub's control edge.
264
265 // Currently 'sub' is either Allocate, Initialize or Start nodes.
266 assert(sub->is_Allocate() || sub->is_Initialize() || sub->is_Start(), "expecting only these nodes");
267
268 // Get control edge of 'sub'.
269 sub = sub->find_exact_control(sub->in(0));
270 if (sub == NULL || sub->is_top())
271 return false; // Conservative answer for dead code
272
273 assert(sub->is_CFG(), "expecting control");
274
275 if (sub == dom)
276 return true;
277
278 if (sub->is_Start() || sub->is_Root())
279 return false;
280
281 {
282 // Check all control edges of 'dom'.
283
284 ResourceMark rm;
285 Arena* arena = Thread::current()->resource_area();
286 Node_List nlist(arena);
287 Unique_Node_List dom_list(arena);
288
289 dom_list.push(dom);
290 bool only_dominating_controls = false;
291
292 for (uint next = 0; next < dom_list.size(); next++) {
293 Node* n = dom_list.at(next);
294 if (!n->is_CFG() && n->pinned()) {
295 // Check only own control edge for pinned non-control nodes.
296 n = n->find_exact_control(n->in(0));
297 if (n == NULL || n->is_top())
298 return false; // Conservative answer for dead code
299 assert(n->is_CFG(), "expecting control");
300 }
301 if (n->is_Con() || n->is_Start() || n->is_Root()) {
302 only_dominating_controls = true;
303 } else if (n->is_CFG()) {
304 if (n->dominates(sub, nlist))
305 only_dominating_controls = true;
306 else
307 return false;
308 } else {
309 // First, own control edge.
310 Node* m = n->find_exact_control(n->in(0));
311 if (m != NULL) {
312 if (m->is_top())
313 return false; // Conservative answer for dead code
314 dom_list.push(m);
315 }
316 // Now, the rest of edges.
317 uint cnt = n->req();
318 for (uint i = 1; i < cnt; i++) {
319 m = n->find_exact_control(n->in(i));
320 if (m == NULL || m->is_top())
321 continue;
322 dom_list.push(m);
323 }
324 }
325 }
326 return only_dominating_controls;
327 }
328 }
329
330 //---------------------detect_ptr_independence---------------------------------
331 // Used by MemNode::find_previous_store to prove that two base
332 // pointers are never equal.
333 // The pointers are accompanied by their associated allocations,
334 // if any, which have been previously discovered by the caller.
335 bool MemNode::detect_ptr_independence(Node* p1, AllocateNode* a1,
336 Node* p2, AllocateNode* a2,
337 PhaseTransform* phase) {
338 // Attempt to prove that these two pointers cannot be aliased.
339 // They may both manifestly be allocations, and they should differ.
340 // Or, if they are not both allocations, they can be distinct constants.
341 // Otherwise, one is an allocation and the other a pre-existing value.
342 if (a1 == NULL && a2 == NULL) { // neither an allocation
343 return (p1 != p2) && p1->is_Con() && p2->is_Con();
344 } else if (a1 != NULL && a2 != NULL) { // both allocations
345 return (a1 != a2);
346 } else if (a1 != NULL) { // one allocation a1
347 // (Note: p2->is_Con implies p2->in(0)->is_Root, which dominates.)
348 return all_controls_dominate(p2, a1);
349 } else { //(a2 != NULL) // one allocation a2
350 return all_controls_dominate(p1, a2);
351 }
352 return false;
353 }
354
355
356 // The logic for reordering loads and stores uses four steps:
357 // (a) Walk carefully past stores and initializations which we
358 // can prove are independent of this load.
359 // (b) Observe that the next memory state makes an exact match
360 // with self (load or store), and locate the relevant store.
361 // (c) Ensure that, if we were to wire self directly to the store,
362 // the optimizer would fold it up somehow.
363 // (d) Do the rewiring, and return, depending on some other part of
364 // the optimizer to fold up the load.
365 // This routine handles steps (a) and (b). Steps (c) and (d) are
366 // specific to loads and stores, so they are handled by the callers.
367 // (Currently, only LoadNode::Ideal has steps (c), (d). More later.)
368 //
369 Node* MemNode::find_previous_store(PhaseTransform* phase) {
370 Node* ctrl = in(MemNode::Control);
371 Node* adr = in(MemNode::Address);
372 intptr_t offset = 0;
373 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
374 AllocateNode* alloc = AllocateNode::Ideal_allocation(base, phase);
375
376 if (offset == Type::OffsetBot)
377 return NULL; // cannot unalias unless there are precise offsets
378
379 const TypeOopPtr *addr_t = adr->bottom_type()->isa_oopptr();
380
381 intptr_t size_in_bytes = memory_size();
382
383 Node* mem = in(MemNode::Memory); // start searching here...
384
385 int cnt = 50; // Cycle limiter
386 for (;;) { // While we can dance past unrelated stores...
387 if (--cnt < 0) break; // Caught in cycle or a complicated dance?
388
389 if (mem->is_Store()) {
390 Node* st_adr = mem->in(MemNode::Address);
391 intptr_t st_offset = 0;
392 Node* st_base = AddPNode::Ideal_base_and_offset(st_adr, phase, st_offset);
393 if (st_base == NULL)
394 break; // inscrutable pointer
395 if (st_offset != offset && st_offset != Type::OffsetBot) {
396 const int MAX_STORE = BytesPerLong;
397 if (st_offset >= offset + size_in_bytes ||
398 st_offset <= offset - MAX_STORE ||
399 st_offset <= offset - mem->as_Store()->memory_size()) {
400 // Success: The offsets are provably independent.
401 // (You may ask, why not just test st_offset != offset and be done?
402 // The answer is that stores of different sizes can co-exist
403 // in the same sequence of RawMem effects. We sometimes initialize
404 // a whole 'tile' of array elements with a single jint or jlong.)
405 mem = mem->in(MemNode::Memory);
406 continue; // (a) advance through independent store memory
407 }
408 }
409 if (st_base != base &&
410 detect_ptr_independence(base, alloc,
411 st_base,
412 AllocateNode::Ideal_allocation(st_base, phase),
413 phase)) {
414 // Success: The bases are provably independent.
415 mem = mem->in(MemNode::Memory);
416 continue; // (a) advance through independent store memory
417 }
418
419 // (b) At this point, if the bases or offsets do not agree, we lose,
420 // since we have not managed to prove 'this' and 'mem' independent.
421 if (st_base == base && st_offset == offset) {
422 return mem; // let caller handle steps (c), (d)
423 }
424
425 } else if (mem->is_Proj() && mem->in(0)->is_Initialize()) {
426 InitializeNode* st_init = mem->in(0)->as_Initialize();
427 AllocateNode* st_alloc = st_init->allocation();
428 if (st_alloc == NULL)
429 break; // something degenerated
430 bool known_identical = false;
431 bool known_independent = false;
432 if (alloc == st_alloc)
433 known_identical = true;
434 else if (alloc != NULL)
435 known_independent = true;
436 else if (all_controls_dominate(this, st_alloc))
437 known_independent = true;
438
439 if (known_independent) {
440 // The bases are provably independent: Either they are
441 // manifestly distinct allocations, or else the control
442 // of this load dominates the store's allocation.
443 int alias_idx = phase->C->get_alias_index(adr_type());
444 if (alias_idx == Compile::AliasIdxRaw) {
445 mem = st_alloc->in(TypeFunc::Memory);
446 } else {
447 mem = st_init->memory(alias_idx);
448 }
449 continue; // (a) advance through independent store memory
450 }
451
452 // (b) at this point, if we are not looking at a store initializing
453 // the same allocation we are loading from, we lose.
454 if (known_identical) {
455 // From caller, can_see_stored_value will consult find_captured_store.
456 return mem; // let caller handle steps (c), (d)
457 }
458
459 } else if (addr_t != NULL && addr_t->is_instance_field()) {
460 // Can't use optimize_simple_memory_chain() since it needs PhaseGVN.
461 if (mem->is_Proj() && mem->in(0)->is_Call()) {
462 CallNode *call = mem->in(0)->as_Call();
463 if (!call->may_modify(addr_t, phase)) {
464 mem = call->in(TypeFunc::Memory);
465 continue; // (a) advance through independent call memory
466 }
467 } else if (mem->is_Proj() && mem->in(0)->is_MemBar()) {
468 mem = mem->in(0)->in(TypeFunc::Memory);
469 continue; // (a) advance through independent MemBar memory
470 } else if (mem->is_MergeMem()) {
471 int alias_idx = phase->C->get_alias_index(adr_type());
472 mem = mem->as_MergeMem()->memory_at(alias_idx);
473 continue; // (a) advance through independent MergeMem memory
474 }
475 }
476
477 // Unless there is an explicit 'continue', we must bail out here,
478 // because 'mem' is an inscrutable memory state (e.g., a call).
479 break;
480 }
481
482 return NULL; // bail out
483 }
484
485 //----------------------calculate_adr_type-------------------------------------
486 // Helper function. Notices when the given type of address hits top or bottom.
487 // Also, asserts a cross-check of the type against the expected address type.
488 const TypePtr* MemNode::calculate_adr_type(const Type* t, const TypePtr* cross_check) {
489 if (t == Type::TOP) return NULL; // does not touch memory any more?
490 #ifdef PRODUCT
491 cross_check = NULL;
492 #else
493 if (!VerifyAliases || is_error_reported() || Node::in_dump()) cross_check = NULL;
494 #endif
495 const TypePtr* tp = t->isa_ptr();
496 if (tp == NULL) {
497 assert(cross_check == NULL || cross_check == TypePtr::BOTTOM, "expected memory type must be wide");
498 return TypePtr::BOTTOM; // touches lots of memory
499 } else {
500 #ifdef ASSERT
501 // %%%% [phh] We don't check the alias index if cross_check is
502 // TypeRawPtr::BOTTOM. Needs to be investigated.
503 if (cross_check != NULL &&
504 cross_check != TypePtr::BOTTOM &&
505 cross_check != TypeRawPtr::BOTTOM) {
506 // Recheck the alias index, to see if it has changed (due to a bug).
507 Compile* C = Compile::current();
508 assert(C->get_alias_index(cross_check) == C->get_alias_index(tp),
509 "must stay in the original alias category");
510 // The type of the address must be contained in the adr_type,
511 // disregarding "null"-ness.
512 // (We make an exception for TypeRawPtr::BOTTOM, which is a bit bucket.)
513 const TypePtr* tp_notnull = tp->join(TypePtr::NOTNULL)->is_ptr();
514 assert(cross_check->meet(tp_notnull) == cross_check,
515 "real address must not escape from expected memory type");
516 }
517 #endif
518 return tp;
519 }
520 }
521
522 //------------------------adr_phi_is_loop_invariant----------------------------
523 // A helper function for Ideal_DU_postCCP to check if a Phi in a counted
524 // loop is loop invariant. Make a quick traversal of Phi and associated
525 // CastPP nodes, looking to see if they are a closed group within the loop.
526 bool MemNode::adr_phi_is_loop_invariant(Node* adr_phi, Node* cast) {
527 // The idea is that the phi-nest must boil down to only CastPP nodes
528 // with the same data. This implies that any path into the loop already
529 // includes such a CastPP, and so the original cast, whatever its input,
530 // must be covered by an equivalent cast, with an earlier control input.
531 ResourceMark rm;
532
533 // The loop entry input of the phi should be the unique dominating
534 // node for every Phi/CastPP in the loop.
535 Unique_Node_List closure;
536 closure.push(adr_phi->in(LoopNode::EntryControl));
537
538 // Add the phi node and the cast to the worklist.
539 Unique_Node_List worklist;
540 worklist.push(adr_phi);
541 if( cast != NULL ){
542 if( !cast->is_ConstraintCast() ) return false;
543 worklist.push(cast);
544 }
545
546 // Begin recursive walk of phi nodes.
547 while( worklist.size() ){
548 // Take a node off the worklist
549 Node *n = worklist.pop();
550 if( !closure.member(n) ){
551 // Add it to the closure.
552 closure.push(n);
553 // Make a sanity check to ensure we don't waste too much time here.
554 if( closure.size() > 20) return false;
555 // This node is OK if:
556 // - it is a cast of an identical value
557 // - or it is a phi node (then we add its inputs to the worklist)
558 // Otherwise, the node is not OK, and we presume the cast is not invariant
559 if( n->is_ConstraintCast() ){
560 worklist.push(n->in(1));
561 } else if( n->is_Phi() ) {
562 for( uint i = 1; i < n->req(); i++ ) {
563 worklist.push(n->in(i));
564 }
565 } else {
566 return false;
567 }
568 }
569 }
570
571 // Quit when the worklist is empty, and we've found no offending nodes.
572 return true;
573 }
574
575 //------------------------------Ideal_DU_postCCP-------------------------------
576 // Find any cast-away of null-ness and keep its control. Null cast-aways are
577 // going away in this pass and we need to make this memory op depend on the
578 // gating null check.
579
580 // I tried to leave the CastPP's in. This makes the graph more accurate in
581 // some sense; we get to keep around the knowledge that an oop is not-null
582 // after some test. Alas, the CastPP's interfere with GVN (some values are
583 // the regular oop, some are the CastPP of the oop, all merge at Phi's which
584 // cannot collapse, etc). This cost us 10% on SpecJVM, even when I removed
585 // some of the more trivial cases in the optimizer. Removing more useless
586 // Phi's started allowing Loads to illegally float above null checks. I gave
587 // up on this approach. CNC 10/20/2000
588 Node *MemNode::Ideal_DU_postCCP( PhaseCCP *ccp ) {
589 Node *ctr = in(MemNode::Control);
590 Node *mem = in(MemNode::Memory);
591 Node *adr = in(MemNode::Address);
592 Node *skipped_cast = NULL;
593 // Need a null check? Regular static accesses do not because they are
594 // from constant addresses. Array ops are gated by the range check (which
595 // always includes a NULL check). Just check field ops.
596 if( !ctr ) {
597 // Scan upwards for the highest location we can place this memory op.
598 while( true ) {
599 switch( adr->Opcode() ) {
600
601 case Op_AddP: // No change to NULL-ness, so peek thru AddP's
602 adr = adr->in(AddPNode::Base);
603 continue;
604
605 case Op_DecodeN: // No change to NULL-ness, so peek thru
606 adr = adr->in(1);
607 continue;
608
609 case Op_CastPP:
610 // If the CastPP is useless, just peek on through it.
611 if( ccp->type(adr) == ccp->type(adr->in(1)) ) {
612 // Remember the cast that we've peeked though. If we peek
613 // through more than one, then we end up remembering the highest
614 // one, that is, if in a loop, the one closest to the top.
615 skipped_cast = adr;
616 adr = adr->in(1);
617 continue;
618 }
619 // CastPP is going away in this pass! We need this memory op to be
620 // control-dependent on the test that is guarding the CastPP.
621 ccp->hash_delete(this);
622 set_req(MemNode::Control, adr->in(0));
623 ccp->hash_insert(this);
624 return this;
625
626 case Op_Phi:
627 // Attempt to float above a Phi to some dominating point.
628 if (adr->in(0) != NULL && adr->in(0)->is_CountedLoop()) {
629 // If we've already peeked through a Cast (which could have set the
630 // control), we can't float above a Phi, because the skipped Cast
631 // may not be loop invariant.
632 if (adr_phi_is_loop_invariant(adr, skipped_cast)) {
633 adr = adr->in(1);
634 continue;
635 }
636 }
637
638 // Intentional fallthrough!
639
640 // No obvious dominating point. The mem op is pinned below the Phi
641 // by the Phi itself. If the Phi goes away (no true value is merged)
642 // then the mem op can float, but not indefinitely. It must be pinned
643 // behind the controls leading to the Phi.
644 case Op_CheckCastPP:
645 // These usually stick around to change address type, however a
646 // useless one can be elided and we still need to pick up a control edge
647 if (adr->in(0) == NULL) {
648 // This CheckCastPP node has NO control and is likely useless. But we
649 // need check further up the ancestor chain for a control input to keep
650 // the node in place. 4959717.
651 skipped_cast = adr;
652 adr = adr->in(1);
653 continue;
654 }
655 ccp->hash_delete(this);
656 set_req(MemNode::Control, adr->in(0));
657 ccp->hash_insert(this);
658 return this;
659
660 // List of "safe" opcodes; those that implicitly block the memory
661 // op below any null check.
662 case Op_CastX2P: // no null checks on native pointers
663 case Op_Parm: // 'this' pointer is not null
664 case Op_LoadP: // Loading from within a klass
665 case Op_LoadN: // Loading from within a klass
666 case Op_LoadKlass: // Loading from within a klass
667 case Op_ConP: // Loading from a klass
668 case Op_CreateEx: // Sucking up the guts of an exception oop
669 case Op_Con: // Reading from TLS
670 case Op_CMoveP: // CMoveP is pinned
671 break; // No progress
672
673 case Op_Proj: // Direct call to an allocation routine
674 case Op_SCMemProj: // Memory state from store conditional ops
675 #ifdef ASSERT
676 {
677 assert(adr->as_Proj()->_con == TypeFunc::Parms, "must be return value");
678 const Node* call = adr->in(0);
679 if (call->is_CallStaticJava()) {
680 const CallStaticJavaNode* call_java = call->as_CallStaticJava();
681 const TypeTuple *r = call_java->tf()->range();
682 assert(r->cnt() > TypeFunc::Parms, "must return value");
683 const Type* ret_type = r->field_at(TypeFunc::Parms);
684 assert(ret_type && ret_type->isa_ptr(), "must return pointer");
685 // We further presume that this is one of
686 // new_instance_Java, new_array_Java, or
687 // the like, but do not assert for this.
688 } else if (call->is_Allocate()) {
689 // similar case to new_instance_Java, etc.
690 } else if (!call->is_CallLeaf()) {
691 // Projections from fetch_oop (OSR) are allowed as well.
692 ShouldNotReachHere();
693 }
694 }
695 #endif
696 break;
697 default:
698 ShouldNotReachHere();
699 }
700 break;
701 }
702 }
703
704 return NULL; // No progress
705 }
706
707
708 //=============================================================================
709 uint LoadNode::size_of() const { return sizeof(*this); }
710 uint LoadNode::cmp( const Node &n ) const
711 { return !Type::cmp( _type, ((LoadNode&)n)._type ); }
712 const Type *LoadNode::bottom_type() const { return _type; }
713 uint LoadNode::ideal_reg() const {
714 return Matcher::base2reg[_type->base()];
715 }
716
717 #ifndef PRODUCT
718 void LoadNode::dump_spec(outputStream *st) const {
719 MemNode::dump_spec(st);
720 if( !Verbose && !WizardMode ) {
721 // standard dump does this in Verbose and WizardMode
722 st->print(" #"); _type->dump_on(st);
723 }
724 }
725 #endif
726
727
728 //----------------------------LoadNode::make-----------------------------------
729 // Polymorphic factory method:
730 Node *LoadNode::make( PhaseGVN& gvn, Node *ctl, Node *mem, Node *adr, const TypePtr* adr_type, const Type *rt, BasicType bt ) {
731 Compile* C = gvn.C;
732
733 // sanity check the alias category against the created node type
734 assert(!(adr_type->isa_oopptr() &&
735 adr_type->offset() == oopDesc::klass_offset_in_bytes()),
736 "use LoadKlassNode instead");
737 assert(!(adr_type->isa_aryptr() &&
738 adr_type->offset() == arrayOopDesc::length_offset_in_bytes()),
739 "use LoadRangeNode instead");
740 switch (bt) {
741 case T_BOOLEAN:
742 case T_BYTE: return new (C, 3) LoadBNode(ctl, mem, adr, adr_type, rt->is_int() );
743 case T_INT: return new (C, 3) LoadINode(ctl, mem, adr, adr_type, rt->is_int() );
744 case T_CHAR: return new (C, 3) LoadCNode(ctl, mem, adr, adr_type, rt->is_int() );
745 case T_SHORT: return new (C, 3) LoadSNode(ctl, mem, adr, adr_type, rt->is_int() );
746 case T_LONG: return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long() );
747 case T_FLOAT: return new (C, 3) LoadFNode(ctl, mem, adr, adr_type, rt );
748 case T_DOUBLE: return new (C, 3) LoadDNode(ctl, mem, adr, adr_type, rt );
749 case T_ADDRESS: return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_ptr() );
750 case T_OBJECT:
751 #ifdef _LP64
752 if (adr->bottom_type()->is_narrow()) {
753 const TypeNarrowOop* narrowtype;
754 if (rt->isa_narrowoop()) {
755 narrowtype = rt->is_narrowoop();
756 } else {
757 narrowtype = rt->is_oopptr()->make_narrowoop();
758 }
759 Node* load = gvn.transform(new (C, 3) LoadNNode(ctl, mem, adr, adr_type, narrowtype));
760
761 return DecodeNNode::decode(&gvn, load);
762 } else
763 #endif
764 {
765 assert(!adr->bottom_type()->is_narrow(), "should have got back a narrow oop");
766 return new (C, 3) LoadPNode(ctl, mem, adr, adr_type, rt->is_oopptr());
767 }
768 }
769 ShouldNotReachHere();
770 return (LoadNode*)NULL;
771 }
772
773 LoadLNode* LoadLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, const Type* rt) {
774 bool require_atomic = true;
775 return new (C, 3) LoadLNode(ctl, mem, adr, adr_type, rt->is_long(), require_atomic);
776 }
777
778
779
780
781 //------------------------------hash-------------------------------------------
782 uint LoadNode::hash() const {
783 // unroll addition of interesting fields
784 return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address);
785 }
786
787 //---------------------------can_see_stored_value------------------------------
788 // This routine exists to make sure this set of tests is done the same
789 // everywhere. We need to make a coordinated change: first LoadNode::Ideal
790 // will change the graph shape in a way which makes memory alive twice at the
791 // same time (uses the Oracle model of aliasing), then some
792 // LoadXNode::Identity will fold things back to the equivalence-class model
793 // of aliasing.
794 Node* MemNode::can_see_stored_value(Node* st, PhaseTransform* phase) const {
795 Node* ld_adr = in(MemNode::Address);
796
797 const TypeInstPtr* tp = phase->type(ld_adr)->isa_instptr();
798 Compile::AliasType* atp = tp != NULL ? phase->C->alias_type(tp) : NULL;
799 if (EliminateAutoBox && atp != NULL && atp->index() >= Compile::AliasIdxRaw &&
800 atp->field() != NULL && !atp->field()->is_volatile()) {
801 uint alias_idx = atp->index();
802 bool final = atp->field()->is_final();
803 Node* result = NULL;
804 Node* current = st;
805 // Skip through chains of MemBarNodes checking the MergeMems for
806 // new states for the slice of this load. Stop once any other
807 // kind of node is encountered. Loads from final memory can skip
808 // through any kind of MemBar but normal loads shouldn't skip
809 // through MemBarAcquire since the could allow them to move out of
810 // a synchronized region.
811 while (current->is_Proj()) {
812 int opc = current->in(0)->Opcode();
813 if ((final && opc == Op_MemBarAcquire) ||
814 opc == Op_MemBarRelease || opc == Op_MemBarCPUOrder) {
815 Node* mem = current->in(0)->in(TypeFunc::Memory);
816 if (mem->is_MergeMem()) {
817 MergeMemNode* merge = mem->as_MergeMem();
818 Node* new_st = merge->memory_at(alias_idx);
819 if (new_st == merge->base_memory()) {
820 // Keep searching
821 current = merge->base_memory();
822 continue;
823 }
824 // Save the new memory state for the slice and fall through
825 // to exit.
826 result = new_st;
827 }
828 }
829 break;
830 }
831 if (result != NULL) {
832 st = result;
833 }
834 }
835
836
837 // Loop around twice in the case Load -> Initialize -> Store.
838 // (See PhaseIterGVN::add_users_to_worklist, which knows about this case.)
839 for (int trip = 0; trip <= 1; trip++) {
840
841 if (st->is_Store()) {
842 Node* st_adr = st->in(MemNode::Address);
843 if (!phase->eqv(st_adr, ld_adr)) {
844 // Try harder before giving up... Match raw and non-raw pointers.
845 intptr_t st_off = 0;
846 AllocateNode* alloc = AllocateNode::Ideal_allocation(st_adr, phase, st_off);
847 if (alloc == NULL) return NULL;
848 intptr_t ld_off = 0;
849 AllocateNode* allo2 = AllocateNode::Ideal_allocation(ld_adr, phase, ld_off);
850 if (alloc != allo2) return NULL;
851 if (ld_off != st_off) return NULL;
852 // At this point we have proven something like this setup:
853 // A = Allocate(...)
854 // L = LoadQ(, AddP(CastPP(, A.Parm),, #Off))
855 // S = StoreQ(, AddP(, A.Parm , #Off), V)
856 // (Actually, we haven't yet proven the Q's are the same.)
857 // In other words, we are loading from a casted version of
858 // the same pointer-and-offset that we stored to.
859 // Thus, we are able to replace L by V.
860 }
861 // Now prove that we have a LoadQ matched to a StoreQ, for some Q.
862 if (store_Opcode() != st->Opcode())
863 return NULL;
864 return st->in(MemNode::ValueIn);
865 }
866
867 intptr_t offset = 0; // scratch
868
869 // A load from a freshly-created object always returns zero.
870 // (This can happen after LoadNode::Ideal resets the load's memory input
871 // to find_captured_store, which returned InitializeNode::zero_memory.)
872 if (st->is_Proj() && st->in(0)->is_Allocate() &&
873 st->in(0) == AllocateNode::Ideal_allocation(ld_adr, phase, offset) &&
874 offset >= st->in(0)->as_Allocate()->minimum_header_size()) {
875 // return a zero value for the load's basic type
876 // (This is one of the few places where a generic PhaseTransform
877 // can create new nodes. Think of it as lazily manifesting
878 // virtually pre-existing constants.)
879 return phase->zerocon(memory_type());
880 }
881
882 // A load from an initialization barrier can match a captured store.
883 if (st->is_Proj() && st->in(0)->is_Initialize()) {
884 InitializeNode* init = st->in(0)->as_Initialize();
885 AllocateNode* alloc = init->allocation();
886 if (alloc != NULL &&
887 alloc == AllocateNode::Ideal_allocation(ld_adr, phase, offset)) {
888 // examine a captured store value
889 st = init->find_captured_store(offset, memory_size(), phase);
890 if (st != NULL)
891 continue; // take one more trip around
892 }
893 }
894
895 break;
896 }
897
898 return NULL;
899 }
900
901 //----------------------is_instance_field_load_with_local_phi------------------
902 bool LoadNode::is_instance_field_load_with_local_phi(Node* ctrl) {
903 if( in(MemNode::Memory)->is_Phi() && in(MemNode::Memory)->in(0) == ctrl &&
904 in(MemNode::Address)->is_AddP() ) {
905 const TypeOopPtr* t_oop = in(MemNode::Address)->bottom_type()->isa_oopptr();
906 // Only instances.
907 if( t_oop != NULL && t_oop->is_instance_field() &&
908 t_oop->offset() != Type::OffsetBot &&
909 t_oop->offset() != Type::OffsetTop) {
910 return true;
911 }
912 }
913 return false;
914 }
915
916 //------------------------------Identity---------------------------------------
917 // Loads are identity if previous store is to same address
918 Node *LoadNode::Identity( PhaseTransform *phase ) {
919 // If the previous store-maker is the right kind of Store, and the store is
920 // to the same address, then we are equal to the value stored.
921 Node* mem = in(MemNode::Memory);
922 Node* value = can_see_stored_value(mem, phase);
923 if( value ) {
924 // byte, short & char stores truncate naturally.
925 // A load has to load the truncated value which requires
926 // some sort of masking operation and that requires an
927 // Ideal call instead of an Identity call.
928 if (memory_size() < BytesPerInt) {
929 // If the input to the store does not fit with the load's result type,
930 // it must be truncated via an Ideal call.
931 if (!phase->type(value)->higher_equal(phase->type(this)))
932 return this;
933 }
934 // (This works even when value is a Con, but LoadNode::Value
935 // usually runs first, producing the singleton type of the Con.)
936 return value;
937 }
938
939 // Search for an existing data phi which was generated before for the same
940 // instance's field to avoid infinite genertion of phis in a loop.
941 Node *region = mem->in(0);
942 if (is_instance_field_load_with_local_phi(region)) {
943 const TypePtr *addr_t = in(MemNode::Address)->bottom_type()->isa_ptr();
944 int this_index = phase->C->get_alias_index(addr_t);
945 int this_offset = addr_t->offset();
946 int this_id = addr_t->is_oopptr()->instance_id();
947 const Type* this_type = bottom_type();
948 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
949 Node* phi = region->fast_out(i);
950 if (phi->is_Phi() && phi != mem &&
951 phi->as_Phi()->is_same_inst_field(this_type, this_id, this_index, this_offset)) {
952 return phi;
953 }
954 }
955 }
956
957 return this;
958 }
959
960
961 // Returns true if the AliasType refers to the field that holds the
962 // cached box array. Currently only handles the IntegerCache case.
963 static bool is_autobox_cache(Compile::AliasType* atp) {
964 if (atp != NULL && atp->field() != NULL) {
965 ciField* field = atp->field();
966 ciSymbol* klass = field->holder()->name();
967 if (field->name() == ciSymbol::cache_field_name() &&
968 field->holder()->uses_default_loader() &&
969 klass == ciSymbol::java_lang_Integer_IntegerCache()) {
970 return true;
971 }
972 }
973 return false;
974 }
975
976 // Fetch the base value in the autobox array
977 static bool fetch_autobox_base(Compile::AliasType* atp, int& cache_offset) {
978 if (atp != NULL && atp->field() != NULL) {
979 ciField* field = atp->field();
980 ciSymbol* klass = field->holder()->name();
981 if (field->name() == ciSymbol::cache_field_name() &&
982 field->holder()->uses_default_loader() &&
983 klass == ciSymbol::java_lang_Integer_IntegerCache()) {
984 assert(field->is_constant(), "what?");
985 ciObjArray* array = field->constant_value().as_object()->as_obj_array();
986 // Fetch the box object at the base of the array and get its value
987 ciInstance* box = array->obj_at(0)->as_instance();
988 ciInstanceKlass* ik = box->klass()->as_instance_klass();
989 if (ik->nof_nonstatic_fields() == 1) {
990 // This should be true nonstatic_field_at requires calling
991 // nof_nonstatic_fields so check it anyway
992 ciConstant c = box->field_value(ik->nonstatic_field_at(0));
993 cache_offset = c.as_int();
994 }
995 return true;
996 }
997 }
998 return false;
999 }
1000
1001 // Returns true if the AliasType refers to the value field of an
1002 // autobox object. Currently only handles Integer.
1003 static bool is_autobox_object(Compile::AliasType* atp) {
1004 if (atp != NULL && atp->field() != NULL) {
1005 ciField* field = atp->field();
1006 ciSymbol* klass = field->holder()->name();
1007 if (field->name() == ciSymbol::value_name() &&
1008 field->holder()->uses_default_loader() &&
1009 klass == ciSymbol::java_lang_Integer()) {
1010 return true;
1011 }
1012 }
1013 return false;
1014 }
1015
1016
1017 // We're loading from an object which has autobox behaviour.
1018 // If this object is result of a valueOf call we'll have a phi
1019 // merging a newly allocated object and a load from the cache.
1020 // We want to replace this load with the original incoming
1021 // argument to the valueOf call.
1022 Node* LoadNode::eliminate_autobox(PhaseGVN* phase) {
1023 Node* base = in(Address)->in(AddPNode::Base);
1024 if (base->is_Phi() && base->req() == 3) {
1025 AllocateNode* allocation = NULL;
1026 int allocation_index = -1;
1027 int load_index = -1;
1028 for (uint i = 1; i < base->req(); i++) {
1029 allocation = AllocateNode::Ideal_allocation(base->in(i), phase);
1030 if (allocation != NULL) {
1031 allocation_index = i;
1032 load_index = 3 - allocation_index;
1033 break;
1034 }
1035 }
1036 LoadNode* load = NULL;
1037 if (allocation != NULL && base->in(load_index)->is_Load()) {
1038 load = base->in(load_index)->as_Load();
1039 }
1040 if (load != NULL && in(Memory)->is_Phi() && in(Memory)->in(0) == base->in(0)) {
1041 // Push the loads from the phi that comes from valueOf up
1042 // through it to allow elimination of the loads and the recovery
1043 // of the original value.
1044 Node* mem_phi = in(Memory);
1045 Node* offset = in(Address)->in(AddPNode::Offset);
1046
1047 Node* in1 = clone();
1048 Node* in1_addr = in1->in(Address)->clone();
1049 in1_addr->set_req(AddPNode::Base, base->in(allocation_index));
1050 in1_addr->set_req(AddPNode::Address, base->in(allocation_index));
1051 in1_addr->set_req(AddPNode::Offset, offset);
1052 in1->set_req(0, base->in(allocation_index));
1053 in1->set_req(Address, in1_addr);
1054 in1->set_req(Memory, mem_phi->in(allocation_index));
1055
1056 Node* in2 = clone();
1057 Node* in2_addr = in2->in(Address)->clone();
1058 in2_addr->set_req(AddPNode::Base, base->in(load_index));
1059 in2_addr->set_req(AddPNode::Address, base->in(load_index));
1060 in2_addr->set_req(AddPNode::Offset, offset);
1061 in2->set_req(0, base->in(load_index));
1062 in2->set_req(Address, in2_addr);
1063 in2->set_req(Memory, mem_phi->in(load_index));
1064
1065 in1_addr = phase->transform(in1_addr);
1066 in1 = phase->transform(in1);
1067 in2_addr = phase->transform(in2_addr);
1068 in2 = phase->transform(in2);
1069
1070 PhiNode* result = PhiNode::make_blank(base->in(0), this);
1071 result->set_req(allocation_index, in1);
1072 result->set_req(load_index, in2);
1073 return result;
1074 }
1075 } else if (base->is_Load()) {
1076 // Eliminate the load of Integer.value for integers from the cache
1077 // array by deriving the value from the index into the array.
1078 // Capture the offset of the load and then reverse the computation.
1079 Node* load_base = base->in(Address)->in(AddPNode::Base);
1080 if (load_base != NULL) {
1081 Compile::AliasType* atp = phase->C->alias_type(load_base->adr_type());
1082 intptr_t cache_offset;
1083 int shift = -1;
1084 Node* cache = NULL;
1085 if (is_autobox_cache(atp)) {
1086 shift = exact_log2(type2aelembytes(T_OBJECT));
1087 cache = AddPNode::Ideal_base_and_offset(load_base->in(Address), phase, cache_offset);
1088 }
1089 if (cache != NULL && base->in(Address)->is_AddP()) {
1090 Node* elements[4];
1091 int count = base->in(Address)->as_AddP()->unpack_offsets(elements, ARRAY_SIZE(elements));
1092 int cache_low;
1093 if (count > 0 && fetch_autobox_base(atp, cache_low)) {
1094 int offset = arrayOopDesc::base_offset_in_bytes(memory_type()) - (cache_low << shift);
1095 // Add up all the offsets making of the address of the load
1096 Node* result = elements[0];
1097 for (int i = 1; i < count; i++) {
1098 result = phase->transform(new (phase->C, 3) AddXNode(result, elements[i]));
1099 }
1100 // Remove the constant offset from the address and then
1101 // remove the scaling of the offset to recover the original index.
1102 result = phase->transform(new (phase->C, 3) AddXNode(result, phase->MakeConX(-offset)));
1103 if (result->Opcode() == Op_LShiftX && result->in(2) == phase->intcon(shift)) {
1104 // Peel the shift off directly but wrap it in a dummy node
1105 // since Ideal can't return existing nodes
1106 result = new (phase->C, 3) RShiftXNode(result->in(1), phase->intcon(0));
1107 } else {
1108 result = new (phase->C, 3) RShiftXNode(result, phase->intcon(shift));
1109 }
1110 #ifdef _LP64
1111 result = new (phase->C, 2) ConvL2INode(phase->transform(result));
1112 #endif
1113 return result;
1114 }
1115 }
1116 }
1117 }
1118 return NULL;
1119 }
1120
1121
1122 //------------------------------Ideal------------------------------------------
1123 // If the load is from Field memory and the pointer is non-null, we can
1124 // zero out the control input.
1125 // If the offset is constant and the base is an object allocation,
1126 // try to hook me up to the exact initializing store.
1127 Node *LoadNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1128 Node* p = MemNode::Ideal_common(phase, can_reshape);
1129 if (p) return (p == NodeSentinel) ? NULL : p;
1130
1131 Node* ctrl = in(MemNode::Control);
1132 Node* address = in(MemNode::Address);
1133
1134 // Skip up past a SafePoint control. Cannot do this for Stores because
1135 // pointer stores & cardmarks must stay on the same side of a SafePoint.
1136 if( ctrl != NULL && ctrl->Opcode() == Op_SafePoint &&
1137 phase->C->get_alias_index(phase->type(address)->is_ptr()) != Compile::AliasIdxRaw ) {
1138 ctrl = ctrl->in(0);
1139 set_req(MemNode::Control,ctrl);
1140 }
1141
1142 // Check for useless control edge in some common special cases
1143 if (in(MemNode::Control) != NULL) {
1144 intptr_t ignore = 0;
1145 Node* base = AddPNode::Ideal_base_and_offset(address, phase, ignore);
1146 if (base != NULL
1147 && phase->type(base)->higher_equal(TypePtr::NOTNULL)
1148 && all_controls_dominate(base, phase->C->start())) {
1149 // A method-invariant, non-null address (constant or 'this' argument).
1150 set_req(MemNode::Control, NULL);
1151 }
1152 }
1153
1154 if (EliminateAutoBox && can_reshape && in(Address)->is_AddP()) {
1155 Node* base = in(Address)->in(AddPNode::Base);
1156 if (base != NULL) {
1157 Compile::AliasType* atp = phase->C->alias_type(adr_type());
1158 if (is_autobox_object(atp)) {
1159 Node* result = eliminate_autobox(phase);
1160 if (result != NULL) return result;
1161 }
1162 }
1163 }
1164
1165 Node* mem = in(MemNode::Memory);
1166 const TypePtr *addr_t = phase->type(address)->isa_ptr();
1167
1168 if (addr_t != NULL) {
1169 // try to optimize our memory input
1170 Node* opt_mem = MemNode::optimize_memory_chain(mem, addr_t, phase);
1171 if (opt_mem != mem) {
1172 set_req(MemNode::Memory, opt_mem);
1173 return this;
1174 }
1175 const TypeOopPtr *t_oop = addr_t->isa_oopptr();
1176 if (can_reshape && opt_mem->is_Phi() &&
1177 (t_oop != NULL) && t_oop->is_instance_field()) {
1178 assert(t_oop->offset() != Type::OffsetBot && t_oop->offset() != Type::OffsetTop, "");
1179 Node *region = opt_mem->in(0);
1180 uint cnt = opt_mem->req();
1181 for( uint i = 1; i < cnt; i++ ) {
1182 Node *in = opt_mem->in(i);
1183 if( in == NULL ) {
1184 region = NULL; // Wait stable graph
1185 break;
1186 }
1187 }
1188 if (region != NULL) {
1189 // Check for loop invariant.
1190 if (cnt == 3) {
1191 for( uint i = 1; i < cnt; i++ ) {
1192 Node *in = opt_mem->in(i);
1193 Node* m = MemNode::optimize_memory_chain(in, addr_t, phase);
1194 if (m == opt_mem) {
1195 set_req(MemNode::Memory, opt_mem->in(cnt - i)); // Skip this phi.
1196 return this;
1197 }
1198 }
1199 }
1200 // Split through Phi (see original code in loopopts.cpp).
1201 assert(phase->C->have_alias_type(addr_t), "instance should have alias type");
1202
1203 // Do nothing here if Identity will find a value
1204 // (to avoid infinite chain of value phis generation).
1205 if ( !phase->eqv(this, this->Identity(phase)) )
1206 return NULL;
1207
1208 const Type* this_type = this->bottom_type();
1209 int this_index = phase->C->get_alias_index(addr_t);
1210 int this_offset = addr_t->offset();
1211 int this_iid = addr_t->is_oopptr()->instance_id();
1212 int wins = 0;
1213 PhaseIterGVN *igvn = phase->is_IterGVN();
1214 Node *phi = new (igvn->C, region->req()) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
1215 for( uint i = 1; i < region->req(); i++ ) {
1216 Node *x;
1217 Node* the_clone = NULL;
1218 if( region->in(i) == phase->C->top() ) {
1219 x = phase->C->top(); // Dead path? Use a dead data op
1220 } else {
1221 x = this->clone(); // Else clone up the data op
1222 the_clone = x; // Remember for possible deletion.
1223 // Alter data node to use pre-phi inputs
1224 if( this->in(0) == region ) {
1225 x->set_req( 0, region->in(i) );
1226 } else {
1227 x->set_req( 0, NULL );
1228 }
1229 for( uint j = 1; j < this->req(); j++ ) {
1230 Node *in = this->in(j);
1231 if( in->is_Phi() && in->in(0) == region )
1232 x->set_req( j, in->in(i) ); // Use pre-Phi input for the clone
1233 }
1234 }
1235 // Check for a 'win' on some paths
1236 const Type *t = x->Value(igvn);
1237
1238 bool singleton = t->singleton();
1239
1240 // See comments in PhaseIdealLoop::split_thru_phi().
1241 if( singleton && t == Type::TOP ) {
1242 singleton &= region->is_Loop() && (i != LoopNode::EntryControl);
1243 }
1244
1245 if( singleton ) {
1246 wins++;
1247 x = igvn->makecon(t);
1248 } else {
1249 // We now call Identity to try to simplify the cloned node.
1250 // Note that some Identity methods call phase->type(this).
1251 // Make sure that the type array is big enough for
1252 // our new node, even though we may throw the node away.
1253 // (This tweaking with igvn only works because x is a new node.)
1254 igvn->set_type(x, t);
1255 Node *y = x->Identity(igvn);
1256 if( y != x ) {
1257 wins++;
1258 x = y;
1259 } else {
1260 y = igvn->hash_find(x);
1261 if( y ) {
1262 wins++;
1263 x = y;
1264 } else {
1265 // Else x is a new node we are keeping
1266 // We do not need register_new_node_with_optimizer
1267 // because set_type has already been called.
1268 igvn->_worklist.push(x);
1269 }
1270 }
1271 }
1272 if (x != the_clone && the_clone != NULL)
1273 igvn->remove_dead_node(the_clone);
1274 phi->set_req(i, x);
1275 }
1276 if( wins > 0 ) {
1277 // Record Phi
1278 igvn->register_new_node_with_optimizer(phi);
1279 return phi;
1280 } else {
1281 igvn->remove_dead_node(phi);
1282 }
1283 }
1284 }
1285 }
1286
1287 // Check for prior store with a different base or offset; make Load
1288 // independent. Skip through any number of them. Bail out if the stores
1289 // are in an endless dead cycle and report no progress. This is a key
1290 // transform for Reflection. However, if after skipping through the Stores
1291 // we can't then fold up against a prior store do NOT do the transform as
1292 // this amounts to using the 'Oracle' model of aliasing. It leaves the same
1293 // array memory alive twice: once for the hoisted Load and again after the
1294 // bypassed Store. This situation only works if EVERYBODY who does
1295 // anti-dependence work knows how to bypass. I.e. we need all
1296 // anti-dependence checks to ask the same Oracle. Right now, that Oracle is
1297 // the alias index stuff. So instead, peek through Stores and IFF we can
1298 // fold up, do so.
1299 Node* prev_mem = find_previous_store(phase);
1300 // Steps (a), (b): Walk past independent stores to find an exact match.
1301 if (prev_mem != NULL && prev_mem != in(MemNode::Memory)) {
1302 // (c) See if we can fold up on the spot, but don't fold up here.
1303 // Fold-up might require truncation (for LoadB/LoadS/LoadC) or
1304 // just return a prior value, which is done by Identity calls.
1305 if (can_see_stored_value(prev_mem, phase)) {
1306 // Make ready for step (d):
1307 set_req(MemNode::Memory, prev_mem);
1308 return this;
1309 }
1310 }
1311
1312 return NULL; // No further progress
1313 }
1314
1315 // Helper to recognize certain Klass fields which are invariant across
1316 // some group of array types (e.g., int[] or all T[] where T < Object).
1317 const Type*
1318 LoadNode::load_array_final_field(const TypeKlassPtr *tkls,
1319 ciKlass* klass) const {
1320 if (tkls->offset() == Klass::modifier_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
1321 // The field is Klass::_modifier_flags. Return its (constant) value.
1322 // (Folds up the 2nd indirection in aClassConstant.getModifiers().)
1323 assert(this->Opcode() == Op_LoadI, "must load an int from _modifier_flags");
1324 return TypeInt::make(klass->modifier_flags());
1325 }
1326 if (tkls->offset() == Klass::access_flags_offset_in_bytes() + (int)sizeof(oopDesc)) {
1327 // The field is Klass::_access_flags. Return its (constant) value.
1328 // (Folds up the 2nd indirection in Reflection.getClassAccessFlags(aClassConstant).)
1329 assert(this->Opcode() == Op_LoadI, "must load an int from _access_flags");
1330 return TypeInt::make(klass->access_flags());
1331 }
1332 if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)) {
1333 // The field is Klass::_layout_helper. Return its constant value if known.
1334 assert(this->Opcode() == Op_LoadI, "must load an int from _layout_helper");
1335 return TypeInt::make(klass->layout_helper());
1336 }
1337
1338 // No match.
1339 return NULL;
1340 }
1341
1342 //------------------------------Value-----------------------------------------
1343 const Type *LoadNode::Value( PhaseTransform *phase ) const {
1344 // Either input is TOP ==> the result is TOP
1345 Node* mem = in(MemNode::Memory);
1346 const Type *t1 = phase->type(mem);
1347 if (t1 == Type::TOP) return Type::TOP;
1348 Node* adr = in(MemNode::Address);
1349 const TypePtr* tp = phase->type(adr)->isa_ptr();
1350 if (tp == NULL || tp->empty()) return Type::TOP;
1351 int off = tp->offset();
1352 assert(off != Type::OffsetTop, "case covered by TypePtr::empty");
1353
1354 // Try to guess loaded type from pointer type
1355 if (tp->base() == Type::AryPtr) {
1356 const Type *t = tp->is_aryptr()->elem();
1357 // Don't do this for integer types. There is only potential profit if
1358 // the element type t is lower than _type; that is, for int types, if _type is
1359 // more restrictive than t. This only happens here if one is short and the other
1360 // char (both 16 bits), and in those cases we've made an intentional decision
1361 // to use one kind of load over the other. See AndINode::Ideal and 4965907.
1362 // Also, do not try to narrow the type for a LoadKlass, regardless of offset.
1363 //
1364 // Yes, it is possible to encounter an expression like (LoadKlass p1:(AddP x x 8))
1365 // where the _gvn.type of the AddP is wider than 8. This occurs when an earlier
1366 // copy p0 of (AddP x x 8) has been proven equal to p1, and the p0 has been
1367 // subsumed by p1. If p1 is on the worklist but has not yet been re-transformed,
1368 // it is possible that p1 will have a type like Foo*[int+]:NotNull*+any.
1369 // In fact, that could have been the original type of p1, and p1 could have
1370 // had an original form like p1:(AddP x x (LShiftL quux 3)), where the
1371 // expression (LShiftL quux 3) independently optimized to the constant 8.
1372 if ((t->isa_int() == NULL) && (t->isa_long() == NULL)
1373 && Opcode() != Op_LoadKlass) {
1374 // t might actually be lower than _type, if _type is a unique
1375 // concrete subclass of abstract class t.
1376 // Make sure the reference is not into the header, by comparing
1377 // the offset against the offset of the start of the array's data.
1378 // Different array types begin at slightly different offsets (12 vs. 16).
1379 // We choose T_BYTE as an example base type that is least restrictive
1380 // as to alignment, which will therefore produce the smallest
1381 // possible base offset.
1382 const int min_base_off = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1383 if ((uint)off >= (uint)min_base_off) { // is the offset beyond the header?
1384 const Type* jt = t->join(_type);
1385 // In any case, do not allow the join, per se, to empty out the type.
1386 if (jt->empty() && !t->empty()) {
1387 // This can happen if a interface-typed array narrows to a class type.
1388 jt = _type;
1389 }
1390
1391 if (EliminateAutoBox) {
1392 // The pointers in the autobox arrays are always non-null
1393 Node* base = in(Address)->in(AddPNode::Base);
1394 if (base != NULL) {
1395 Compile::AliasType* atp = phase->C->alias_type(base->adr_type());
1396 if (is_autobox_cache(atp)) {
1397 return jt->join(TypePtr::NOTNULL)->is_ptr();
1398 }
1399 }
1400 }
1401 return jt;
1402 }
1403 }
1404 } else if (tp->base() == Type::InstPtr) {
1405 assert( off != Type::OffsetBot ||
1406 // arrays can be cast to Objects
1407 tp->is_oopptr()->klass()->is_java_lang_Object() ||
1408 // unsafe field access may not have a constant offset
1409 phase->C->has_unsafe_access(),
1410 "Field accesses must be precise" );
1411 // For oop loads, we expect the _type to be precise
1412 } else if (tp->base() == Type::KlassPtr) {
1413 assert( off != Type::OffsetBot ||
1414 // arrays can be cast to Objects
1415 tp->is_klassptr()->klass()->is_java_lang_Object() ||
1416 // also allow array-loading from the primary supertype
1417 // array during subtype checks
1418 Opcode() == Op_LoadKlass,
1419 "Field accesses must be precise" );
1420 // For klass/static loads, we expect the _type to be precise
1421 }
1422
1423 const TypeKlassPtr *tkls = tp->isa_klassptr();
1424 if (tkls != NULL && !StressReflectiveCode) {
1425 ciKlass* klass = tkls->klass();
1426 if (klass->is_loaded() && tkls->klass_is_exact()) {
1427 // We are loading a field from a Klass metaobject whose identity
1428 // is known at compile time (the type is "exact" or "precise").
1429 // Check for fields we know are maintained as constants by the VM.
1430 if (tkls->offset() == Klass::super_check_offset_offset_in_bytes() + (int)sizeof(oopDesc)) {
1431 // The field is Klass::_super_check_offset. Return its (constant) value.
1432 // (Folds up type checking code.)
1433 assert(Opcode() == Op_LoadI, "must load an int from _super_check_offset");
1434 return TypeInt::make(klass->super_check_offset());
1435 }
1436 // Compute index into primary_supers array
1437 juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
1438 // Check for overflowing; use unsigned compare to handle the negative case.
1439 if( depth < ciKlass::primary_super_limit() ) {
1440 // The field is an element of Klass::_primary_supers. Return its (constant) value.
1441 // (Folds up type checking code.)
1442 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1443 ciKlass *ss = klass->super_of_depth(depth);
1444 return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1445 }
1446 const Type* aift = load_array_final_field(tkls, klass);
1447 if (aift != NULL) return aift;
1448 if (tkls->offset() == in_bytes(arrayKlass::component_mirror_offset()) + (int)sizeof(oopDesc)
1449 && klass->is_array_klass()) {
1450 // The field is arrayKlass::_component_mirror. Return its (constant) value.
1451 // (Folds up aClassConstant.getComponentType, common in Arrays.copyOf.)
1452 assert(Opcode() == Op_LoadP, "must load an oop from _component_mirror");
1453 return TypeInstPtr::make(klass->as_array_klass()->component_mirror());
1454 }
1455 if (tkls->offset() == Klass::java_mirror_offset_in_bytes() + (int)sizeof(oopDesc)) {
1456 // The field is Klass::_java_mirror. Return its (constant) value.
1457 // (Folds up the 2nd indirection in anObjConstant.getClass().)
1458 assert(Opcode() == Op_LoadP, "must load an oop from _java_mirror");
1459 return TypeInstPtr::make(klass->java_mirror());
1460 }
1461 }
1462
1463 // We can still check if we are loading from the primary_supers array at a
1464 // shallow enough depth. Even though the klass is not exact, entries less
1465 // than or equal to its super depth are correct.
1466 if (klass->is_loaded() ) {
1467 ciType *inner = klass->klass();
1468 while( inner->is_obj_array_klass() )
1469 inner = inner->as_obj_array_klass()->base_element_type();
1470 if( inner->is_instance_klass() &&
1471 !inner->as_instance_klass()->flags().is_interface() ) {
1472 // Compute index into primary_supers array
1473 juint depth = (tkls->offset() - (Klass::primary_supers_offset_in_bytes() + (int)sizeof(oopDesc))) / sizeof(klassOop);
1474 // Check for overflowing; use unsigned compare to handle the negative case.
1475 if( depth < ciKlass::primary_super_limit() &&
1476 depth <= klass->super_depth() ) { // allow self-depth checks to handle self-check case
1477 // The field is an element of Klass::_primary_supers. Return its (constant) value.
1478 // (Folds up type checking code.)
1479 assert(Opcode() == Op_LoadKlass, "must load a klass from _primary_supers");
1480 ciKlass *ss = klass->super_of_depth(depth);
1481 return ss ? TypeKlassPtr::make(ss) : TypePtr::NULL_PTR;
1482 }
1483 }
1484 }
1485
1486 // If the type is enough to determine that the thing is not an array,
1487 // we can give the layout_helper a positive interval type.
1488 // This will help short-circuit some reflective code.
1489 if (tkls->offset() == Klass::layout_helper_offset_in_bytes() + (int)sizeof(oopDesc)
1490 && !klass->is_array_klass() // not directly typed as an array
1491 && !klass->is_interface() // specifically not Serializable & Cloneable
1492 && !klass->is_java_lang_Object() // not the supertype of all T[]
1493 ) {
1494 // Note: When interfaces are reliable, we can narrow the interface
1495 // test to (klass != Serializable && klass != Cloneable).
1496 assert(Opcode() == Op_LoadI, "must load an int from _layout_helper");
1497 jint min_size = Klass::instance_layout_helper(oopDesc::header_size(), false);
1498 // The key property of this type is that it folds up tests
1499 // for array-ness, since it proves that the layout_helper is positive.
1500 // Thus, a generic value like the basic object layout helper works fine.
1501 return TypeInt::make(min_size, max_jint, Type::WidenMin);
1502 }
1503 }
1504
1505 // If we are loading from a freshly-allocated object, produce a zero,
1506 // if the load is provably beyond the header of the object.
1507 // (Also allow a variable load from a fresh array to produce zero.)
1508 if (ReduceFieldZeroing) {
1509 Node* value = can_see_stored_value(mem,phase);
1510 if (value != NULL && value->is_Con())
1511 return value->bottom_type();
1512 }
1513
1514 const TypeOopPtr *tinst = tp->isa_oopptr();
1515 if (tinst != NULL && tinst->is_instance_field()) {
1516 // If we have an instance type and our memory input is the
1517 // programs's initial memory state, there is no matching store,
1518 // so just return a zero of the appropriate type
1519 Node *mem = in(MemNode::Memory);
1520 if (mem->is_Parm() && mem->in(0)->is_Start()) {
1521 assert(mem->as_Parm()->_con == TypeFunc::Memory, "must be memory Parm");
1522 return Type::get_zero_type(_type->basic_type());
1523 }
1524 }
1525 return _type;
1526 }
1527
1528 //------------------------------match_edge-------------------------------------
1529 // Do we Match on this edge index or not? Match only the address.
1530 uint LoadNode::match_edge(uint idx) const {
1531 return idx == MemNode::Address;
1532 }
1533
1534 //--------------------------LoadBNode::Ideal--------------------------------------
1535 //
1536 // If the previous store is to the same address as this load,
1537 // and the value stored was larger than a byte, replace this load
1538 // with the value stored truncated to a byte. If no truncation is
1539 // needed, the replacement is done in LoadNode::Identity().
1540 //
1541 Node *LoadBNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1542 Node* mem = in(MemNode::Memory);
1543 Node* value = can_see_stored_value(mem,phase);
1544 if( value && !phase->type(value)->higher_equal( _type ) ) {
1545 Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(24)) );
1546 return new (phase->C, 3) RShiftINode(result, phase->intcon(24));
1547 }
1548 // Identity call will handle the case where truncation is not needed.
1549 return LoadNode::Ideal(phase, can_reshape);
1550 }
1551
1552 //--------------------------LoadCNode::Ideal--------------------------------------
1553 //
1554 // If the previous store is to the same address as this load,
1555 // and the value stored was larger than a char, replace this load
1556 // with the value stored truncated to a char. If no truncation is
1557 // needed, the replacement is done in LoadNode::Identity().
1558 //
1559 Node *LoadCNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1560 Node* mem = in(MemNode::Memory);
1561 Node* value = can_see_stored_value(mem,phase);
1562 if( value && !phase->type(value)->higher_equal( _type ) )
1563 return new (phase->C, 3) AndINode(value,phase->intcon(0xFFFF));
1564 // Identity call will handle the case where truncation is not needed.
1565 return LoadNode::Ideal(phase, can_reshape);
1566 }
1567
1568 //--------------------------LoadSNode::Ideal--------------------------------------
1569 //
1570 // If the previous store is to the same address as this load,
1571 // and the value stored was larger than a short, replace this load
1572 // with the value stored truncated to a short. If no truncation is
1573 // needed, the replacement is done in LoadNode::Identity().
1574 //
1575 Node *LoadSNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1576 Node* mem = in(MemNode::Memory);
1577 Node* value = can_see_stored_value(mem,phase);
1578 if( value && !phase->type(value)->higher_equal( _type ) ) {
1579 Node *result = phase->transform( new (phase->C, 3) LShiftINode(value, phase->intcon(16)) );
1580 return new (phase->C, 3) RShiftINode(result, phase->intcon(16));
1581 }
1582 // Identity call will handle the case where truncation is not needed.
1583 return LoadNode::Ideal(phase, can_reshape);
1584 }
1585
1586 //=============================================================================
1587 //------------------------------Value------------------------------------------
1588 const Type *LoadKlassNode::Value( PhaseTransform *phase ) const {
1589 // Either input is TOP ==> the result is TOP
1590 const Type *t1 = phase->type( in(MemNode::Memory) );
1591 if (t1 == Type::TOP) return Type::TOP;
1592 Node *adr = in(MemNode::Address);
1593 const Type *t2 = phase->type( adr );
1594 if (t2 == Type::TOP) return Type::TOP;
1595 const TypePtr *tp = t2->is_ptr();
1596 if (TypePtr::above_centerline(tp->ptr()) ||
1597 tp->ptr() == TypePtr::Null) return Type::TOP;
1598
1599 // Return a more precise klass, if possible
1600 const TypeInstPtr *tinst = tp->isa_instptr();
1601 if (tinst != NULL) {
1602 ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
1603 int offset = tinst->offset();
1604 if (ik == phase->C->env()->Class_klass()
1605 && (offset == java_lang_Class::klass_offset_in_bytes() ||
1606 offset == java_lang_Class::array_klass_offset_in_bytes())) {
1607 // We are loading a special hidden field from a Class mirror object,
1608 // the field which points to the VM's Klass metaobject.
1609 ciType* t = tinst->java_mirror_type();
1610 // java_mirror_type returns non-null for compile-time Class constants.
1611 if (t != NULL) {
1612 // constant oop => constant klass
1613 if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
1614 return TypeKlassPtr::make(ciArrayKlass::make(t));
1615 }
1616 if (!t->is_klass()) {
1617 // a primitive Class (e.g., int.class) has NULL for a klass field
1618 return TypePtr::NULL_PTR;
1619 }
1620 // (Folds up the 1st indirection in aClassConstant.getModifiers().)
1621 return TypeKlassPtr::make(t->as_klass());
1622 }
1623 // non-constant mirror, so we can't tell what's going on
1624 }
1625 if( !ik->is_loaded() )
1626 return _type; // Bail out if not loaded
1627 if (offset == oopDesc::klass_offset_in_bytes()) {
1628 if (tinst->klass_is_exact()) {
1629 return TypeKlassPtr::make(ik);
1630 }
1631 // See if we can become precise: no subklasses and no interface
1632 // (Note: We need to support verified interfaces.)
1633 if (!ik->is_interface() && !ik->has_subklass()) {
1634 //assert(!UseExactTypes, "this code should be useless with exact types");
1635 // Add a dependence; if any subclass added we need to recompile
1636 if (!ik->is_final()) {
1637 // %%% should use stronger assert_unique_concrete_subtype instead
1638 phase->C->dependencies()->assert_leaf_type(ik);
1639 }
1640 // Return precise klass
1641 return TypeKlassPtr::make(ik);
1642 }
1643
1644 // Return root of possible klass
1645 return TypeKlassPtr::make(TypePtr::NotNull, ik, 0/*offset*/);
1646 }
1647 }
1648
1649 // Check for loading klass from an array
1650 const TypeAryPtr *tary = tp->isa_aryptr();
1651 if( tary != NULL ) {
1652 ciKlass *tary_klass = tary->klass();
1653 if (tary_klass != NULL // can be NULL when at BOTTOM or TOP
1654 && tary->offset() == oopDesc::klass_offset_in_bytes()) {
1655 if (tary->klass_is_exact()) {
1656 return TypeKlassPtr::make(tary_klass);
1657 }
1658 ciArrayKlass *ak = tary->klass()->as_array_klass();
1659 // If the klass is an object array, we defer the question to the
1660 // array component klass.
1661 if( ak->is_obj_array_klass() ) {
1662 assert( ak->is_loaded(), "" );
1663 ciKlass *base_k = ak->as_obj_array_klass()->base_element_klass();
1664 if( base_k->is_loaded() && base_k->is_instance_klass() ) {
1665 ciInstanceKlass* ik = base_k->as_instance_klass();
1666 // See if we can become precise: no subklasses and no interface
1667 if (!ik->is_interface() && !ik->has_subklass()) {
1668 //assert(!UseExactTypes, "this code should be useless with exact types");
1669 // Add a dependence; if any subclass added we need to recompile
1670 if (!ik->is_final()) {
1671 phase->C->dependencies()->assert_leaf_type(ik);
1672 }
1673 // Return precise array klass
1674 return TypeKlassPtr::make(ak);
1675 }
1676 }
1677 return TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
1678 } else { // Found a type-array?
1679 //assert(!UseExactTypes, "this code should be useless with exact types");
1680 assert( ak->is_type_array_klass(), "" );
1681 return TypeKlassPtr::make(ak); // These are always precise
1682 }
1683 }
1684 }
1685
1686 // Check for loading klass from an array klass
1687 const TypeKlassPtr *tkls = tp->isa_klassptr();
1688 if (tkls != NULL && !StressReflectiveCode) {
1689 ciKlass* klass = tkls->klass();
1690 if( !klass->is_loaded() )
1691 return _type; // Bail out if not loaded
1692 if( klass->is_obj_array_klass() &&
1693 (uint)tkls->offset() == objArrayKlass::element_klass_offset_in_bytes() + sizeof(oopDesc)) {
1694 ciKlass* elem = klass->as_obj_array_klass()->element_klass();
1695 // // Always returning precise element type is incorrect,
1696 // // e.g., element type could be object and array may contain strings
1697 // return TypeKlassPtr::make(TypePtr::Constant, elem, 0);
1698
1699 // The array's TypeKlassPtr was declared 'precise' or 'not precise'
1700 // according to the element type's subclassing.
1701 return TypeKlassPtr::make(tkls->ptr(), elem, 0/*offset*/);
1702 }
1703 if( klass->is_instance_klass() && tkls->klass_is_exact() &&
1704 (uint)tkls->offset() == Klass::super_offset_in_bytes() + sizeof(oopDesc)) {
1705 ciKlass* sup = klass->as_instance_klass()->super();
1706 // The field is Klass::_super. Return its (constant) value.
1707 // (Folds up the 2nd indirection in aClassConstant.getSuperClass().)
1708 return sup ? TypeKlassPtr::make(sup) : TypePtr::NULL_PTR;
1709 }
1710 }
1711
1712 // Bailout case
1713 return LoadNode::Value(phase);
1714 }
1715
1716 //------------------------------Identity---------------------------------------
1717 // To clean up reflective code, simplify k.java_mirror.as_klass to plain k.
1718 // Also feed through the klass in Allocate(...klass...)._klass.
1719 Node* LoadKlassNode::Identity( PhaseTransform *phase ) {
1720 Node* x = LoadNode::Identity(phase);
1721 if (x != this) return x;
1722
1723 // Take apart the address into an oop and and offset.
1724 // Return 'this' if we cannot.
1725 Node* adr = in(MemNode::Address);
1726 intptr_t offset = 0;
1727 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
1728 if (base == NULL) return this;
1729 const TypeOopPtr* toop = phase->type(adr)->isa_oopptr();
1730 if (toop == NULL) return this;
1731
1732 // We can fetch the klass directly through an AllocateNode.
1733 // This works even if the klass is not constant (clone or newArray).
1734 if (offset == oopDesc::klass_offset_in_bytes()) {
1735 Node* allocated_klass = AllocateNode::Ideal_klass(base, phase);
1736 if (allocated_klass != NULL) {
1737 return allocated_klass;
1738 }
1739 }
1740
1741 // Simplify k.java_mirror.as_klass to plain k, where k is a klassOop.
1742 // Simplify ak.component_mirror.array_klass to plain ak, ak an arrayKlass.
1743 // See inline_native_Class_query for occurrences of these patterns.
1744 // Java Example: x.getClass().isAssignableFrom(y)
1745 // Java Example: Array.newInstance(x.getClass().getComponentType(), n)
1746 //
1747 // This improves reflective code, often making the Class
1748 // mirror go completely dead. (Current exception: Class
1749 // mirrors may appear in debug info, but we could clean them out by
1750 // introducing a new debug info operator for klassOop.java_mirror).
1751 if (toop->isa_instptr() && toop->klass() == phase->C->env()->Class_klass()
1752 && (offset == java_lang_Class::klass_offset_in_bytes() ||
1753 offset == java_lang_Class::array_klass_offset_in_bytes())) {
1754 // We are loading a special hidden field from a Class mirror,
1755 // the field which points to its Klass or arrayKlass metaobject.
1756 if (base->is_Load()) {
1757 Node* adr2 = base->in(MemNode::Address);
1758 const TypeKlassPtr* tkls = phase->type(adr2)->isa_klassptr();
1759 if (tkls != NULL && !tkls->empty()
1760 && (tkls->klass()->is_instance_klass() ||
1761 tkls->klass()->is_array_klass())
1762 && adr2->is_AddP()
1763 ) {
1764 int mirror_field = Klass::java_mirror_offset_in_bytes();
1765 if (offset == java_lang_Class::array_klass_offset_in_bytes()) {
1766 mirror_field = in_bytes(arrayKlass::component_mirror_offset());
1767 }
1768 if (tkls->offset() == mirror_field + (int)sizeof(oopDesc)) {
1769 return adr2->in(AddPNode::Base);
1770 }
1771 }
1772 }
1773 }
1774
1775 return this;
1776 }
1777
1778 //------------------------------Value-----------------------------------------
1779 const Type *LoadRangeNode::Value( PhaseTransform *phase ) const {
1780 // Either input is TOP ==> the result is TOP
1781 const Type *t1 = phase->type( in(MemNode::Memory) );
1782 if( t1 == Type::TOP ) return Type::TOP;
1783 Node *adr = in(MemNode::Address);
1784 const Type *t2 = phase->type( adr );
1785 if( t2 == Type::TOP ) return Type::TOP;
1786 const TypePtr *tp = t2->is_ptr();
1787 if (TypePtr::above_centerline(tp->ptr())) return Type::TOP;
1788 const TypeAryPtr *tap = tp->isa_aryptr();
1789 if( !tap ) return _type;
1790 return tap->size();
1791 }
1792
1793 //------------------------------Identity---------------------------------------
1794 // Feed through the length in AllocateArray(...length...)._length.
1795 Node* LoadRangeNode::Identity( PhaseTransform *phase ) {
1796 Node* x = LoadINode::Identity(phase);
1797 if (x != this) return x;
1798
1799 // Take apart the address into an oop and and offset.
1800 // Return 'this' if we cannot.
1801 Node* adr = in(MemNode::Address);
1802 intptr_t offset = 0;
1803 Node* base = AddPNode::Ideal_base_and_offset(adr, phase, offset);
1804 if (base == NULL) return this;
1805 const TypeAryPtr* tary = phase->type(adr)->isa_aryptr();
1806 if (tary == NULL) return this;
1807
1808 // We can fetch the length directly through an AllocateArrayNode.
1809 // This works even if the length is not constant (clone or newArray).
1810 if (offset == arrayOopDesc::length_offset_in_bytes()) {
1811 Node* allocated_length = AllocateArrayNode::Ideal_length(base, phase);
1812 if (allocated_length != NULL) {
1813 return allocated_length;
1814 }
1815 }
1816
1817 return this;
1818
1819 }
1820 //=============================================================================
1821 //---------------------------StoreNode::make-----------------------------------
1822 // Polymorphic factory method:
1823 StoreNode* StoreNode::make( PhaseGVN& gvn, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val, BasicType bt ) {
1824 Compile* C = gvn.C;
1825
1826 switch (bt) {
1827 case T_BOOLEAN:
1828 case T_BYTE: return new (C, 4) StoreBNode(ctl, mem, adr, adr_type, val);
1829 case T_INT: return new (C, 4) StoreINode(ctl, mem, adr, adr_type, val);
1830 case T_CHAR:
1831 case T_SHORT: return new (C, 4) StoreCNode(ctl, mem, adr, adr_type, val);
1832 case T_LONG: return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val);
1833 case T_FLOAT: return new (C, 4) StoreFNode(ctl, mem, adr, adr_type, val);
1834 case T_DOUBLE: return new (C, 4) StoreDNode(ctl, mem, adr, adr_type, val);
1835 case T_ADDRESS:
1836 case T_OBJECT:
1837 #ifdef _LP64
1838 if (adr->bottom_type()->is_narrow() ||
1839 (UseCompressedOops && val->bottom_type()->isa_klassptr() &&
1840 adr->bottom_type()->isa_rawptr())) {
1841 const TypePtr* type = val->bottom_type()->is_ptr();
1842 Node* cp = EncodePNode::encode(&gvn, val);
1843 return new (C, 4) StoreNNode(ctl, mem, adr, adr_type, cp);
1844 } else
1845 #endif
1846 {
1847 return new (C, 4) StorePNode(ctl, mem, adr, adr_type, val);
1848 }
1849 }
1850 ShouldNotReachHere();
1851 return (StoreNode*)NULL;
1852 }
1853
1854 StoreLNode* StoreLNode::make_atomic(Compile *C, Node* ctl, Node* mem, Node* adr, const TypePtr* adr_type, Node* val) {
1855 bool require_atomic = true;
1856 return new (C, 4) StoreLNode(ctl, mem, adr, adr_type, val, require_atomic);
1857 }
1858
1859
1860 //--------------------------bottom_type----------------------------------------
1861 const Type *StoreNode::bottom_type() const {
1862 return Type::MEMORY;
1863 }
1864
1865 //------------------------------hash-------------------------------------------
1866 uint StoreNode::hash() const {
1867 // unroll addition of interesting fields
1868 //return (uintptr_t)in(Control) + (uintptr_t)in(Memory) + (uintptr_t)in(Address) + (uintptr_t)in(ValueIn);
1869
1870 // Since they are not commoned, do not hash them:
1871 return NO_HASH;
1872 }
1873
1874 //------------------------------Ideal------------------------------------------
1875 // Change back-to-back Store(, p, x) -> Store(m, p, y) to Store(m, p, x).
1876 // When a store immediately follows a relevant allocation/initialization,
1877 // try to capture it into the initialization, or hoist it above.
1878 Node *StoreNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1879 Node* p = MemNode::Ideal_common(phase, can_reshape);
1880 if (p) return (p == NodeSentinel) ? NULL : p;
1881
1882 Node* mem = in(MemNode::Memory);
1883 Node* address = in(MemNode::Address);
1884
1885 // Back-to-back stores to same address? Fold em up.
1886 // Generally unsafe if I have intervening uses...
1887 if (mem->is_Store() && phase->eqv_uncast(mem->in(MemNode::Address), address)) {
1888 // Looking at a dead closed cycle of memory?
1889 assert(mem != mem->in(MemNode::Memory), "dead loop in StoreNode::Ideal");
1890
1891 assert(Opcode() == mem->Opcode() ||
1892 phase->C->get_alias_index(adr_type()) == Compile::AliasIdxRaw,
1893 "no mismatched stores, except on raw memory");
1894
1895 if (mem->outcnt() == 1 && // check for intervening uses
1896 mem->as_Store()->memory_size() <= this->memory_size()) {
1897 // If anybody other than 'this' uses 'mem', we cannot fold 'mem' away.
1898 // For example, 'mem' might be the final state at a conditional return.
1899 // Or, 'mem' might be used by some node which is live at the same time
1900 // 'this' is live, which might be unschedulable. So, require exactly
1901 // ONE user, the 'this' store, until such time as we clone 'mem' for
1902 // each of 'mem's uses (thus making the exactly-1-user-rule hold true).
1903 if (can_reshape) { // (%%% is this an anachronism?)
1904 set_req_X(MemNode::Memory, mem->in(MemNode::Memory),
1905 phase->is_IterGVN());
1906 } else {
1907 // It's OK to do this in the parser, since DU info is always accurate,
1908 // and the parser always refers to nodes via SafePointNode maps.
1909 set_req(MemNode::Memory, mem->in(MemNode::Memory));
1910 }
1911 return this;
1912 }
1913 }
1914
1915 // Capture an unaliased, unconditional, simple store into an initializer.
1916 // Or, if it is independent of the allocation, hoist it above the allocation.
1917 if (ReduceFieldZeroing && /*can_reshape &&*/
1918 mem->is_Proj() && mem->in(0)->is_Initialize()) {
1919 InitializeNode* init = mem->in(0)->as_Initialize();
1920 intptr_t offset = init->can_capture_store(this, phase);
1921 if (offset > 0) {
1922 Node* moved = init->capture_store(this, offset, phase);
1923 // If the InitializeNode captured me, it made a raw copy of me,
1924 // and I need to disappear.
1925 if (moved != NULL) {
1926 // %%% hack to ensure that Ideal returns a new node:
1927 mem = MergeMemNode::make(phase->C, mem);
1928 return mem; // fold me away
1929 }
1930 }
1931 }
1932
1933 return NULL; // No further progress
1934 }
1935
1936 //------------------------------Value-----------------------------------------
1937 const Type *StoreNode::Value( PhaseTransform *phase ) const {
1938 // Either input is TOP ==> the result is TOP
1939 const Type *t1 = phase->type( in(MemNode::Memory) );
1940 if( t1 == Type::TOP ) return Type::TOP;
1941 const Type *t2 = phase->type( in(MemNode::Address) );
1942 if( t2 == Type::TOP ) return Type::TOP;
1943 const Type *t3 = phase->type( in(MemNode::ValueIn) );
1944 if( t3 == Type::TOP ) return Type::TOP;
1945 return Type::MEMORY;
1946 }
1947
1948 //------------------------------Identity---------------------------------------
1949 // Remove redundant stores:
1950 // Store(m, p, Load(m, p)) changes to m.
1951 // Store(, p, x) -> Store(m, p, x) changes to Store(m, p, x).
1952 Node *StoreNode::Identity( PhaseTransform *phase ) {
1953 Node* mem = in(MemNode::Memory);
1954 Node* adr = in(MemNode::Address);
1955 Node* val = in(MemNode::ValueIn);
1956
1957 // Load then Store? Then the Store is useless
1958 if (val->is_Load() &&
1959 phase->eqv_uncast( val->in(MemNode::Address), adr ) &&
1960 phase->eqv_uncast( val->in(MemNode::Memory ), mem ) &&
1961 val->as_Load()->store_Opcode() == Opcode()) {
1962 return mem;
1963 }
1964
1965 // Two stores in a row of the same value?
1966 if (mem->is_Store() &&
1967 phase->eqv_uncast( mem->in(MemNode::Address), adr ) &&
1968 phase->eqv_uncast( mem->in(MemNode::ValueIn), val ) &&
1969 mem->Opcode() == Opcode()) {
1970 return mem;
1971 }
1972
1973 // Store of zero anywhere into a freshly-allocated object?
1974 // Then the store is useless.
1975 // (It must already have been captured by the InitializeNode.)
1976 if (ReduceFieldZeroing && phase->type(val)->is_zero_type()) {
1977 // a newly allocated object is already all-zeroes everywhere
1978 if (mem->is_Proj() && mem->in(0)->is_Allocate()) {
1979 return mem;
1980 }
1981
1982 // the store may also apply to zero-bits in an earlier object
1983 Node* prev_mem = find_previous_store(phase);
1984 // Steps (a), (b): Walk past independent stores to find an exact match.
1985 if (prev_mem != NULL) {
1986 Node* prev_val = can_see_stored_value(prev_mem, phase);
1987 if (prev_val != NULL && phase->eqv(prev_val, val)) {
1988 // prev_val and val might differ by a cast; it would be good
1989 // to keep the more informative of the two.
1990 return mem;
1991 }
1992 }
1993 }
1994
1995 return this;
1996 }
1997
1998 //------------------------------match_edge-------------------------------------
1999 // Do we Match on this edge index or not? Match only memory & value
2000 uint StoreNode::match_edge(uint idx) const {
2001 return idx == MemNode::Address || idx == MemNode::ValueIn;
2002 }
2003
2004 //------------------------------cmp--------------------------------------------
2005 // Do not common stores up together. They generally have to be split
2006 // back up anyways, so do not bother.
2007 uint StoreNode::cmp( const Node &n ) const {
2008 return (&n == this); // Always fail except on self
2009 }
2010
2011 //------------------------------Ideal_masked_input-----------------------------
2012 // Check for a useless mask before a partial-word store
2013 // (StoreB ... (AndI valIn conIa) )
2014 // If (conIa & mask == mask) this simplifies to
2015 // (StoreB ... (valIn) )
2016 Node *StoreNode::Ideal_masked_input(PhaseGVN *phase, uint mask) {
2017 Node *val = in(MemNode::ValueIn);
2018 if( val->Opcode() == Op_AndI ) {
2019 const TypeInt *t = phase->type( val->in(2) )->isa_int();
2020 if( t && t->is_con() && (t->get_con() & mask) == mask ) {
2021 set_req(MemNode::ValueIn, val->in(1));
2022 return this;
2023 }
2024 }
2025 return NULL;
2026 }
2027
2028
2029 //------------------------------Ideal_sign_extended_input----------------------
2030 // Check for useless sign-extension before a partial-word store
2031 // (StoreB ... (RShiftI _ (LShiftI _ valIn conIL ) conIR) )
2032 // If (conIL == conIR && conIR <= num_bits) this simplifies to
2033 // (StoreB ... (valIn) )
2034 Node *StoreNode::Ideal_sign_extended_input(PhaseGVN *phase, int num_bits) {
2035 Node *val = in(MemNode::ValueIn);
2036 if( val->Opcode() == Op_RShiftI ) {
2037 const TypeInt *t = phase->type( val->in(2) )->isa_int();
2038 if( t && t->is_con() && (t->get_con() <= num_bits) ) {
2039 Node *shl = val->in(1);
2040 if( shl->Opcode() == Op_LShiftI ) {
2041 const TypeInt *t2 = phase->type( shl->in(2) )->isa_int();
2042 if( t2 && t2->is_con() && (t2->get_con() == t->get_con()) ) {
2043 set_req(MemNode::ValueIn, shl->in(1));
2044 return this;
2045 }
2046 }
2047 }
2048 }
2049 return NULL;
2050 }
2051
2052 //------------------------------value_never_loaded-----------------------------------
2053 // Determine whether there are any possible loads of the value stored.
2054 // For simplicity, we actually check if there are any loads from the
2055 // address stored to, not just for loads of the value stored by this node.
2056 //
2057 bool StoreNode::value_never_loaded( PhaseTransform *phase) const {
2058 Node *adr = in(Address);
2059 const TypeOopPtr *adr_oop = phase->type(adr)->isa_oopptr();
2060 if (adr_oop == NULL)
2061 return false;
2062 if (!adr_oop->is_instance_field())
2063 return false; // if not a distinct instance, there may be aliases of the address
2064 for (DUIterator_Fast imax, i = adr->fast_outs(imax); i < imax; i++) {
2065 Node *use = adr->fast_out(i);
2066 int opc = use->Opcode();
2067 if (use->is_Load() || use->is_LoadStore()) {
2068 return false;
2069 }
2070 }
2071 return true;
2072 }
2073
2074 //=============================================================================
2075 //------------------------------Ideal------------------------------------------
2076 // If the store is from an AND mask that leaves the low bits untouched, then
2077 // we can skip the AND operation. If the store is from a sign-extension
2078 // (a left shift, then right shift) we can skip both.
2079 Node *StoreBNode::Ideal(PhaseGVN *phase, bool can_reshape){
2080 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFF);
2081 if( progress != NULL ) return progress;
2082
2083 progress = StoreNode::Ideal_sign_extended_input(phase, 24);
2084 if( progress != NULL ) return progress;
2085
2086 // Finally check the default case
2087 return StoreNode::Ideal(phase, can_reshape);
2088 }
2089
2090 //=============================================================================
2091 //------------------------------Ideal------------------------------------------
2092 // If the store is from an AND mask that leaves the low bits untouched, then
2093 // we can skip the AND operation
2094 Node *StoreCNode::Ideal(PhaseGVN *phase, bool can_reshape){
2095 Node *progress = StoreNode::Ideal_masked_input(phase, 0xFFFF);
2096 if( progress != NULL ) return progress;
2097
2098 progress = StoreNode::Ideal_sign_extended_input(phase, 16);
2099 if( progress != NULL ) return progress;
2100
2101 // Finally check the default case
2102 return StoreNode::Ideal(phase, can_reshape);
2103 }
2104
2105 //=============================================================================
2106 //------------------------------Identity---------------------------------------
2107 Node *StoreCMNode::Identity( PhaseTransform *phase ) {
2108 // No need to card mark when storing a null ptr
2109 Node* my_store = in(MemNode::OopStore);
2110 if (my_store->is_Store()) {
2111 const Type *t1 = phase->type( my_store->in(MemNode::ValueIn) );
2112 if( t1 == TypePtr::NULL_PTR ) {
2113 return in(MemNode::Memory);
2114 }
2115 }
2116 return this;
2117 }
2118
2119 //------------------------------Value-----------------------------------------
2120 const Type *StoreCMNode::Value( PhaseTransform *phase ) const {
2121 // Either input is TOP ==> the result is TOP
2122 const Type *t = phase->type( in(MemNode::Memory) );
2123 if( t == Type::TOP ) return Type::TOP;
2124 t = phase->type( in(MemNode::Address) );
2125 if( t == Type::TOP ) return Type::TOP;
2126 t = phase->type( in(MemNode::ValueIn) );
2127 if( t == Type::TOP ) return Type::TOP;
2128 // If extra input is TOP ==> the result is TOP
2129 t = phase->type( in(MemNode::OopStore) );
2130 if( t == Type::TOP ) return Type::TOP;
2131
2132 return StoreNode::Value( phase );
2133 }
2134
2135
2136 //=============================================================================
2137 //----------------------------------SCMemProjNode------------------------------
2138 const Type * SCMemProjNode::Value( PhaseTransform *phase ) const
2139 {
2140 return bottom_type();
2141 }
2142
2143 //=============================================================================
2144 LoadStoreNode::LoadStoreNode( Node *c, Node *mem, Node *adr, Node *val, Node *ex ) : Node(5) {
2145 init_req(MemNode::Control, c );
2146 init_req(MemNode::Memory , mem);
2147 init_req(MemNode::Address, adr);
2148 init_req(MemNode::ValueIn, val);
2149 init_req( ExpectedIn, ex );
2150 init_class_id(Class_LoadStore);
2151
2152 }
2153
2154 //=============================================================================
2155 //-------------------------------adr_type--------------------------------------
2156 // Do we Match on this edge index or not? Do not match memory
2157 const TypePtr* ClearArrayNode::adr_type() const {
2158 Node *adr = in(3);
2159 return MemNode::calculate_adr_type(adr->bottom_type());
2160 }
2161
2162 //------------------------------match_edge-------------------------------------
2163 // Do we Match on this edge index or not? Do not match memory
2164 uint ClearArrayNode::match_edge(uint idx) const {
2165 return idx > 1;
2166 }
2167
2168 //------------------------------Identity---------------------------------------
2169 // Clearing a zero length array does nothing
2170 Node *ClearArrayNode::Identity( PhaseTransform *phase ) {
2171 return phase->type(in(2))->higher_equal(TypeX::ZERO) ? in(1) : this;
2172 }
2173
2174 //------------------------------Idealize---------------------------------------
2175 // Clearing a short array is faster with stores
2176 Node *ClearArrayNode::Ideal(PhaseGVN *phase, bool can_reshape){
2177 const int unit = BytesPerLong;
2178 const TypeX* t = phase->type(in(2))->isa_intptr_t();
2179 if (!t) return NULL;
2180 if (!t->is_con()) return NULL;
2181 intptr_t raw_count = t->get_con();
2182 intptr_t size = raw_count;
2183 if (!Matcher::init_array_count_is_in_bytes) size *= unit;
2184 // Clearing nothing uses the Identity call.
2185 // Negative clears are possible on dead ClearArrays
2186 // (see jck test stmt114.stmt11402.val).
2187 if (size <= 0 || size % unit != 0) return NULL;
2188 intptr_t count = size / unit;
2189 // Length too long; use fast hardware clear
2190 if (size > Matcher::init_array_short_size) return NULL;
2191 Node *mem = in(1);
2192 if( phase->type(mem)==Type::TOP ) return NULL;
2193 Node *adr = in(3);
2194 const Type* at = phase->type(adr);
2195 if( at==Type::TOP ) return NULL;
2196 const TypePtr* atp = at->isa_ptr();
2197 // adjust atp to be the correct array element address type
2198 if (atp == NULL) atp = TypePtr::BOTTOM;
2199 else atp = atp->add_offset(Type::OffsetBot);
2200 // Get base for derived pointer purposes
2201 if( adr->Opcode() != Op_AddP ) Unimplemented();
2202 Node *base = adr->in(1);
2203
2204 Node *zero = phase->makecon(TypeLong::ZERO);
2205 Node *off = phase->MakeConX(BytesPerLong);
2206 mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
2207 count--;
2208 while( count-- ) {
2209 mem = phase->transform(mem);
2210 adr = phase->transform(new (phase->C, 4) AddPNode(base,adr,off));
2211 mem = new (phase->C, 4) StoreLNode(in(0),mem,adr,atp,zero);
2212 }
2213 return mem;
2214 }
2215
2216 //----------------------------clear_memory-------------------------------------
2217 // Generate code to initialize object storage to zero.
2218 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2219 intptr_t start_offset,
2220 Node* end_offset,
2221 PhaseGVN* phase) {
2222 Compile* C = phase->C;
2223 intptr_t offset = start_offset;
2224
2225 int unit = BytesPerLong;
2226 if ((offset % unit) != 0) {
2227 Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(offset));
2228 adr = phase->transform(adr);
2229 const TypePtr* atp = TypeRawPtr::BOTTOM;
2230 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
2231 mem = phase->transform(mem);
2232 offset += BytesPerInt;
2233 }
2234 assert((offset % unit) == 0, "");
2235
2236 // Initialize the remaining stuff, if any, with a ClearArray.
2237 return clear_memory(ctl, mem, dest, phase->MakeConX(offset), end_offset, phase);
2238 }
2239
2240 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2241 Node* start_offset,
2242 Node* end_offset,
2243 PhaseGVN* phase) {
2244 if (start_offset == end_offset) {
2245 // nothing to do
2246 return mem;
2247 }
2248
2249 Compile* C = phase->C;
2250 int unit = BytesPerLong;
2251 Node* zbase = start_offset;
2252 Node* zend = end_offset;
2253
2254 // Scale to the unit required by the CPU:
2255 if (!Matcher::init_array_count_is_in_bytes) {
2256 Node* shift = phase->intcon(exact_log2(unit));
2257 zbase = phase->transform( new(C,3) URShiftXNode(zbase, shift) );
2258 zend = phase->transform( new(C,3) URShiftXNode(zend, shift) );
2259 }
2260
2261 Node* zsize = phase->transform( new(C,3) SubXNode(zend, zbase) );
2262 Node* zinit = phase->zerocon((unit == BytesPerLong) ? T_LONG : T_INT);
2263
2264 // Bulk clear double-words
2265 Node* adr = phase->transform( new(C,4) AddPNode(dest, dest, start_offset) );
2266 mem = new (C, 4) ClearArrayNode(ctl, mem, zsize, adr);
2267 return phase->transform(mem);
2268 }
2269
2270 Node* ClearArrayNode::clear_memory(Node* ctl, Node* mem, Node* dest,
2271 intptr_t start_offset,
2272 intptr_t end_offset,
2273 PhaseGVN* phase) {
2274 if (start_offset == end_offset) {
2275 // nothing to do
2276 return mem;
2277 }
2278
2279 Compile* C = phase->C;
2280 assert((end_offset % BytesPerInt) == 0, "odd end offset");
2281 intptr_t done_offset = end_offset;
2282 if ((done_offset % BytesPerLong) != 0) {
2283 done_offset -= BytesPerInt;
2284 }
2285 if (done_offset > start_offset) {
2286 mem = clear_memory(ctl, mem, dest,
2287 start_offset, phase->MakeConX(done_offset), phase);
2288 }
2289 if (done_offset < end_offset) { // emit the final 32-bit store
2290 Node* adr = new (C, 4) AddPNode(dest, dest, phase->MakeConX(done_offset));
2291 adr = phase->transform(adr);
2292 const TypePtr* atp = TypeRawPtr::BOTTOM;
2293 mem = StoreNode::make(*phase, ctl, mem, adr, atp, phase->zerocon(T_INT), T_INT);
2294 mem = phase->transform(mem);
2295 done_offset += BytesPerInt;
2296 }
2297 assert(done_offset == end_offset, "");
2298 return mem;
2299 }
2300
2301 //=============================================================================
2302 // Do we match on this edge? No memory edges
2303 uint StrCompNode::match_edge(uint idx) const {
2304 return idx == 5 || idx == 6;
2305 }
2306
2307 //------------------------------Ideal------------------------------------------
2308 // Return a node which is more "ideal" than the current node. Strip out
2309 // control copies
2310 Node *StrCompNode::Ideal(PhaseGVN *phase, bool can_reshape){
2311 return remove_dead_region(phase, can_reshape) ? this : NULL;
2312 }
2313
2314
2315 //=============================================================================
2316 MemBarNode::MemBarNode(Compile* C, int alias_idx, Node* precedent)
2317 : MultiNode(TypeFunc::Parms + (precedent == NULL? 0: 1)),
2318 _adr_type(C->get_adr_type(alias_idx))
2319 {
2320 init_class_id(Class_MemBar);
2321 Node* top = C->top();
2322 init_req(TypeFunc::I_O,top);
2323 init_req(TypeFunc::FramePtr,top);
2324 init_req(TypeFunc::ReturnAdr,top);
2325 if (precedent != NULL)
2326 init_req(TypeFunc::Parms, precedent);
2327 }
2328
2329 //------------------------------cmp--------------------------------------------
2330 uint MemBarNode::hash() const { return NO_HASH; }
2331 uint MemBarNode::cmp( const Node &n ) const {
2332 return (&n == this); // Always fail except on self
2333 }
2334
2335 //------------------------------make-------------------------------------------
2336 MemBarNode* MemBarNode::make(Compile* C, int opcode, int atp, Node* pn) {
2337 int len = Precedent + (pn == NULL? 0: 1);
2338 switch (opcode) {
2339 case Op_MemBarAcquire: return new(C, len) MemBarAcquireNode(C, atp, pn);
2340 case Op_MemBarRelease: return new(C, len) MemBarReleaseNode(C, atp, pn);
2341 case Op_MemBarVolatile: return new(C, len) MemBarVolatileNode(C, atp, pn);
2342 case Op_MemBarCPUOrder: return new(C, len) MemBarCPUOrderNode(C, atp, pn);
2343 case Op_Initialize: return new(C, len) InitializeNode(C, atp, pn);
2344 default: ShouldNotReachHere(); return NULL;
2345 }
2346 }
2347
2348 //------------------------------Ideal------------------------------------------
2349 // Return a node which is more "ideal" than the current node. Strip out
2350 // control copies
2351 Node *MemBarNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2352 if (remove_dead_region(phase, can_reshape)) return this;
2353 return NULL;
2354 }
2355
2356 //------------------------------Value------------------------------------------
2357 const Type *MemBarNode::Value( PhaseTransform *phase ) const {
2358 if( !in(0) ) return Type::TOP;
2359 if( phase->type(in(0)) == Type::TOP )
2360 return Type::TOP;
2361 return TypeTuple::MEMBAR;
2362 }
2363
2364 //------------------------------match------------------------------------------
2365 // Construct projections for memory.
2366 Node *MemBarNode::match( const ProjNode *proj, const Matcher *m ) {
2367 switch (proj->_con) {
2368 case TypeFunc::Control:
2369 case TypeFunc::Memory:
2370 return new (m->C, 1) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
2371 }
2372 ShouldNotReachHere();
2373 return NULL;
2374 }
2375
2376 //===========================InitializeNode====================================
2377 // SUMMARY:
2378 // This node acts as a memory barrier on raw memory, after some raw stores.
2379 // The 'cooked' oop value feeds from the Initialize, not the Allocation.
2380 // The Initialize can 'capture' suitably constrained stores as raw inits.
2381 // It can coalesce related raw stores into larger units (called 'tiles').
2382 // It can avoid zeroing new storage for memory units which have raw inits.
2383 // At macro-expansion, it is marked 'complete', and does not optimize further.
2384 //
2385 // EXAMPLE:
2386 // The object 'new short[2]' occupies 16 bytes in a 32-bit machine.
2387 // ctl = incoming control; mem* = incoming memory
2388 // (Note: A star * on a memory edge denotes I/O and other standard edges.)
2389 // First allocate uninitialized memory and fill in the header:
2390 // alloc = (Allocate ctl mem* 16 #short[].klass ...)
2391 // ctl := alloc.Control; mem* := alloc.Memory*
2392 // rawmem = alloc.Memory; rawoop = alloc.RawAddress
2393 // Then initialize to zero the non-header parts of the raw memory block:
2394 // init = (Initialize alloc.Control alloc.Memory* alloc.RawAddress)
2395 // ctl := init.Control; mem.SLICE(#short[*]) := init.Memory
2396 // After the initialize node executes, the object is ready for service:
2397 // oop := (CheckCastPP init.Control alloc.RawAddress #short[])
2398 // Suppose its body is immediately initialized as {1,2}:
2399 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
2400 // store2 = (StoreC init.Control store1 (+ oop 14) 2)
2401 // mem.SLICE(#short[*]) := store2
2402 //
2403 // DETAILS:
2404 // An InitializeNode collects and isolates object initialization after
2405 // an AllocateNode and before the next possible safepoint. As a
2406 // memory barrier (MemBarNode), it keeps critical stores from drifting
2407 // down past any safepoint or any publication of the allocation.
2408 // Before this barrier, a newly-allocated object may have uninitialized bits.
2409 // After this barrier, it may be treated as a real oop, and GC is allowed.
2410 //
2411 // The semantics of the InitializeNode include an implicit zeroing of
2412 // the new object from object header to the end of the object.
2413 // (The object header and end are determined by the AllocateNode.)
2414 //
2415 // Certain stores may be added as direct inputs to the InitializeNode.
2416 // These stores must update raw memory, and they must be to addresses
2417 // derived from the raw address produced by AllocateNode, and with
2418 // a constant offset. They must be ordered by increasing offset.
2419 // The first one is at in(RawStores), the last at in(req()-1).
2420 // Unlike most memory operations, they are not linked in a chain,
2421 // but are displayed in parallel as users of the rawmem output of
2422 // the allocation.
2423 //
2424 // (See comments in InitializeNode::capture_store, which continue
2425 // the example given above.)
2426 //
2427 // When the associated Allocate is macro-expanded, the InitializeNode
2428 // may be rewritten to optimize collected stores. A ClearArrayNode
2429 // may also be created at that point to represent any required zeroing.
2430 // The InitializeNode is then marked 'complete', prohibiting further
2431 // capturing of nearby memory operations.
2432 //
2433 // During macro-expansion, all captured initializations which store
2434 // constant values of 32 bits or smaller are coalesced (if advantagous)
2435 // into larger 'tiles' 32 or 64 bits. This allows an object to be
2436 // initialized in fewer memory operations. Memory words which are
2437 // covered by neither tiles nor non-constant stores are pre-zeroed
2438 // by explicit stores of zero. (The code shape happens to do all
2439 // zeroing first, then all other stores, with both sequences occurring
2440 // in order of ascending offsets.)
2441 //
2442 // Alternatively, code may be inserted between an AllocateNode and its
2443 // InitializeNode, to perform arbitrary initialization of the new object.
2444 // E.g., the object copying intrinsics insert complex data transfers here.
2445 // The initialization must then be marked as 'complete' disable the
2446 // built-in zeroing semantics and the collection of initializing stores.
2447 //
2448 // While an InitializeNode is incomplete, reads from the memory state
2449 // produced by it are optimizable if they match the control edge and
2450 // new oop address associated with the allocation/initialization.
2451 // They return a stored value (if the offset matches) or else zero.
2452 // A write to the memory state, if it matches control and address,
2453 // and if it is to a constant offset, may be 'captured' by the
2454 // InitializeNode. It is cloned as a raw memory operation and rewired
2455 // inside the initialization, to the raw oop produced by the allocation.
2456 // Operations on addresses which are provably distinct (e.g., to
2457 // other AllocateNodes) are allowed to bypass the initialization.
2458 //
2459 // The effect of all this is to consolidate object initialization
2460 // (both arrays and non-arrays, both piecewise and bulk) into a
2461 // single location, where it can be optimized as a unit.
2462 //
2463 // Only stores with an offset less than TrackedInitializationLimit words
2464 // will be considered for capture by an InitializeNode. This puts a
2465 // reasonable limit on the complexity of optimized initializations.
2466
2467 //---------------------------InitializeNode------------------------------------
2468 InitializeNode::InitializeNode(Compile* C, int adr_type, Node* rawoop)
2469 : _is_complete(false),
2470 MemBarNode(C, adr_type, rawoop)
2471 {
2472 init_class_id(Class_Initialize);
2473
2474 assert(adr_type == Compile::AliasIdxRaw, "only valid atp");
2475 assert(in(RawAddress) == rawoop, "proper init");
2476 // Note: allocation() can be NULL, for secondary initialization barriers
2477 }
2478
2479 // Since this node is not matched, it will be processed by the
2480 // register allocator. Declare that there are no constraints
2481 // on the allocation of the RawAddress edge.
2482 const RegMask &InitializeNode::in_RegMask(uint idx) const {
2483 // This edge should be set to top, by the set_complete. But be conservative.
2484 if (idx == InitializeNode::RawAddress)
2485 return *(Compile::current()->matcher()->idealreg2spillmask[in(idx)->ideal_reg()]);
2486 return RegMask::Empty;
2487 }
2488
2489 Node* InitializeNode::memory(uint alias_idx) {
2490 Node* mem = in(Memory);
2491 if (mem->is_MergeMem()) {
2492 return mem->as_MergeMem()->memory_at(alias_idx);
2493 } else {
2494 // incoming raw memory is not split
2495 return mem;
2496 }
2497 }
2498
2499 bool InitializeNode::is_non_zero() {
2500 if (is_complete()) return false;
2501 remove_extra_zeroes();
2502 return (req() > RawStores);
2503 }
2504
2505 void InitializeNode::set_complete(PhaseGVN* phase) {
2506 assert(!is_complete(), "caller responsibility");
2507 _is_complete = true;
2508
2509 // After this node is complete, it contains a bunch of
2510 // raw-memory initializations. There is no need for
2511 // it to have anything to do with non-raw memory effects.
2512 // Therefore, tell all non-raw users to re-optimize themselves,
2513 // after skipping the memory effects of this initialization.
2514 PhaseIterGVN* igvn = phase->is_IterGVN();
2515 if (igvn) igvn->add_users_to_worklist(this);
2516 }
2517
2518 // convenience function
2519 // return false if the init contains any stores already
2520 bool AllocateNode::maybe_set_complete(PhaseGVN* phase) {
2521 InitializeNode* init = initialization();
2522 if (init == NULL || init->is_complete()) return false;
2523 init->remove_extra_zeroes();
2524 // for now, if this allocation has already collected any inits, bail:
2525 if (init->is_non_zero()) return false;
2526 init->set_complete(phase);
2527 return true;
2528 }
2529
2530 void InitializeNode::remove_extra_zeroes() {
2531 if (req() == RawStores) return;
2532 Node* zmem = zero_memory();
2533 uint fill = RawStores;
2534 for (uint i = fill; i < req(); i++) {
2535 Node* n = in(i);
2536 if (n->is_top() || n == zmem) continue; // skip
2537 if (fill < i) set_req(fill, n); // compact
2538 ++fill;
2539 }
2540 // delete any empty spaces created:
2541 while (fill < req()) {
2542 del_req(fill);
2543 }
2544 }
2545
2546 // Helper for remembering which stores go with which offsets.
2547 intptr_t InitializeNode::get_store_offset(Node* st, PhaseTransform* phase) {
2548 if (!st->is_Store()) return -1; // can happen to dead code via subsume_node
2549 intptr_t offset = -1;
2550 Node* base = AddPNode::Ideal_base_and_offset(st->in(MemNode::Address),
2551 phase, offset);
2552 if (base == NULL) return -1; // something is dead,
2553 if (offset < 0) return -1; // dead, dead
2554 return offset;
2555 }
2556
2557 // Helper for proving that an initialization expression is
2558 // "simple enough" to be folded into an object initialization.
2559 // Attempts to prove that a store's initial value 'n' can be captured
2560 // within the initialization without creating a vicious cycle, such as:
2561 // { Foo p = new Foo(); p.next = p; }
2562 // True for constants and parameters and small combinations thereof.
2563 bool InitializeNode::detect_init_independence(Node* n,
2564 bool st_is_pinned,
2565 int& count) {
2566 if (n == NULL) return true; // (can this really happen?)
2567 if (n->is_Proj()) n = n->in(0);
2568 if (n == this) return false; // found a cycle
2569 if (n->is_Con()) return true;
2570 if (n->is_Start()) return true; // params, etc., are OK
2571 if (n->is_Root()) return true; // even better
2572
2573 Node* ctl = n->in(0);
2574 if (ctl != NULL && !ctl->is_top()) {
2575 if (ctl->is_Proj()) ctl = ctl->in(0);
2576 if (ctl == this) return false;
2577
2578 // If we already know that the enclosing memory op is pinned right after
2579 // the init, then any control flow that the store has picked up
2580 // must have preceded the init, or else be equal to the init.
2581 // Even after loop optimizations (which might change control edges)
2582 // a store is never pinned *before* the availability of its inputs.
2583 if (!MemNode::all_controls_dominate(n, this))
2584 return false; // failed to prove a good control
2585
2586 }
2587
2588 // Check data edges for possible dependencies on 'this'.
2589 if ((count += 1) > 20) return false; // complexity limit
2590 for (uint i = 1; i < n->req(); i++) {
2591 Node* m = n->in(i);
2592 if (m == NULL || m == n || m->is_top()) continue;
2593 uint first_i = n->find_edge(m);
2594 if (i != first_i) continue; // process duplicate edge just once
2595 if (!detect_init_independence(m, st_is_pinned, count)) {
2596 return false;
2597 }
2598 }
2599
2600 return true;
2601 }
2602
2603 // Here are all the checks a Store must pass before it can be moved into
2604 // an initialization. Returns zero if a check fails.
2605 // On success, returns the (constant) offset to which the store applies,
2606 // within the initialized memory.
2607 intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase) {
2608 const int FAIL = 0;
2609 if (st->req() != MemNode::ValueIn + 1)
2610 return FAIL; // an inscrutable StoreNode (card mark?)
2611 Node* ctl = st->in(MemNode::Control);
2612 if (!(ctl != NULL && ctl->is_Proj() && ctl->in(0) == this))
2613 return FAIL; // must be unconditional after the initialization
2614 Node* mem = st->in(MemNode::Memory);
2615 if (!(mem->is_Proj() && mem->in(0) == this))
2616 return FAIL; // must not be preceded by other stores
2617 Node* adr = st->in(MemNode::Address);
2618 intptr_t offset;
2619 AllocateNode* alloc = AllocateNode::Ideal_allocation(adr, phase, offset);
2620 if (alloc == NULL)
2621 return FAIL; // inscrutable address
2622 if (alloc != allocation())
2623 return FAIL; // wrong allocation! (store needs to float up)
2624 Node* val = st->in(MemNode::ValueIn);
2625 int complexity_count = 0;
2626 if (!detect_init_independence(val, true, complexity_count))
2627 return FAIL; // stored value must be 'simple enough'
2628
2629 return offset; // success
2630 }
2631
2632 // Find the captured store in(i) which corresponds to the range
2633 // [start..start+size) in the initialized object.
2634 // If there is one, return its index i. If there isn't, return the
2635 // negative of the index where it should be inserted.
2636 // Return 0 if the queried range overlaps an initialization boundary
2637 // or if dead code is encountered.
2638 // If size_in_bytes is zero, do not bother with overlap checks.
2639 int InitializeNode::captured_store_insertion_point(intptr_t start,
2640 int size_in_bytes,
2641 PhaseTransform* phase) {
2642 const int FAIL = 0, MAX_STORE = BytesPerLong;
2643
2644 if (is_complete())
2645 return FAIL; // arraycopy got here first; punt
2646
2647 assert(allocation() != NULL, "must be present");
2648
2649 // no negatives, no header fields:
2650 if (start < (intptr_t) allocation()->minimum_header_size()) return FAIL;
2651
2652 // after a certain size, we bail out on tracking all the stores:
2653 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
2654 if (start >= ti_limit) return FAIL;
2655
2656 for (uint i = InitializeNode::RawStores, limit = req(); ; ) {
2657 if (i >= limit) return -(int)i; // not found; here is where to put it
2658
2659 Node* st = in(i);
2660 intptr_t st_off = get_store_offset(st, phase);
2661 if (st_off < 0) {
2662 if (st != zero_memory()) {
2663 return FAIL; // bail out if there is dead garbage
2664 }
2665 } else if (st_off > start) {
2666 // ...we are done, since stores are ordered
2667 if (st_off < start + size_in_bytes) {
2668 return FAIL; // the next store overlaps
2669 }
2670 return -(int)i; // not found; here is where to put it
2671 } else if (st_off < start) {
2672 if (size_in_bytes != 0 &&
2673 start < st_off + MAX_STORE &&
2674 start < st_off + st->as_Store()->memory_size()) {
2675 return FAIL; // the previous store overlaps
2676 }
2677 } else {
2678 if (size_in_bytes != 0 &&
2679 st->as_Store()->memory_size() != size_in_bytes) {
2680 return FAIL; // mismatched store size
2681 }
2682 return i;
2683 }
2684
2685 ++i;
2686 }
2687 }
2688
2689 // Look for a captured store which initializes at the offset 'start'
2690 // with the given size. If there is no such store, and no other
2691 // initialization interferes, then return zero_memory (the memory
2692 // projection of the AllocateNode).
2693 Node* InitializeNode::find_captured_store(intptr_t start, int size_in_bytes,
2694 PhaseTransform* phase) {
2695 assert(stores_are_sane(phase), "");
2696 int i = captured_store_insertion_point(start, size_in_bytes, phase);
2697 if (i == 0) {
2698 return NULL; // something is dead
2699 } else if (i < 0) {
2700 return zero_memory(); // just primordial zero bits here
2701 } else {
2702 Node* st = in(i); // here is the store at this position
2703 assert(get_store_offset(st->as_Store(), phase) == start, "sanity");
2704 return st;
2705 }
2706 }
2707
2708 // Create, as a raw pointer, an address within my new object at 'offset'.
2709 Node* InitializeNode::make_raw_address(intptr_t offset,
2710 PhaseTransform* phase) {
2711 Node* addr = in(RawAddress);
2712 if (offset != 0) {
2713 Compile* C = phase->C;
2714 addr = phase->transform( new (C, 4) AddPNode(C->top(), addr,
2715 phase->MakeConX(offset)) );
2716 }
2717 return addr;
2718 }
2719
2720 // Clone the given store, converting it into a raw store
2721 // initializing a field or element of my new object.
2722 // Caller is responsible for retiring the original store,
2723 // with subsume_node or the like.
2724 //
2725 // From the example above InitializeNode::InitializeNode,
2726 // here are the old stores to be captured:
2727 // store1 = (StoreC init.Control init.Memory (+ oop 12) 1)
2728 // store2 = (StoreC init.Control store1 (+ oop 14) 2)
2729 //
2730 // Here is the changed code; note the extra edges on init:
2731 // alloc = (Allocate ...)
2732 // rawoop = alloc.RawAddress
2733 // rawstore1 = (StoreC alloc.Control alloc.Memory (+ rawoop 12) 1)
2734 // rawstore2 = (StoreC alloc.Control alloc.Memory (+ rawoop 14) 2)
2735 // init = (Initialize alloc.Control alloc.Memory rawoop
2736 // rawstore1 rawstore2)
2737 //
2738 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
2739 PhaseTransform* phase) {
2740 assert(stores_are_sane(phase), "");
2741
2742 if (start < 0) return NULL;
2743 assert(can_capture_store(st, phase) == start, "sanity");
2744
2745 Compile* C = phase->C;
2746 int size_in_bytes = st->memory_size();
2747 int i = captured_store_insertion_point(start, size_in_bytes, phase);
2748 if (i == 0) return NULL; // bail out
2749 Node* prev_mem = NULL; // raw memory for the captured store
2750 if (i > 0) {
2751 prev_mem = in(i); // there is a pre-existing store under this one
2752 set_req(i, C->top()); // temporarily disconnect it
2753 // See StoreNode::Ideal 'st->outcnt() == 1' for the reason to disconnect.
2754 } else {
2755 i = -i; // no pre-existing store
2756 prev_mem = zero_memory(); // a slice of the newly allocated object
2757 if (i > InitializeNode::RawStores && in(i-1) == prev_mem)
2758 set_req(--i, C->top()); // reuse this edge; it has been folded away
2759 else
2760 ins_req(i, C->top()); // build a new edge
2761 }
2762 Node* new_st = st->clone();
2763 new_st->set_req(MemNode::Control, in(Control));
2764 new_st->set_req(MemNode::Memory, prev_mem);
2765 new_st->set_req(MemNode::Address, make_raw_address(start, phase));
2766 new_st = phase->transform(new_st);
2767
2768 // At this point, new_st might have swallowed a pre-existing store
2769 // at the same offset, or perhaps new_st might have disappeared,
2770 // if it redundantly stored the same value (or zero to fresh memory).
2771
2772 // In any case, wire it in:
2773 set_req(i, new_st);
2774
2775 // The caller may now kill the old guy.
2776 DEBUG_ONLY(Node* check_st = find_captured_store(start, size_in_bytes, phase));
2777 assert(check_st == new_st || check_st == NULL, "must be findable");
2778 assert(!is_complete(), "");
2779 return new_st;
2780 }
2781
2782 static bool store_constant(jlong* tiles, int num_tiles,
2783 intptr_t st_off, int st_size,
2784 jlong con) {
2785 if ((st_off & (st_size-1)) != 0)
2786 return false; // strange store offset (assume size==2**N)
2787 address addr = (address)tiles + st_off;
2788 assert(st_off >= 0 && addr+st_size <= (address)&tiles[num_tiles], "oob");
2789 switch (st_size) {
2790 case sizeof(jbyte): *(jbyte*) addr = (jbyte) con; break;
2791 case sizeof(jchar): *(jchar*) addr = (jchar) con; break;
2792 case sizeof(jint): *(jint*) addr = (jint) con; break;
2793 case sizeof(jlong): *(jlong*) addr = (jlong) con; break;
2794 default: return false; // strange store size (detect size!=2**N here)
2795 }
2796 return true; // return success to caller
2797 }
2798
2799 // Coalesce subword constants into int constants and possibly
2800 // into long constants. The goal, if the CPU permits,
2801 // is to initialize the object with a small number of 64-bit tiles.
2802 // Also, convert floating-point constants to bit patterns.
2803 // Non-constants are not relevant to this pass.
2804 //
2805 // In terms of the running example on InitializeNode::InitializeNode
2806 // and InitializeNode::capture_store, here is the transformation
2807 // of rawstore1 and rawstore2 into rawstore12:
2808 // alloc = (Allocate ...)
2809 // rawoop = alloc.RawAddress
2810 // tile12 = 0x00010002
2811 // rawstore12 = (StoreI alloc.Control alloc.Memory (+ rawoop 12) tile12)
2812 // init = (Initialize alloc.Control alloc.Memory rawoop rawstore12)
2813 //
2814 void
2815 InitializeNode::coalesce_subword_stores(intptr_t header_size,
2816 Node* size_in_bytes,
2817 PhaseGVN* phase) {
2818 Compile* C = phase->C;
2819
2820 assert(stores_are_sane(phase), "");
2821 // Note: After this pass, they are not completely sane,
2822 // since there may be some overlaps.
2823
2824 int old_subword = 0, old_long = 0, new_int = 0, new_long = 0;
2825
2826 intptr_t ti_limit = (TrackedInitializationLimit * HeapWordSize);
2827 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, ti_limit);
2828 size_limit = MIN2(size_limit, ti_limit);
2829 size_limit = align_size_up(size_limit, BytesPerLong);
2830 int num_tiles = size_limit / BytesPerLong;
2831
2832 // allocate space for the tile map:
2833 const int small_len = DEBUG_ONLY(true ? 3 :) 30; // keep stack frames small
2834 jlong tiles_buf[small_len];
2835 Node* nodes_buf[small_len];
2836 jlong inits_buf[small_len];
2837 jlong* tiles = ((num_tiles <= small_len) ? &tiles_buf[0]
2838 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
2839 Node** nodes = ((num_tiles <= small_len) ? &nodes_buf[0]
2840 : NEW_RESOURCE_ARRAY(Node*, num_tiles));
2841 jlong* inits = ((num_tiles <= small_len) ? &inits_buf[0]
2842 : NEW_RESOURCE_ARRAY(jlong, num_tiles));
2843 // tiles: exact bitwise model of all primitive constants
2844 // nodes: last constant-storing node subsumed into the tiles model
2845 // inits: which bytes (in each tile) are touched by any initializations
2846
2847 //// Pass A: Fill in the tile model with any relevant stores.
2848
2849 Copy::zero_to_bytes(tiles, sizeof(tiles[0]) * num_tiles);
2850 Copy::zero_to_bytes(nodes, sizeof(nodes[0]) * num_tiles);
2851 Copy::zero_to_bytes(inits, sizeof(inits[0]) * num_tiles);
2852 Node* zmem = zero_memory(); // initially zero memory state
2853 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
2854 Node* st = in(i);
2855 intptr_t st_off = get_store_offset(st, phase);
2856
2857 // Figure out the store's offset and constant value:
2858 if (st_off < header_size) continue; //skip (ignore header)
2859 if (st->in(MemNode::Memory) != zmem) continue; //skip (odd store chain)
2860 int st_size = st->as_Store()->memory_size();
2861 if (st_off + st_size > size_limit) break;
2862
2863 // Record which bytes are touched, whether by constant or not.
2864 if (!store_constant(inits, num_tiles, st_off, st_size, (jlong) -1))
2865 continue; // skip (strange store size)
2866
2867 const Type* val = phase->type(st->in(MemNode::ValueIn));
2868 if (!val->singleton()) continue; //skip (non-con store)
2869 BasicType type = val->basic_type();
2870
2871 jlong con = 0;
2872 switch (type) {
2873 case T_INT: con = val->is_int()->get_con(); break;
2874 case T_LONG: con = val->is_long()->get_con(); break;
2875 case T_FLOAT: con = jint_cast(val->getf()); break;
2876 case T_DOUBLE: con = jlong_cast(val->getd()); break;
2877 default: continue; //skip (odd store type)
2878 }
2879
2880 if (type == T_LONG && Matcher::isSimpleConstant64(con) &&
2881 st->Opcode() == Op_StoreL) {
2882 continue; // This StoreL is already optimal.
2883 }
2884
2885 // Store down the constant.
2886 store_constant(tiles, num_tiles, st_off, st_size, con);
2887
2888 intptr_t j = st_off >> LogBytesPerLong;
2889
2890 if (type == T_INT && st_size == BytesPerInt
2891 && (st_off & BytesPerInt) == BytesPerInt) {
2892 jlong lcon = tiles[j];
2893 if (!Matcher::isSimpleConstant64(lcon) &&
2894 st->Opcode() == Op_StoreI) {
2895 // This StoreI is already optimal by itself.
2896 jint* intcon = (jint*) &tiles[j];
2897 intcon[1] = 0; // undo the store_constant()
2898
2899 // If the previous store is also optimal by itself, back up and
2900 // undo the action of the previous loop iteration... if we can.
2901 // But if we can't, just let the previous half take care of itself.
2902 st = nodes[j];
2903 st_off -= BytesPerInt;
2904 con = intcon[0];
2905 if (con != 0 && st != NULL && st->Opcode() == Op_StoreI) {
2906 assert(st_off >= header_size, "still ignoring header");
2907 assert(get_store_offset(st, phase) == st_off, "must be");
2908 assert(in(i-1) == zmem, "must be");
2909 DEBUG_ONLY(const Type* tcon = phase->type(st->in(MemNode::ValueIn)));
2910 assert(con == tcon->is_int()->get_con(), "must be");
2911 // Undo the effects of the previous loop trip, which swallowed st:
2912 intcon[0] = 0; // undo store_constant()
2913 set_req(i-1, st); // undo set_req(i, zmem)
2914 nodes[j] = NULL; // undo nodes[j] = st
2915 --old_subword; // undo ++old_subword
2916 }
2917 continue; // This StoreI is already optimal.
2918 }
2919 }
2920
2921 // This store is not needed.
2922 set_req(i, zmem);
2923 nodes[j] = st; // record for the moment
2924 if (st_size < BytesPerLong) // something has changed
2925 ++old_subword; // includes int/float, but who's counting...
2926 else ++old_long;
2927 }
2928
2929 if ((old_subword + old_long) == 0)
2930 return; // nothing more to do
2931
2932 //// Pass B: Convert any non-zero tiles into optimal constant stores.
2933 // Be sure to insert them before overlapping non-constant stores.
2934 // (E.g., byte[] x = { 1,2,y,4 } => x[int 0] = 0x01020004, x[2]=y.)
2935 for (int j = 0; j < num_tiles; j++) {
2936 jlong con = tiles[j];
2937 jlong init = inits[j];
2938 if (con == 0) continue;
2939 jint con0, con1; // split the constant, address-wise
2940 jint init0, init1; // split the init map, address-wise
2941 { union { jlong con; jint intcon[2]; } u;
2942 u.con = con;
2943 con0 = u.intcon[0];
2944 con1 = u.intcon[1];
2945 u.con = init;
2946 init0 = u.intcon[0];
2947 init1 = u.intcon[1];
2948 }
2949
2950 Node* old = nodes[j];
2951 assert(old != NULL, "need the prior store");
2952 intptr_t offset = (j * BytesPerLong);
2953
2954 bool split = !Matcher::isSimpleConstant64(con);
2955
2956 if (offset < header_size) {
2957 assert(offset + BytesPerInt >= header_size, "second int counts");
2958 assert(*(jint*)&tiles[j] == 0, "junk in header");
2959 split = true; // only the second word counts
2960 // Example: int a[] = { 42 ... }
2961 } else if (con0 == 0 && init0 == -1) {
2962 split = true; // first word is covered by full inits
2963 // Example: int a[] = { ... foo(), 42 ... }
2964 } else if (con1 == 0 && init1 == -1) {
2965 split = true; // second word is covered by full inits
2966 // Example: int a[] = { ... 42, foo() ... }
2967 }
2968
2969 // Here's a case where init0 is neither 0 nor -1:
2970 // byte a[] = { ... 0,0,foo(),0, 0,0,0,42 ... }
2971 // Assuming big-endian memory, init0, init1 are 0x0000FF00, 0x000000FF.
2972 // In this case the tile is not split; it is (jlong)42.
2973 // The big tile is stored down, and then the foo() value is inserted.
2974 // (If there were foo(),foo() instead of foo(),0, init0 would be -1.)
2975
2976 Node* ctl = old->in(MemNode::Control);
2977 Node* adr = make_raw_address(offset, phase);
2978 const TypePtr* atp = TypeRawPtr::BOTTOM;
2979
2980 // One or two coalesced stores to plop down.
2981 Node* st[2];
2982 intptr_t off[2];
2983 int nst = 0;
2984 if (!split) {
2985 ++new_long;
2986 off[nst] = offset;
2987 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
2988 phase->longcon(con), T_LONG);
2989 } else {
2990 // Omit either if it is a zero.
2991 if (con0 != 0) {
2992 ++new_int;
2993 off[nst] = offset;
2994 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
2995 phase->intcon(con0), T_INT);
2996 }
2997 if (con1 != 0) {
2998 ++new_int;
2999 offset += BytesPerInt;
3000 adr = make_raw_address(offset, phase);
3001 off[nst] = offset;
3002 st[nst++] = StoreNode::make(*phase, ctl, zmem, adr, atp,
3003 phase->intcon(con1), T_INT);
3004 }
3005 }
3006
3007 // Insert second store first, then the first before the second.
3008 // Insert each one just before any overlapping non-constant stores.
3009 while (nst > 0) {
3010 Node* st1 = st[--nst];
3011 C->copy_node_notes_to(st1, old);
3012 st1 = phase->transform(st1);
3013 offset = off[nst];
3014 assert(offset >= header_size, "do not smash header");
3015 int ins_idx = captured_store_insertion_point(offset, /*size:*/0, phase);
3016 guarantee(ins_idx != 0, "must re-insert constant store");
3017 if (ins_idx < 0) ins_idx = -ins_idx; // never overlap
3018 if (ins_idx > InitializeNode::RawStores && in(ins_idx-1) == zmem)
3019 set_req(--ins_idx, st1);
3020 else
3021 ins_req(ins_idx, st1);
3022 }
3023 }
3024
3025 if (PrintCompilation && WizardMode)
3026 tty->print_cr("Changed %d/%d subword/long constants into %d/%d int/long",
3027 old_subword, old_long, new_int, new_long);
3028 if (C->log() != NULL)
3029 C->log()->elem("comment that='%d/%d subword/long to %d/%d int/long'",
3030 old_subword, old_long, new_int, new_long);
3031
3032 // Clean up any remaining occurrences of zmem:
3033 remove_extra_zeroes();
3034 }
3035
3036 // Explore forward from in(start) to find the first fully initialized
3037 // word, and return its offset. Skip groups of subword stores which
3038 // together initialize full words. If in(start) is itself part of a
3039 // fully initialized word, return the offset of in(start). If there
3040 // are no following full-word stores, or if something is fishy, return
3041 // a negative value.
3042 intptr_t InitializeNode::find_next_fullword_store(uint start, PhaseGVN* phase) {
3043 int int_map = 0;
3044 intptr_t int_map_off = 0;
3045 const int FULL_MAP = right_n_bits(BytesPerInt); // the int_map we hope for
3046
3047 for (uint i = start, limit = req(); i < limit; i++) {
3048 Node* st = in(i);
3049
3050 intptr_t st_off = get_store_offset(st, phase);
3051 if (st_off < 0) break; // return conservative answer
3052
3053 int st_size = st->as_Store()->memory_size();
3054 if (st_size >= BytesPerInt && (st_off % BytesPerInt) == 0) {
3055 return st_off; // we found a complete word init
3056 }
3057
3058 // update the map:
3059
3060 intptr_t this_int_off = align_size_down(st_off, BytesPerInt);
3061 if (this_int_off != int_map_off) {
3062 // reset the map:
3063 int_map = 0;
3064 int_map_off = this_int_off;
3065 }
3066
3067 int subword_off = st_off - this_int_off;
3068 int_map |= right_n_bits(st_size) << subword_off;
3069 if ((int_map & FULL_MAP) == FULL_MAP) {
3070 return this_int_off; // we found a complete word init
3071 }
3072
3073 // Did this store hit or cross the word boundary?
3074 intptr_t next_int_off = align_size_down(st_off + st_size, BytesPerInt);
3075 if (next_int_off == this_int_off + BytesPerInt) {
3076 // We passed the current int, without fully initializing it.
3077 int_map_off = next_int_off;
3078 int_map >>= BytesPerInt;
3079 } else if (next_int_off > this_int_off + BytesPerInt) {
3080 // We passed the current and next int.
3081 return this_int_off + BytesPerInt;
3082 }
3083 }
3084
3085 return -1;
3086 }
3087
3088
3089 // Called when the associated AllocateNode is expanded into CFG.
3090 // At this point, we may perform additional optimizations.
3091 // Linearize the stores by ascending offset, to make memory
3092 // activity as coherent as possible.
3093 Node* InitializeNode::complete_stores(Node* rawctl, Node* rawmem, Node* rawptr,
3094 intptr_t header_size,
3095 Node* size_in_bytes,
3096 PhaseGVN* phase) {
3097 assert(!is_complete(), "not already complete");
3098 assert(stores_are_sane(phase), "");
3099 assert(allocation() != NULL, "must be present");
3100
3101 remove_extra_zeroes();
3102
3103 if (ReduceFieldZeroing || ReduceBulkZeroing)
3104 // reduce instruction count for common initialization patterns
3105 coalesce_subword_stores(header_size, size_in_bytes, phase);
3106
3107 Node* zmem = zero_memory(); // initially zero memory state
3108 Node* inits = zmem; // accumulating a linearized chain of inits
3109 #ifdef ASSERT
3110 intptr_t first_offset = allocation()->minimum_header_size();
3111 intptr_t last_init_off = first_offset; // previous init offset
3112 intptr_t last_init_end = first_offset; // previous init offset+size
3113 intptr_t last_tile_end = first_offset; // previous tile offset+size
3114 #endif
3115 intptr_t zeroes_done = header_size;
3116
3117 bool do_zeroing = true; // we might give up if inits are very sparse
3118 int big_init_gaps = 0; // how many large gaps have we seen?
3119
3120 if (ZeroTLAB) do_zeroing = false;
3121 if (!ReduceFieldZeroing && !ReduceBulkZeroing) do_zeroing = false;
3122
3123 for (uint i = InitializeNode::RawStores, limit = req(); i < limit; i++) {
3124 Node* st = in(i);
3125 intptr_t st_off = get_store_offset(st, phase);
3126 if (st_off < 0)
3127 break; // unknown junk in the inits
3128 if (st->in(MemNode::Memory) != zmem)
3129 break; // complicated store chains somehow in list
3130
3131 int st_size = st->as_Store()->memory_size();
3132 intptr_t next_init_off = st_off + st_size;
3133
3134 if (do_zeroing && zeroes_done < next_init_off) {
3135 // See if this store needs a zero before it or under it.
3136 intptr_t zeroes_needed = st_off;
3137
3138 if (st_size < BytesPerInt) {
3139 // Look for subword stores which only partially initialize words.
3140 // If we find some, we must lay down some word-level zeroes first,
3141 // underneath the subword stores.
3142 //
3143 // Examples:
3144 // byte[] a = { p,q,r,s } => a[0]=p,a[1]=q,a[2]=r,a[3]=s
3145 // byte[] a = { x,y,0,0 } => a[0..3] = 0, a[0]=x,a[1]=y
3146 // byte[] a = { 0,0,z,0 } => a[0..3] = 0, a[2]=z
3147 //
3148 // Note: coalesce_subword_stores may have already done this,
3149 // if it was prompted by constant non-zero subword initializers.
3150 // But this case can still arise with non-constant stores.
3151
3152 intptr_t next_full_store = find_next_fullword_store(i, phase);
3153
3154 // In the examples above:
3155 // in(i) p q r s x y z
3156 // st_off 12 13 14 15 12 13 14
3157 // st_size 1 1 1 1 1 1 1
3158 // next_full_s. 12 16 16 16 16 16 16
3159 // z's_done 12 16 16 16 12 16 12
3160 // z's_needed 12 16 16 16 16 16 16
3161 // zsize 0 0 0 0 4 0 4
3162 if (next_full_store < 0) {
3163 // Conservative tack: Zero to end of current word.
3164 zeroes_needed = align_size_up(zeroes_needed, BytesPerInt);
3165 } else {
3166 // Zero to beginning of next fully initialized word.
3167 // Or, don't zero at all, if we are already in that word.
3168 assert(next_full_store >= zeroes_needed, "must go forward");
3169 assert((next_full_store & (BytesPerInt-1)) == 0, "even boundary");
3170 zeroes_needed = next_full_store;
3171 }
3172 }
3173
3174 if (zeroes_needed > zeroes_done) {
3175 intptr_t zsize = zeroes_needed - zeroes_done;
3176 // Do some incremental zeroing on rawmem, in parallel with inits.
3177 zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3178 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3179 zeroes_done, zeroes_needed,
3180 phase);
3181 zeroes_done = zeroes_needed;
3182 if (zsize > Matcher::init_array_short_size && ++big_init_gaps > 2)
3183 do_zeroing = false; // leave the hole, next time
3184 }
3185 }
3186
3187 // Collect the store and move on:
3188 st->set_req(MemNode::Memory, inits);
3189 inits = st; // put it on the linearized chain
3190 set_req(i, zmem); // unhook from previous position
3191
3192 if (zeroes_done == st_off)
3193 zeroes_done = next_init_off;
3194
3195 assert(!do_zeroing || zeroes_done >= next_init_off, "don't miss any");
3196
3197 #ifdef ASSERT
3198 // Various order invariants. Weaker than stores_are_sane because
3199 // a large constant tile can be filled in by smaller non-constant stores.
3200 assert(st_off >= last_init_off, "inits do not reverse");
3201 last_init_off = st_off;
3202 const Type* val = NULL;
3203 if (st_size >= BytesPerInt &&
3204 (val = phase->type(st->in(MemNode::ValueIn)))->singleton() &&
3205 (int)val->basic_type() < (int)T_OBJECT) {
3206 assert(st_off >= last_tile_end, "tiles do not overlap");
3207 assert(st_off >= last_init_end, "tiles do not overwrite inits");
3208 last_tile_end = MAX2(last_tile_end, next_init_off);
3209 } else {
3210 intptr_t st_tile_end = align_size_up(next_init_off, BytesPerLong);
3211 assert(st_tile_end >= last_tile_end, "inits stay with tiles");
3212 assert(st_off >= last_init_end, "inits do not overlap");
3213 last_init_end = next_init_off; // it's a non-tile
3214 }
3215 #endif //ASSERT
3216 }
3217
3218 remove_extra_zeroes(); // clear out all the zmems left over
3219 add_req(inits);
3220
3221 if (!ZeroTLAB) {
3222 // If anything remains to be zeroed, zero it all now.
3223 zeroes_done = align_size_down(zeroes_done, BytesPerInt);
3224 // if it is the last unused 4 bytes of an instance, forget about it
3225 intptr_t size_limit = phase->find_intptr_t_con(size_in_bytes, max_jint);
3226 if (zeroes_done + BytesPerLong >= size_limit) {
3227 assert(allocation() != NULL, "");
3228 Node* klass_node = allocation()->in(AllocateNode::KlassNode);
3229 ciKlass* k = phase->type(klass_node)->is_klassptr()->klass();
3230 if (zeroes_done == k->layout_helper())
3231 zeroes_done = size_limit;
3232 }
3233 if (zeroes_done < size_limit) {
3234 rawmem = ClearArrayNode::clear_memory(rawctl, rawmem, rawptr,
3235 zeroes_done, size_in_bytes, phase);
3236 }
3237 }
3238
3239 set_complete(phase);
3240 return rawmem;
3241 }
3242
3243
3244 #ifdef ASSERT
3245 bool InitializeNode::stores_are_sane(PhaseTransform* phase) {
3246 if (is_complete())
3247 return true; // stores could be anything at this point
3248 assert(allocation() != NULL, "must be present");
3249 intptr_t last_off = allocation()->minimum_header_size();
3250 for (uint i = InitializeNode::RawStores; i < req(); i++) {
3251 Node* st = in(i);
3252 intptr_t st_off = get_store_offset(st, phase);
3253 if (st_off < 0) continue; // ignore dead garbage
3254 if (last_off > st_off) {
3255 tty->print_cr("*** bad store offset at %d: %d > %d", i, last_off, st_off);
3256 this->dump(2);
3257 assert(false, "ascending store offsets");
3258 return false;
3259 }
3260 last_off = st_off + st->as_Store()->memory_size();
3261 }
3262 return true;
3263 }
3264 #endif //ASSERT
3265
3266
3267
3268
3269 //============================MergeMemNode=====================================
3270 //
3271 // SEMANTICS OF MEMORY MERGES: A MergeMem is a memory state assembled from several
3272 // contributing store or call operations. Each contributor provides the memory
3273 // state for a particular "alias type" (see Compile::alias_type). For example,
3274 // if a MergeMem has an input X for alias category #6, then any memory reference
3275 // to alias category #6 may use X as its memory state input, as an exact equivalent
3276 // to using the MergeMem as a whole.
3277 // Load<6>( MergeMem(<6>: X, ...), p ) <==> Load<6>(X,p)
3278 //
3279 // (Here, the <N> notation gives the index of the relevant adr_type.)
3280 //
3281 // In one special case (and more cases in the future), alias categories overlap.
3282 // The special alias category "Bot" (Compile::AliasIdxBot) includes all memory
3283 // states. Therefore, if a MergeMem has only one contributing input W for Bot,
3284 // it is exactly equivalent to that state W:
3285 // MergeMem(<Bot>: W) <==> W
3286 //
3287 // Usually, the merge has more than one input. In that case, where inputs
3288 // overlap (i.e., one is Bot), the narrower alias type determines the memory
3289 // state for that type, and the wider alias type (Bot) fills in everywhere else:
3290 // Load<5>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<5>(W,p)
3291 // Load<6>( MergeMem(<Bot>: W, <6>: X), p ) <==> Load<6>(X,p)
3292 //
3293 // A merge can take a "wide" memory state as one of its narrow inputs.
3294 // This simply means that the merge observes out only the relevant parts of
3295 // the wide input. That is, wide memory states arriving at narrow merge inputs
3296 // are implicitly "filtered" or "sliced" as necessary. (This is rare.)
3297 //
3298 // These rules imply that MergeMem nodes may cascade (via their <Bot> links),
3299 // and that memory slices "leak through":
3300 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y)) <==> MergeMem(<Bot>: W, <7>: Y)
3301 //
3302 // But, in such a cascade, repeated memory slices can "block the leak":
3303 // MergeMem(<Bot>: MergeMem(<Bot>: W, <7>: Y), <7>: Y') <==> MergeMem(<Bot>: W, <7>: Y')
3304 //
3305 // In the last example, Y is not part of the combined memory state of the
3306 // outermost MergeMem. The system must, of course, prevent unschedulable
3307 // memory states from arising, so you can be sure that the state Y is somehow
3308 // a precursor to state Y'.
3309 //
3310 //
3311 // REPRESENTATION OF MEMORY MERGES: The indexes used to address the Node::in array
3312 // of each MergeMemNode array are exactly the numerical alias indexes, including
3313 // but not limited to AliasIdxTop, AliasIdxBot, and AliasIdxRaw. The functions
3314 // Compile::alias_type (and kin) produce and manage these indexes.
3315 //
3316 // By convention, the value of in(AliasIdxTop) (i.e., in(1)) is always the top node.
3317 // (Note that this provides quick access to the top node inside MergeMem methods,
3318 // without the need to reach out via TLS to Compile::current.)
3319 //
3320 // As a consequence of what was just described, a MergeMem that represents a full
3321 // memory state has an edge in(AliasIdxBot) which is a "wide" memory state,
3322 // containing all alias categories.
3323 //
3324 // MergeMem nodes never (?) have control inputs, so in(0) is NULL.
3325 //
3326 // All other edges in(N) (including in(AliasIdxRaw), which is in(3)) are either
3327 // a memory state for the alias type <N>, or else the top node, meaning that
3328 // there is no particular input for that alias type. Note that the length of
3329 // a MergeMem is variable, and may be extended at any time to accommodate new
3330 // memory states at larger alias indexes. When merges grow, they are of course
3331 // filled with "top" in the unused in() positions.
3332 //
3333 // This use of top is named "empty_memory()", or "empty_mem" (no-memory) as a variable.
3334 // (Top was chosen because it works smoothly with passes like GCM.)
3335 //
3336 // For convenience, we hardwire the alias index for TypeRawPtr::BOTTOM. (It is
3337 // the type of random VM bits like TLS references.) Since it is always the
3338 // first non-Bot memory slice, some low-level loops use it to initialize an
3339 // index variable: for (i = AliasIdxRaw; i < req(); i++).
3340 //
3341 //
3342 // ACCESSORS: There is a special accessor MergeMemNode::base_memory which returns
3343 // the distinguished "wide" state. The accessor MergeMemNode::memory_at(N) returns
3344 // the memory state for alias type <N>, or (if there is no particular slice at <N>,
3345 // it returns the base memory. To prevent bugs, memory_at does not accept <Top>
3346 // or <Bot> indexes. The iterator MergeMemStream provides robust iteration over
3347 // MergeMem nodes or pairs of such nodes, ensuring that the non-top edges are visited.
3348 //
3349 // %%%% We may get rid of base_memory as a separate accessor at some point; it isn't
3350 // really that different from the other memory inputs. An abbreviation called
3351 // "bot_memory()" for "memory_at(AliasIdxBot)" would keep code tidy.
3352 //
3353 //
3354 // PARTIAL MEMORY STATES: During optimization, MergeMem nodes may arise that represent
3355 // partial memory states. When a Phi splits through a MergeMem, the copy of the Phi
3356 // that "emerges though" the base memory will be marked as excluding the alias types
3357 // of the other (narrow-memory) copies which "emerged through" the narrow edges:
3358 //
3359 // Phi<Bot>(U, MergeMem(<Bot>: W, <8>: Y))
3360 // ==Ideal=> MergeMem(<Bot>: Phi<Bot-8>(U, W), Phi<8>(U, Y))
3361 //
3362 // This strange "subtraction" effect is necessary to ensure IGVN convergence.
3363 // (It is currently unimplemented.) As you can see, the resulting merge is
3364 // actually a disjoint union of memory states, rather than an overlay.
3365 //
3366
3367 //------------------------------MergeMemNode-----------------------------------
3368 Node* MergeMemNode::make_empty_memory() {
3369 Node* empty_memory = (Node*) Compile::current()->top();
3370 assert(empty_memory->is_top(), "correct sentinel identity");
3371 return empty_memory;
3372 }
3373
3374 MergeMemNode::MergeMemNode(Node *new_base) : Node(1+Compile::AliasIdxRaw) {
3375 init_class_id(Class_MergeMem);
3376 // all inputs are nullified in Node::Node(int)
3377 // set_input(0, NULL); // no control input
3378
3379 // Initialize the edges uniformly to top, for starters.
3380 Node* empty_mem = make_empty_memory();
3381 for (uint i = Compile::AliasIdxTop; i < req(); i++) {
3382 init_req(i,empty_mem);
3383 }
3384 assert(empty_memory() == empty_mem, "");
3385
3386 if( new_base != NULL && new_base->is_MergeMem() ) {
3387 MergeMemNode* mdef = new_base->as_MergeMem();
3388 assert(mdef->empty_memory() == empty_mem, "consistent sentinels");
3389 for (MergeMemStream mms(this, mdef); mms.next_non_empty2(); ) {
3390 mms.set_memory(mms.memory2());
3391 }
3392 assert(base_memory() == mdef->base_memory(), "");
3393 } else {
3394 set_base_memory(new_base);
3395 }
3396 }
3397
3398 // Make a new, untransformed MergeMem with the same base as 'mem'.
3399 // If mem is itself a MergeMem, populate the result with the same edges.
3400 MergeMemNode* MergeMemNode::make(Compile* C, Node* mem) {
3401 return new(C, 1+Compile::AliasIdxRaw) MergeMemNode(mem);
3402 }
3403
3404 //------------------------------cmp--------------------------------------------
3405 uint MergeMemNode::hash() const { return NO_HASH; }
3406 uint MergeMemNode::cmp( const Node &n ) const {
3407 return (&n == this); // Always fail except on self
3408 }
3409
3410 //------------------------------Identity---------------------------------------
3411 Node* MergeMemNode::Identity(PhaseTransform *phase) {
3412 // Identity if this merge point does not record any interesting memory
3413 // disambiguations.
3414 Node* base_mem = base_memory();
3415 Node* empty_mem = empty_memory();
3416 if (base_mem != empty_mem) { // Memory path is not dead?
3417 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3418 Node* mem = in(i);
3419 if (mem != empty_mem && mem != base_mem) {
3420 return this; // Many memory splits; no change
3421 }
3422 }
3423 }
3424 return base_mem; // No memory splits; ID on the one true input
3425 }
3426
3427 //------------------------------Ideal------------------------------------------
3428 // This method is invoked recursively on chains of MergeMem nodes
3429 Node *MergeMemNode::Ideal(PhaseGVN *phase, bool can_reshape) {
3430 // Remove chain'd MergeMems
3431 //
3432 // This is delicate, because the each "in(i)" (i >= Raw) is interpreted
3433 // relative to the "in(Bot)". Since we are patching both at the same time,
3434 // we have to be careful to read each "in(i)" relative to the old "in(Bot)",
3435 // but rewrite each "in(i)" relative to the new "in(Bot)".
3436 Node *progress = NULL;
3437
3438
3439 Node* old_base = base_memory();
3440 Node* empty_mem = empty_memory();
3441 if (old_base == empty_mem)
3442 return NULL; // Dead memory path.
3443
3444 MergeMemNode* old_mbase;
3445 if (old_base != NULL && old_base->is_MergeMem())
3446 old_mbase = old_base->as_MergeMem();
3447 else
3448 old_mbase = NULL;
3449 Node* new_base = old_base;
3450
3451 // simplify stacked MergeMems in base memory
3452 if (old_mbase) new_base = old_mbase->base_memory();
3453
3454 // the base memory might contribute new slices beyond my req()
3455 if (old_mbase) grow_to_match(old_mbase);
3456
3457 // Look carefully at the base node if it is a phi.
3458 PhiNode* phi_base;
3459 if (new_base != NULL && new_base->is_Phi())
3460 phi_base = new_base->as_Phi();
3461 else
3462 phi_base = NULL;
3463
3464 Node* phi_reg = NULL;
3465 uint phi_len = (uint)-1;
3466 if (phi_base != NULL && !phi_base->is_copy()) {
3467 // do not examine phi if degraded to a copy
3468 phi_reg = phi_base->region();
3469 phi_len = phi_base->req();
3470 // see if the phi is unfinished
3471 for (uint i = 1; i < phi_len; i++) {
3472 if (phi_base->in(i) == NULL) {
3473 // incomplete phi; do not look at it yet!
3474 phi_reg = NULL;
3475 phi_len = (uint)-1;
3476 break;
3477 }
3478 }
3479 }
3480
3481 // Note: We do not call verify_sparse on entry, because inputs
3482 // can normalize to the base_memory via subsume_node or similar
3483 // mechanisms. This method repairs that damage.
3484
3485 assert(!old_mbase || old_mbase->is_empty_memory(empty_mem), "consistent sentinels");
3486
3487 // Look at each slice.
3488 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3489 Node* old_in = in(i);
3490 // calculate the old memory value
3491 Node* old_mem = old_in;
3492 if (old_mem == empty_mem) old_mem = old_base;
3493 assert(old_mem == memory_at(i), "");
3494
3495 // maybe update (reslice) the old memory value
3496
3497 // simplify stacked MergeMems
3498 Node* new_mem = old_mem;
3499 MergeMemNode* old_mmem;
3500 if (old_mem != NULL && old_mem->is_MergeMem())
3501 old_mmem = old_mem->as_MergeMem();
3502 else
3503 old_mmem = NULL;
3504 if (old_mmem == this) {
3505 // This can happen if loops break up and safepoints disappear.
3506 // A merge of BotPtr (default) with a RawPtr memory derived from a
3507 // safepoint can be rewritten to a merge of the same BotPtr with
3508 // the BotPtr phi coming into the loop. If that phi disappears
3509 // also, we can end up with a self-loop of the mergemem.
3510 // In general, if loops degenerate and memory effects disappear,
3511 // a mergemem can be left looking at itself. This simply means
3512 // that the mergemem's default should be used, since there is
3513 // no longer any apparent effect on this slice.
3514 // Note: If a memory slice is a MergeMem cycle, it is unreachable
3515 // from start. Update the input to TOP.
3516 new_mem = (new_base == this || new_base == empty_mem)? empty_mem : new_base;
3517 }
3518 else if (old_mmem != NULL) {
3519 new_mem = old_mmem->memory_at(i);
3520 }
3521 // else preceeding memory was not a MergeMem
3522
3523 // replace equivalent phis (unfortunately, they do not GVN together)
3524 if (new_mem != NULL && new_mem != new_base &&
3525 new_mem->req() == phi_len && new_mem->in(0) == phi_reg) {
3526 if (new_mem->is_Phi()) {
3527 PhiNode* phi_mem = new_mem->as_Phi();
3528 for (uint i = 1; i < phi_len; i++) {
3529 if (phi_base->in(i) != phi_mem->in(i)) {
3530 phi_mem = NULL;
3531 break;
3532 }
3533 }
3534 if (phi_mem != NULL) {
3535 // equivalent phi nodes; revert to the def
3536 new_mem = new_base;
3537 }
3538 }
3539 }
3540
3541 // maybe store down a new value
3542 Node* new_in = new_mem;
3543 if (new_in == new_base) new_in = empty_mem;
3544
3545 if (new_in != old_in) {
3546 // Warning: Do not combine this "if" with the previous "if"
3547 // A memory slice might have be be rewritten even if it is semantically
3548 // unchanged, if the base_memory value has changed.
3549 set_req(i, new_in);
3550 progress = this; // Report progress
3551 }
3552 }
3553
3554 if (new_base != old_base) {
3555 set_req(Compile::AliasIdxBot, new_base);
3556 // Don't use set_base_memory(new_base), because we need to update du.
3557 assert(base_memory() == new_base, "");
3558 progress = this;
3559 }
3560
3561 if( base_memory() == this ) {
3562 // a self cycle indicates this memory path is dead
3563 set_req(Compile::AliasIdxBot, empty_mem);
3564 }
3565
3566 // Resolve external cycles by calling Ideal on a MergeMem base_memory
3567 // Recursion must occur after the self cycle check above
3568 if( base_memory()->is_MergeMem() ) {
3569 MergeMemNode *new_mbase = base_memory()->as_MergeMem();
3570 Node *m = phase->transform(new_mbase); // Rollup any cycles
3571 if( m != NULL && (m->is_top() ||
3572 m->is_MergeMem() && m->as_MergeMem()->base_memory() == empty_mem) ) {
3573 // propagate rollup of dead cycle to self
3574 set_req(Compile::AliasIdxBot, empty_mem);
3575 }
3576 }
3577
3578 if( base_memory() == empty_mem ) {
3579 progress = this;
3580 // Cut inputs during Parse phase only.
3581 // During Optimize phase a dead MergeMem node will be subsumed by Top.
3582 if( !can_reshape ) {
3583 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3584 if( in(i) != empty_mem ) { set_req(i, empty_mem); }
3585 }
3586 }
3587 }
3588
3589 if( !progress && base_memory()->is_Phi() && can_reshape ) {
3590 // Check if PhiNode::Ideal's "Split phis through memory merges"
3591 // transform should be attempted. Look for this->phi->this cycle.
3592 uint merge_width = req();
3593 if (merge_width > Compile::AliasIdxRaw) {
3594 PhiNode* phi = base_memory()->as_Phi();
3595 for( uint i = 1; i < phi->req(); ++i ) {// For all paths in
3596 if (phi->in(i) == this) {
3597 phase->is_IterGVN()->_worklist.push(phi);
3598 break;
3599 }
3600 }
3601 }
3602 }
3603
3604 assert(progress || verify_sparse(), "please, no dups of base");
3605 return progress;
3606 }
3607
3608 //-------------------------set_base_memory-------------------------------------
3609 void MergeMemNode::set_base_memory(Node *new_base) {
3610 Node* empty_mem = empty_memory();
3611 set_req(Compile::AliasIdxBot, new_base);
3612 assert(memory_at(req()) == new_base, "must set default memory");
3613 // Clear out other occurrences of new_base:
3614 if (new_base != empty_mem) {
3615 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3616 if (in(i) == new_base) set_req(i, empty_mem);
3617 }
3618 }
3619 }
3620
3621 //------------------------------out_RegMask------------------------------------
3622 const RegMask &MergeMemNode::out_RegMask() const {
3623 return RegMask::Empty;
3624 }
3625
3626 //------------------------------dump_spec--------------------------------------
3627 #ifndef PRODUCT
3628 void MergeMemNode::dump_spec(outputStream *st) const {
3629 st->print(" {");
3630 Node* base_mem = base_memory();
3631 for( uint i = Compile::AliasIdxRaw; i < req(); i++ ) {
3632 Node* mem = memory_at(i);
3633 if (mem == base_mem) { st->print(" -"); continue; }
3634 st->print( " N%d:", mem->_idx );
3635 Compile::current()->get_adr_type(i)->dump_on(st);
3636 }
3637 st->print(" }");
3638 }
3639 #endif // !PRODUCT
3640
3641
3642 #ifdef ASSERT
3643 static bool might_be_same(Node* a, Node* b) {
3644 if (a == b) return true;
3645 if (!(a->is_Phi() || b->is_Phi())) return false;
3646 // phis shift around during optimization
3647 return true; // pretty stupid...
3648 }
3649
3650 // verify a narrow slice (either incoming or outgoing)
3651 static void verify_memory_slice(const MergeMemNode* m, int alias_idx, Node* n) {
3652 if (!VerifyAliases) return; // don't bother to verify unless requested
3653 if (is_error_reported()) return; // muzzle asserts when debugging an error
3654 if (Node::in_dump()) return; // muzzle asserts when printing
3655 assert(alias_idx >= Compile::AliasIdxRaw, "must not disturb base_memory or sentinel");
3656 assert(n != NULL, "");
3657 // Elide intervening MergeMem's
3658 while (n->is_MergeMem()) {
3659 n = n->as_MergeMem()->memory_at(alias_idx);
3660 }
3661 Compile* C = Compile::current();
3662 const TypePtr* n_adr_type = n->adr_type();
3663 if (n == m->empty_memory()) {
3664 // Implicit copy of base_memory()
3665 } else if (n_adr_type != TypePtr::BOTTOM) {
3666 assert(n_adr_type != NULL, "new memory must have a well-defined adr_type");
3667 assert(C->must_alias(n_adr_type, alias_idx), "new memory must match selected slice");
3668 } else {
3669 // A few places like make_runtime_call "know" that VM calls are narrow,
3670 // and can be used to update only the VM bits stored as TypeRawPtr::BOTTOM.
3671 bool expected_wide_mem = false;
3672 if (n == m->base_memory()) {
3673 expected_wide_mem = true;
3674 } else if (alias_idx == Compile::AliasIdxRaw ||
3675 n == m->memory_at(Compile::AliasIdxRaw)) {
3676 expected_wide_mem = true;
3677 } else if (!C->alias_type(alias_idx)->is_rewritable()) {
3678 // memory can "leak through" calls on channels that
3679 // are write-once. Allow this also.
3680 expected_wide_mem = true;
3681 }
3682 assert(expected_wide_mem, "expected narrow slice replacement");
3683 }
3684 }
3685 #else // !ASSERT
3686 #define verify_memory_slice(m,i,n) (0) // PRODUCT version is no-op
3687 #endif
3688
3689
3690 //-----------------------------memory_at---------------------------------------
3691 Node* MergeMemNode::memory_at(uint alias_idx) const {
3692 assert(alias_idx >= Compile::AliasIdxRaw ||
3693 alias_idx == Compile::AliasIdxBot && Compile::current()->AliasLevel() == 0,
3694 "must avoid base_memory and AliasIdxTop");
3695
3696 // Otherwise, it is a narrow slice.
3697 Node* n = alias_idx < req() ? in(alias_idx) : empty_memory();
3698 Compile *C = Compile::current();
3699 if (is_empty_memory(n)) {
3700 // the array is sparse; empty slots are the "top" node
3701 n = base_memory();
3702 assert(Node::in_dump()
3703 || n == NULL || n->bottom_type() == Type::TOP
3704 || n->adr_type() == TypePtr::BOTTOM
3705 || n->adr_type() == TypeRawPtr::BOTTOM
3706 || Compile::current()->AliasLevel() == 0,
3707 "must be a wide memory");
3708 // AliasLevel == 0 if we are organizing the memory states manually.
3709 // See verify_memory_slice for comments on TypeRawPtr::BOTTOM.
3710 } else {
3711 // make sure the stored slice is sane
3712 #ifdef ASSERT
3713 if (is_error_reported() || Node::in_dump()) {
3714 } else if (might_be_same(n, base_memory())) {
3715 // Give it a pass: It is a mostly harmless repetition of the base.
3716 // This can arise normally from node subsumption during optimization.
3717 } else {
3718 verify_memory_slice(this, alias_idx, n);
3719 }
3720 #endif
3721 }
3722 return n;
3723 }
3724
3725 //---------------------------set_memory_at-------------------------------------
3726 void MergeMemNode::set_memory_at(uint alias_idx, Node *n) {
3727 verify_memory_slice(this, alias_idx, n);
3728 Node* empty_mem = empty_memory();
3729 if (n == base_memory()) n = empty_mem; // collapse default
3730 uint need_req = alias_idx+1;
3731 if (req() < need_req) {
3732 if (n == empty_mem) return; // already the default, so do not grow me
3733 // grow the sparse array
3734 do {
3735 add_req(empty_mem);
3736 } while (req() < need_req);
3737 }
3738 set_req( alias_idx, n );
3739 }
3740
3741
3742
3743 //--------------------------iteration_setup------------------------------------
3744 void MergeMemNode::iteration_setup(const MergeMemNode* other) {
3745 if (other != NULL) {
3746 grow_to_match(other);
3747 // invariant: the finite support of mm2 is within mm->req()
3748 #ifdef ASSERT
3749 for (uint i = req(); i < other->req(); i++) {
3750 assert(other->is_empty_memory(other->in(i)), "slice left uncovered");
3751 }
3752 #endif
3753 }
3754 // Replace spurious copies of base_memory by top.
3755 Node* base_mem = base_memory();
3756 if (base_mem != NULL && !base_mem->is_top()) {
3757 for (uint i = Compile::AliasIdxBot+1, imax = req(); i < imax; i++) {
3758 if (in(i) == base_mem)
3759 set_req(i, empty_memory());
3760 }
3761 }
3762 }
3763
3764 //---------------------------grow_to_match-------------------------------------
3765 void MergeMemNode::grow_to_match(const MergeMemNode* other) {
3766 Node* empty_mem = empty_memory();
3767 assert(other->is_empty_memory(empty_mem), "consistent sentinels");
3768 // look for the finite support of the other memory
3769 for (uint i = other->req(); --i >= req(); ) {
3770 if (other->in(i) != empty_mem) {
3771 uint new_len = i+1;
3772 while (req() < new_len) add_req(empty_mem);
3773 break;
3774 }
3775 }
3776 }
3777
3778 //---------------------------verify_sparse-------------------------------------
3779 #ifndef PRODUCT
3780 bool MergeMemNode::verify_sparse() const {
3781 assert(is_empty_memory(make_empty_memory()), "sane sentinel");
3782 Node* base_mem = base_memory();
3783 // The following can happen in degenerate cases, since empty==top.
3784 if (is_empty_memory(base_mem)) return true;
3785 for (uint i = Compile::AliasIdxRaw; i < req(); i++) {
3786 assert(in(i) != NULL, "sane slice");
3787 if (in(i) == base_mem) return false; // should have been the sentinel value!
3788 }
3789 return true;
3790 }
3791
3792 bool MergeMemStream::match_memory(Node* mem, const MergeMemNode* mm, int idx) {
3793 Node* n;
3794 n = mm->in(idx);
3795 if (mem == n) return true; // might be empty_memory()
3796 n = (idx == Compile::AliasIdxBot)? mm->base_memory(): mm->memory_at(idx);
3797 if (mem == n) return true;
3798 while (n->is_Phi() && (n = n->as_Phi()->is_copy()) != NULL) {
3799 if (mem == n) return true;
3800 if (n == NULL) break;
3801 }
3802 return false;
3803 }
3804 #endif // !PRODUCT