Sat, 16 Mar 2013 07:39:14 -0700
8009166: [parfait] Null pointer deference in hotspot/src/share/vm/opto/type.cpp
Summary: add guarantee() to as_instance_type()
Reviewed-by: kvn, twisti
1 /*
2 * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "precompiled.hpp"
26 #include "ci/bcEscapeAnalyzer.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "libadt/vectset.hpp"
29 #include "memory/allocation.hpp"
30 #include "opto/c2compiler.hpp"
31 #include "opto/callnode.hpp"
32 #include "opto/cfgnode.hpp"
33 #include "opto/compile.hpp"
34 #include "opto/escape.hpp"
35 #include "opto/phaseX.hpp"
36 #include "opto/rootnode.hpp"
38 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
39 _nodes(C->comp_arena(), C->unique(), C->unique(), NULL),
40 _collecting(true),
41 _verify(false),
42 _compile(C),
43 _igvn(igvn),
44 _node_map(C->comp_arena()) {
45 // Add unknown java object.
46 add_java_object(C->top(), PointsToNode::GlobalEscape);
47 phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
48 // Add ConP(#NULL) and ConN(#NULL) nodes.
49 Node* oop_null = igvn->zerocon(T_OBJECT);
50 assert(oop_null->_idx < nodes_size(), "should be created already");
51 add_java_object(oop_null, PointsToNode::NoEscape);
52 null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
53 if (UseCompressedOops) {
54 Node* noop_null = igvn->zerocon(T_NARROWOOP);
55 assert(noop_null->_idx < nodes_size(), "should be created already");
56 map_ideal_node(noop_null, null_obj);
57 }
58 _pcmp_neq = NULL; // Should be initialized
59 _pcmp_eq = NULL;
60 }
62 bool ConnectionGraph::has_candidates(Compile *C) {
63 // EA brings benefits only when the code has allocations and/or locks which
64 // are represented by ideal Macro nodes.
65 int cnt = C->macro_count();
66 for( int i=0; i < cnt; i++ ) {
67 Node *n = C->macro_node(i);
68 if ( n->is_Allocate() )
69 return true;
70 if( n->is_Lock() ) {
71 Node* obj = n->as_Lock()->obj_node()->uncast();
72 if( !(obj->is_Parm() || obj->is_Con()) )
73 return true;
74 }
75 }
76 return false;
77 }
79 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
80 Compile::TracePhase t2("escapeAnalysis", &Phase::_t_escapeAnalysis, true);
81 ResourceMark rm;
83 // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
84 // to create space for them in ConnectionGraph::_nodes[].
85 Node* oop_null = igvn->zerocon(T_OBJECT);
86 Node* noop_null = igvn->zerocon(T_NARROWOOP);
87 ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn);
88 // Perform escape analysis
89 if (congraph->compute_escape()) {
90 // There are non escaping objects.
91 C->set_congraph(congraph);
92 }
93 // Cleanup.
94 if (oop_null->outcnt() == 0)
95 igvn->hash_delete(oop_null);
96 if (noop_null->outcnt() == 0)
97 igvn->hash_delete(noop_null);
98 }
100 bool ConnectionGraph::compute_escape() {
101 Compile* C = _compile;
102 PhaseGVN* igvn = _igvn;
104 // Worklists used by EA.
105 Unique_Node_List delayed_worklist;
106 GrowableArray<Node*> alloc_worklist;
107 GrowableArray<Node*> ptr_cmp_worklist;
108 GrowableArray<Node*> storestore_worklist;
109 GrowableArray<PointsToNode*> ptnodes_worklist;
110 GrowableArray<JavaObjectNode*> java_objects_worklist;
111 GrowableArray<JavaObjectNode*> non_escaped_worklist;
112 GrowableArray<FieldNode*> oop_fields_worklist;
113 DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
115 { Compile::TracePhase t3("connectionGraph", &Phase::_t_connectionGraph, true);
117 // 1. Populate Connection Graph (CG) with PointsTo nodes.
118 ideal_nodes.map(C->unique(), NULL); // preallocate space
119 // Initialize worklist
120 if (C->root() != NULL) {
121 ideal_nodes.push(C->root());
122 }
123 for( uint next = 0; next < ideal_nodes.size(); ++next ) {
124 Node* n = ideal_nodes.at(next);
125 // Create PointsTo nodes and add them to Connection Graph. Called
126 // only once per ideal node since ideal_nodes is Unique_Node list.
127 add_node_to_connection_graph(n, &delayed_worklist);
128 PointsToNode* ptn = ptnode_adr(n->_idx);
129 if (ptn != NULL) {
130 ptnodes_worklist.append(ptn);
131 if (ptn->is_JavaObject()) {
132 java_objects_worklist.append(ptn->as_JavaObject());
133 if ((n->is_Allocate() || n->is_CallStaticJava()) &&
134 (ptn->escape_state() < PointsToNode::GlobalEscape)) {
135 // Only allocations and java static calls results are interesting.
136 non_escaped_worklist.append(ptn->as_JavaObject());
137 }
138 } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
139 oop_fields_worklist.append(ptn->as_Field());
140 }
141 }
142 if (n->is_MergeMem()) {
143 // Collect all MergeMem nodes to add memory slices for
144 // scalar replaceable objects in split_unique_types().
145 _mergemem_worklist.append(n->as_MergeMem());
146 } else if (OptimizePtrCompare && n->is_Cmp() &&
147 (n->Opcode() == Op_CmpP || n->Opcode() == Op_CmpN)) {
148 // Collect compare pointers nodes.
149 ptr_cmp_worklist.append(n);
150 } else if (n->is_MemBarStoreStore()) {
151 // Collect all MemBarStoreStore nodes so that depending on the
152 // escape status of the associated Allocate node some of them
153 // may be eliminated.
154 storestore_worklist.append(n);
155 #ifdef ASSERT
156 } else if(n->is_AddP()) {
157 // Collect address nodes for graph verification.
158 addp_worklist.append(n);
159 #endif
160 }
161 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
162 Node* m = n->fast_out(i); // Get user
163 ideal_nodes.push(m);
164 }
165 }
166 if (non_escaped_worklist.length() == 0) {
167 _collecting = false;
168 return false; // Nothing to do.
169 }
170 // Add final simple edges to graph.
171 while(delayed_worklist.size() > 0) {
172 Node* n = delayed_worklist.pop();
173 add_final_edges(n);
174 }
175 int ptnodes_length = ptnodes_worklist.length();
177 #ifdef ASSERT
178 if (VerifyConnectionGraph) {
179 // Verify that no new simple edges could be created and all
180 // local vars has edges.
181 _verify = true;
182 for (int next = 0; next < ptnodes_length; ++next) {
183 PointsToNode* ptn = ptnodes_worklist.at(next);
184 add_final_edges(ptn->ideal_node());
185 if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
186 ptn->dump();
187 assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
188 }
189 }
190 _verify = false;
191 }
192 #endif
194 // 2. Finish Graph construction by propagating references to all
195 // java objects through graph.
196 if (!complete_connection_graph(ptnodes_worklist, non_escaped_worklist,
197 java_objects_worklist, oop_fields_worklist)) {
198 // All objects escaped or hit time or iterations limits.
199 _collecting = false;
200 return false;
201 }
203 // 3. Adjust scalar_replaceable state of nonescaping objects and push
204 // scalar replaceable allocations on alloc_worklist for processing
205 // in split_unique_types().
206 int non_escaped_length = non_escaped_worklist.length();
207 for (int next = 0; next < non_escaped_length; next++) {
208 JavaObjectNode* ptn = non_escaped_worklist.at(next);
209 if (ptn->escape_state() == PointsToNode::NoEscape &&
210 ptn->scalar_replaceable()) {
211 adjust_scalar_replaceable_state(ptn);
212 if (ptn->scalar_replaceable()) {
213 alloc_worklist.append(ptn->ideal_node());
214 }
215 }
216 }
218 #ifdef ASSERT
219 if (VerifyConnectionGraph) {
220 // Verify that graph is complete - no new edges could be added or needed.
221 verify_connection_graph(ptnodes_worklist, non_escaped_worklist,
222 java_objects_worklist, addp_worklist);
223 }
224 assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
225 assert(null_obj->escape_state() == PointsToNode::NoEscape &&
226 null_obj->edge_count() == 0 &&
227 !null_obj->arraycopy_src() &&
228 !null_obj->arraycopy_dst(), "sanity");
229 #endif
231 _collecting = false;
233 } // TracePhase t3("connectionGraph")
235 // 4. Optimize ideal graph based on EA information.
236 bool has_non_escaping_obj = (non_escaped_worklist.length() > 0);
237 if (has_non_escaping_obj) {
238 optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
239 }
241 #ifndef PRODUCT
242 if (PrintEscapeAnalysis) {
243 dump(ptnodes_worklist); // Dump ConnectionGraph
244 }
245 #endif
247 bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
248 #ifdef ASSERT
249 if (VerifyConnectionGraph) {
250 int alloc_length = alloc_worklist.length();
251 for (int next = 0; next < alloc_length; ++next) {
252 Node* n = alloc_worklist.at(next);
253 PointsToNode* ptn = ptnode_adr(n->_idx);
254 assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
255 }
256 }
257 #endif
259 // 5. Separate memory graph for scalar replaceable allcations.
260 if (has_scalar_replaceable_candidates &&
261 C->AliasLevel() >= 3 && EliminateAllocations) {
262 // Now use the escape information to create unique types for
263 // scalar replaceable objects.
264 split_unique_types(alloc_worklist);
265 if (C->failing()) return false;
266 C->print_method("After Escape Analysis", 2);
268 #ifdef ASSERT
269 } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
270 tty->print("=== No allocations eliminated for ");
271 C->method()->print_short_name();
272 if(!EliminateAllocations) {
273 tty->print(" since EliminateAllocations is off ===");
274 } else if(!has_scalar_replaceable_candidates) {
275 tty->print(" since there are no scalar replaceable candidates ===");
276 } else if(C->AliasLevel() < 3) {
277 tty->print(" since AliasLevel < 3 ===");
278 }
279 tty->cr();
280 #endif
281 }
282 return has_non_escaping_obj;
283 }
285 // Utility function for nodes that load an object
286 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
287 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
288 // ThreadLocal has RawPtr type.
289 const Type* t = _igvn->type(n);
290 if (t->make_ptr() != NULL) {
291 Node* adr = n->in(MemNode::Address);
292 #ifdef ASSERT
293 if (!adr->is_AddP()) {
294 assert(_igvn->type(adr)->isa_rawptr(), "sanity");
295 } else {
296 assert((ptnode_adr(adr->_idx) == NULL ||
297 ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
298 }
299 #endif
300 add_local_var_and_edge(n, PointsToNode::NoEscape,
301 adr, delayed_worklist);
302 }
303 }
305 // Populate Connection Graph with PointsTo nodes and create simple
306 // connection graph edges.
307 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
308 assert(!_verify, "this method sould not be called for verification");
309 PhaseGVN* igvn = _igvn;
310 uint n_idx = n->_idx;
311 PointsToNode* n_ptn = ptnode_adr(n_idx);
312 if (n_ptn != NULL)
313 return; // No need to redefine PointsTo node during first iteration.
315 if (n->is_Call()) {
316 // Arguments to allocation and locking don't escape.
317 if (n->is_AbstractLock()) {
318 // Put Lock and Unlock nodes on IGVN worklist to process them during
319 // first IGVN optimization when escape information is still available.
320 record_for_optimizer(n);
321 } else if (n->is_Allocate()) {
322 add_call_node(n->as_Call());
323 record_for_optimizer(n);
324 } else {
325 if (n->is_CallStaticJava()) {
326 const char* name = n->as_CallStaticJava()->_name;
327 if (name != NULL && strcmp(name, "uncommon_trap") == 0)
328 return; // Skip uncommon traps
329 }
330 // Don't mark as processed since call's arguments have to be processed.
331 delayed_worklist->push(n);
332 // Check if a call returns an object.
333 if (n->as_Call()->returns_pointer() &&
334 n->as_Call()->proj_out(TypeFunc::Parms) != NULL) {
335 add_call_node(n->as_Call());
336 }
337 }
338 return;
339 }
340 // Put this check here to process call arguments since some call nodes
341 // point to phantom_obj.
342 if (n_ptn == phantom_obj || n_ptn == null_obj)
343 return; // Skip predefined nodes.
345 int opcode = n->Opcode();
346 switch (opcode) {
347 case Op_AddP: {
348 Node* base = get_addp_base(n);
349 PointsToNode* ptn_base = ptnode_adr(base->_idx);
350 // Field nodes are created for all field types. They are used in
351 // adjust_scalar_replaceable_state() and split_unique_types().
352 // Note, non-oop fields will have only base edges in Connection
353 // Graph because such fields are not used for oop loads and stores.
354 int offset = address_offset(n, igvn);
355 add_field(n, PointsToNode::NoEscape, offset);
356 if (ptn_base == NULL) {
357 delayed_worklist->push(n); // Process it later.
358 } else {
359 n_ptn = ptnode_adr(n_idx);
360 add_base(n_ptn->as_Field(), ptn_base);
361 }
362 break;
363 }
364 case Op_CastX2P: {
365 map_ideal_node(n, phantom_obj);
366 break;
367 }
368 case Op_CastPP:
369 case Op_CheckCastPP:
370 case Op_EncodeP:
371 case Op_DecodeN:
372 case Op_EncodePKlass:
373 case Op_DecodeNKlass: {
374 add_local_var_and_edge(n, PointsToNode::NoEscape,
375 n->in(1), delayed_worklist);
376 break;
377 }
378 case Op_CMoveP: {
379 add_local_var(n, PointsToNode::NoEscape);
380 // Do not add edges during first iteration because some could be
381 // not defined yet.
382 delayed_worklist->push(n);
383 break;
384 }
385 case Op_ConP:
386 case Op_ConN:
387 case Op_ConNKlass: {
388 // assume all oop constants globally escape except for null
389 PointsToNode::EscapeState es;
390 if (igvn->type(n) == TypePtr::NULL_PTR ||
391 igvn->type(n) == TypeNarrowOop::NULL_PTR) {
392 es = PointsToNode::NoEscape;
393 } else {
394 es = PointsToNode::GlobalEscape;
395 }
396 add_java_object(n, es);
397 break;
398 }
399 case Op_CreateEx: {
400 // assume that all exception objects globally escape
401 add_java_object(n, PointsToNode::GlobalEscape);
402 break;
403 }
404 case Op_LoadKlass:
405 case Op_LoadNKlass: {
406 // Unknown class is loaded
407 map_ideal_node(n, phantom_obj);
408 break;
409 }
410 case Op_LoadP:
411 case Op_LoadN:
412 case Op_LoadPLocked: {
413 add_objload_to_connection_graph(n, delayed_worklist);
414 break;
415 }
416 case Op_Parm: {
417 map_ideal_node(n, phantom_obj);
418 break;
419 }
420 case Op_PartialSubtypeCheck: {
421 // Produces Null or notNull and is used in only in CmpP so
422 // phantom_obj could be used.
423 map_ideal_node(n, phantom_obj); // Result is unknown
424 break;
425 }
426 case Op_Phi: {
427 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
428 // ThreadLocal has RawPtr type.
429 const Type* t = n->as_Phi()->type();
430 if (t->make_ptr() != NULL) {
431 add_local_var(n, PointsToNode::NoEscape);
432 // Do not add edges during first iteration because some could be
433 // not defined yet.
434 delayed_worklist->push(n);
435 }
436 break;
437 }
438 case Op_Proj: {
439 // we are only interested in the oop result projection from a call
440 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
441 n->in(0)->as_Call()->returns_pointer()) {
442 add_local_var_and_edge(n, PointsToNode::NoEscape,
443 n->in(0), delayed_worklist);
444 }
445 break;
446 }
447 case Op_Rethrow: // Exception object escapes
448 case Op_Return: {
449 if (n->req() > TypeFunc::Parms &&
450 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
451 // Treat Return value as LocalVar with GlobalEscape escape state.
452 add_local_var_and_edge(n, PointsToNode::GlobalEscape,
453 n->in(TypeFunc::Parms), delayed_worklist);
454 }
455 break;
456 }
457 case Op_GetAndSetP:
458 case Op_GetAndSetN: {
459 add_objload_to_connection_graph(n, delayed_worklist);
460 // fallthrough
461 }
462 case Op_StoreP:
463 case Op_StoreN:
464 case Op_StoreNKlass:
465 case Op_StorePConditional:
466 case Op_CompareAndSwapP:
467 case Op_CompareAndSwapN: {
468 Node* adr = n->in(MemNode::Address);
469 const Type *adr_type = igvn->type(adr);
470 adr_type = adr_type->make_ptr();
471 if (adr_type->isa_oopptr() ||
472 (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
473 (adr_type == TypeRawPtr::NOTNULL &&
474 adr->in(AddPNode::Address)->is_Proj() &&
475 adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
476 delayed_worklist->push(n); // Process it later.
477 #ifdef ASSERT
478 assert(adr->is_AddP(), "expecting an AddP");
479 if (adr_type == TypeRawPtr::NOTNULL) {
480 // Verify a raw address for a store captured by Initialize node.
481 int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
482 assert(offs != Type::OffsetBot, "offset must be a constant");
483 }
484 #endif
485 } else {
486 // Ignore copy the displaced header to the BoxNode (OSR compilation).
487 if (adr->is_BoxLock())
488 break;
489 // Stored value escapes in unsafe access.
490 if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
491 // Pointer stores in G1 barriers looks like unsafe access.
492 // Ignore such stores to be able scalar replace non-escaping
493 // allocations.
494 if (UseG1GC && adr->is_AddP()) {
495 Node* base = get_addp_base(adr);
496 if (base->Opcode() == Op_LoadP &&
497 base->in(MemNode::Address)->is_AddP()) {
498 adr = base->in(MemNode::Address);
499 Node* tls = get_addp_base(adr);
500 if (tls->Opcode() == Op_ThreadLocal) {
501 int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
502 if (offs == in_bytes(JavaThread::satb_mark_queue_offset() +
503 PtrQueue::byte_offset_of_buf())) {
504 break; // G1 pre barier previous oop value store.
505 }
506 if (offs == in_bytes(JavaThread::dirty_card_queue_offset() +
507 PtrQueue::byte_offset_of_buf())) {
508 break; // G1 post barier card address store.
509 }
510 }
511 }
512 }
513 delayed_worklist->push(n); // Process unsafe access later.
514 break;
515 }
516 #ifdef ASSERT
517 n->dump(1);
518 assert(false, "not unsafe or G1 barrier raw StoreP");
519 #endif
520 }
521 break;
522 }
523 case Op_AryEq:
524 case Op_StrComp:
525 case Op_StrEquals:
526 case Op_StrIndexOf:
527 case Op_EncodeISOArray: {
528 add_local_var(n, PointsToNode::ArgEscape);
529 delayed_worklist->push(n); // Process it later.
530 break;
531 }
532 case Op_ThreadLocal: {
533 add_java_object(n, PointsToNode::ArgEscape);
534 break;
535 }
536 default:
537 ; // Do nothing for nodes not related to EA.
538 }
539 return;
540 }
542 #ifdef ASSERT
543 #define ELSE_FAIL(name) \
544 /* Should not be called for not pointer type. */ \
545 n->dump(1); \
546 assert(false, name); \
547 break;
548 #else
549 #define ELSE_FAIL(name) \
550 break;
551 #endif
553 // Add final simple edges to graph.
554 void ConnectionGraph::add_final_edges(Node *n) {
555 PointsToNode* n_ptn = ptnode_adr(n->_idx);
556 #ifdef ASSERT
557 if (_verify && n_ptn->is_JavaObject())
558 return; // This method does not change graph for JavaObject.
559 #endif
561 if (n->is_Call()) {
562 process_call_arguments(n->as_Call());
563 return;
564 }
565 assert(n->is_Store() || n->is_LoadStore() ||
566 (n_ptn != NULL) && (n_ptn->ideal_node() != NULL),
567 "node should be registered already");
568 int opcode = n->Opcode();
569 switch (opcode) {
570 case Op_AddP: {
571 Node* base = get_addp_base(n);
572 PointsToNode* ptn_base = ptnode_adr(base->_idx);
573 assert(ptn_base != NULL, "field's base should be registered");
574 add_base(n_ptn->as_Field(), ptn_base);
575 break;
576 }
577 case Op_CastPP:
578 case Op_CheckCastPP:
579 case Op_EncodeP:
580 case Op_DecodeN:
581 case Op_EncodePKlass:
582 case Op_DecodeNKlass: {
583 add_local_var_and_edge(n, PointsToNode::NoEscape,
584 n->in(1), NULL);
585 break;
586 }
587 case Op_CMoveP: {
588 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
589 Node* in = n->in(i);
590 if (in == NULL)
591 continue; // ignore NULL
592 Node* uncast_in = in->uncast();
593 if (uncast_in->is_top() || uncast_in == n)
594 continue; // ignore top or inputs which go back this node
595 PointsToNode* ptn = ptnode_adr(in->_idx);
596 assert(ptn != NULL, "node should be registered");
597 add_edge(n_ptn, ptn);
598 }
599 break;
600 }
601 case Op_LoadP:
602 case Op_LoadN:
603 case Op_LoadPLocked: {
604 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
605 // ThreadLocal has RawPtr type.
606 const Type* t = _igvn->type(n);
607 if (t->make_ptr() != NULL) {
608 Node* adr = n->in(MemNode::Address);
609 add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
610 break;
611 }
612 ELSE_FAIL("Op_LoadP");
613 }
614 case Op_Phi: {
615 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
616 // ThreadLocal has RawPtr type.
617 const Type* t = n->as_Phi()->type();
618 if (t->make_ptr() != NULL) {
619 for (uint i = 1; i < n->req(); i++) {
620 Node* in = n->in(i);
621 if (in == NULL)
622 continue; // ignore NULL
623 Node* uncast_in = in->uncast();
624 if (uncast_in->is_top() || uncast_in == n)
625 continue; // ignore top or inputs which go back this node
626 PointsToNode* ptn = ptnode_adr(in->_idx);
627 assert(ptn != NULL, "node should be registered");
628 add_edge(n_ptn, ptn);
629 }
630 break;
631 }
632 ELSE_FAIL("Op_Phi");
633 }
634 case Op_Proj: {
635 // we are only interested in the oop result projection from a call
636 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
637 n->in(0)->as_Call()->returns_pointer()) {
638 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), NULL);
639 break;
640 }
641 ELSE_FAIL("Op_Proj");
642 }
643 case Op_Rethrow: // Exception object escapes
644 case Op_Return: {
645 if (n->req() > TypeFunc::Parms &&
646 _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
647 // Treat Return value as LocalVar with GlobalEscape escape state.
648 add_local_var_and_edge(n, PointsToNode::GlobalEscape,
649 n->in(TypeFunc::Parms), NULL);
650 break;
651 }
652 ELSE_FAIL("Op_Return");
653 }
654 case Op_StoreP:
655 case Op_StoreN:
656 case Op_StoreNKlass:
657 case Op_StorePConditional:
658 case Op_CompareAndSwapP:
659 case Op_CompareAndSwapN:
660 case Op_GetAndSetP:
661 case Op_GetAndSetN: {
662 Node* adr = n->in(MemNode::Address);
663 if (opcode == Op_GetAndSetP || opcode == Op_GetAndSetN) {
664 const Type* t = _igvn->type(n);
665 if (t->make_ptr() != NULL) {
666 add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
667 }
668 }
669 const Type *adr_type = _igvn->type(adr);
670 adr_type = adr_type->make_ptr();
671 if (adr_type->isa_oopptr() ||
672 (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
673 (adr_type == TypeRawPtr::NOTNULL &&
674 adr->in(AddPNode::Address)->is_Proj() &&
675 adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
676 // Point Address to Value
677 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
678 assert(adr_ptn != NULL &&
679 adr_ptn->as_Field()->is_oop(), "node should be registered");
680 Node *val = n->in(MemNode::ValueIn);
681 PointsToNode* ptn = ptnode_adr(val->_idx);
682 assert(ptn != NULL, "node should be registered");
683 add_edge(adr_ptn, ptn);
684 break;
685 } else if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
686 // Stored value escapes in unsafe access.
687 Node *val = n->in(MemNode::ValueIn);
688 PointsToNode* ptn = ptnode_adr(val->_idx);
689 assert(ptn != NULL, "node should be registered");
690 ptn->set_escape_state(PointsToNode::GlobalEscape);
691 // Add edge to object for unsafe access with offset.
692 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
693 assert(adr_ptn != NULL, "node should be registered");
694 if (adr_ptn->is_Field()) {
695 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
696 add_edge(adr_ptn, ptn);
697 }
698 break;
699 }
700 ELSE_FAIL("Op_StoreP");
701 }
702 case Op_AryEq:
703 case Op_StrComp:
704 case Op_StrEquals:
705 case Op_StrIndexOf:
706 case Op_EncodeISOArray: {
707 // char[] arrays passed to string intrinsic do not escape but
708 // they are not scalar replaceable. Adjust escape state for them.
709 // Start from in(2) edge since in(1) is memory edge.
710 for (uint i = 2; i < n->req(); i++) {
711 Node* adr = n->in(i);
712 const Type* at = _igvn->type(adr);
713 if (!adr->is_top() && at->isa_ptr()) {
714 assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
715 at->isa_ptr() != NULL, "expecting a pointer");
716 if (adr->is_AddP()) {
717 adr = get_addp_base(adr);
718 }
719 PointsToNode* ptn = ptnode_adr(adr->_idx);
720 assert(ptn != NULL, "node should be registered");
721 add_edge(n_ptn, ptn);
722 }
723 }
724 break;
725 }
726 default: {
727 // This method should be called only for EA specific nodes which may
728 // miss some edges when they were created.
729 #ifdef ASSERT
730 n->dump(1);
731 #endif
732 guarantee(false, "unknown node");
733 }
734 }
735 return;
736 }
738 void ConnectionGraph::add_call_node(CallNode* call) {
739 assert(call->returns_pointer(), "only for call which returns pointer");
740 uint call_idx = call->_idx;
741 if (call->is_Allocate()) {
742 Node* k = call->in(AllocateNode::KlassNode);
743 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
744 assert(kt != NULL, "TypeKlassPtr required.");
745 ciKlass* cik = kt->klass();
746 PointsToNode::EscapeState es = PointsToNode::NoEscape;
747 bool scalar_replaceable = true;
748 if (call->is_AllocateArray()) {
749 if (!cik->is_array_klass()) { // StressReflectiveCode
750 es = PointsToNode::GlobalEscape;
751 } else {
752 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
753 if (length < 0 || length > EliminateAllocationArraySizeLimit) {
754 // Not scalar replaceable if the length is not constant or too big.
755 scalar_replaceable = false;
756 }
757 }
758 } else { // Allocate instance
759 if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
760 !cik->is_instance_klass() || // StressReflectiveCode
761 cik->as_instance_klass()->has_finalizer()) {
762 es = PointsToNode::GlobalEscape;
763 }
764 }
765 add_java_object(call, es);
766 PointsToNode* ptn = ptnode_adr(call_idx);
767 if (!scalar_replaceable && ptn->scalar_replaceable()) {
768 ptn->set_scalar_replaceable(false);
769 }
770 } else if (call->is_CallStaticJava()) {
771 // Call nodes could be different types:
772 //
773 // 1. CallDynamicJavaNode (what happened during call is unknown):
774 //
775 // - mapped to GlobalEscape JavaObject node if oop is returned;
776 //
777 // - all oop arguments are escaping globally;
778 //
779 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
780 //
781 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
782 //
783 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
784 // - mapped to NoEscape JavaObject node if non-escaping object allocated
785 // during call is returned;
786 // - mapped to ArgEscape LocalVar node pointed to object arguments
787 // which are returned and does not escape during call;
788 //
789 // - oop arguments escaping status is defined by bytecode analysis;
790 //
791 // For a static call, we know exactly what method is being called.
792 // Use bytecode estimator to record whether the call's return value escapes.
793 ciMethod* meth = call->as_CallJava()->method();
794 if (meth == NULL) {
795 const char* name = call->as_CallStaticJava()->_name;
796 assert(strncmp(name, "_multianewarray", 15) == 0, "TODO: add failed case check");
797 // Returns a newly allocated unescaped object.
798 add_java_object(call, PointsToNode::NoEscape);
799 ptnode_adr(call_idx)->set_scalar_replaceable(false);
800 } else {
801 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
802 call_analyzer->copy_dependencies(_compile->dependencies());
803 if (call_analyzer->is_return_allocated()) {
804 // Returns a newly allocated unescaped object, simply
805 // update dependency information.
806 // Mark it as NoEscape so that objects referenced by
807 // it's fields will be marked as NoEscape at least.
808 add_java_object(call, PointsToNode::NoEscape);
809 ptnode_adr(call_idx)->set_scalar_replaceable(false);
810 } else {
811 // Determine whether any arguments are returned.
812 const TypeTuple* d = call->tf()->domain();
813 bool ret_arg = false;
814 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
815 if (d->field_at(i)->isa_ptr() != NULL &&
816 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
817 ret_arg = true;
818 break;
819 }
820 }
821 if (ret_arg) {
822 add_local_var(call, PointsToNode::ArgEscape);
823 } else {
824 // Returns unknown object.
825 map_ideal_node(call, phantom_obj);
826 }
827 }
828 }
829 } else {
830 // An other type of call, assume the worst case:
831 // returned value is unknown and globally escapes.
832 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
833 map_ideal_node(call, phantom_obj);
834 }
835 }
837 void ConnectionGraph::process_call_arguments(CallNode *call) {
838 bool is_arraycopy = false;
839 switch (call->Opcode()) {
840 #ifdef ASSERT
841 case Op_Allocate:
842 case Op_AllocateArray:
843 case Op_Lock:
844 case Op_Unlock:
845 assert(false, "should be done already");
846 break;
847 #endif
848 case Op_CallLeafNoFP:
849 is_arraycopy = (call->as_CallLeaf()->_name != NULL &&
850 strstr(call->as_CallLeaf()->_name, "arraycopy") != 0);
851 // fall through
852 case Op_CallLeaf: {
853 // Stub calls, objects do not escape but they are not scale replaceable.
854 // Adjust escape state for outgoing arguments.
855 const TypeTuple * d = call->tf()->domain();
856 bool src_has_oops = false;
857 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
858 const Type* at = d->field_at(i);
859 Node *arg = call->in(i);
860 const Type *aat = _igvn->type(arg);
861 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr())
862 continue;
863 if (arg->is_AddP()) {
864 //
865 // The inline_native_clone() case when the arraycopy stub is called
866 // after the allocation before Initialize and CheckCastPP nodes.
867 // Or normal arraycopy for object arrays case.
868 //
869 // Set AddP's base (Allocate) as not scalar replaceable since
870 // pointer to the base (with offset) is passed as argument.
871 //
872 arg = get_addp_base(arg);
873 }
874 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
875 assert(arg_ptn != NULL, "should be registered");
876 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
877 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
878 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
879 aat->isa_ptr() != NULL, "expecting an Ptr");
880 bool arg_has_oops = aat->isa_oopptr() &&
881 (aat->isa_oopptr()->klass() == NULL || aat->isa_instptr() ||
882 (aat->isa_aryptr() && aat->isa_aryptr()->klass()->is_obj_array_klass()));
883 if (i == TypeFunc::Parms) {
884 src_has_oops = arg_has_oops;
885 }
886 //
887 // src or dst could be j.l.Object when other is basic type array:
888 //
889 // arraycopy(char[],0,Object*,0,size);
890 // arraycopy(Object*,0,char[],0,size);
891 //
892 // Don't add edges in such cases.
893 //
894 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
895 arg_has_oops && (i > TypeFunc::Parms);
896 #ifdef ASSERT
897 if (!(is_arraycopy ||
898 (call->as_CallLeaf()->_name != NULL &&
899 (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre") == 0 ||
900 strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ||
901 strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 ||
902 strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 ||
903 strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 ||
904 strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_decryptAESCrypt") == 0)
905 ))) {
906 call->dump();
907 fatal(err_msg_res("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name));
908 }
909 #endif
910 // Always process arraycopy's destination object since
911 // we need to add all possible edges to references in
912 // source object.
913 if (arg_esc >= PointsToNode::ArgEscape &&
914 !arg_is_arraycopy_dest) {
915 continue;
916 }
917 set_escape_state(arg_ptn, PointsToNode::ArgEscape);
918 if (arg_is_arraycopy_dest) {
919 Node* src = call->in(TypeFunc::Parms);
920 if (src->is_AddP()) {
921 src = get_addp_base(src);
922 }
923 PointsToNode* src_ptn = ptnode_adr(src->_idx);
924 assert(src_ptn != NULL, "should be registered");
925 if (arg_ptn != src_ptn) {
926 // Special arraycopy edge:
927 // A destination object's field can't have the source object
928 // as base since objects escape states are not related.
929 // Only escape state of destination object's fields affects
930 // escape state of fields in source object.
931 add_arraycopy(call, PointsToNode::ArgEscape, src_ptn, arg_ptn);
932 }
933 }
934 }
935 }
936 break;
937 }
938 case Op_CallStaticJava: {
939 // For a static call, we know exactly what method is being called.
940 // Use bytecode estimator to record the call's escape affects
941 #ifdef ASSERT
942 const char* name = call->as_CallStaticJava()->_name;
943 assert((name == NULL || strcmp(name, "uncommon_trap") != 0), "normal calls only");
944 #endif
945 ciMethod* meth = call->as_CallJava()->method();
946 BCEscapeAnalyzer* call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
947 // fall-through if not a Java method or no analyzer information
948 if (call_analyzer != NULL) {
949 PointsToNode* call_ptn = ptnode_adr(call->_idx);
950 const TypeTuple* d = call->tf()->domain();
951 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
952 const Type* at = d->field_at(i);
953 int k = i - TypeFunc::Parms;
954 Node* arg = call->in(i);
955 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
956 if (at->isa_ptr() != NULL &&
957 call_analyzer->is_arg_returned(k)) {
958 // The call returns arguments.
959 if (call_ptn != NULL) { // Is call's result used?
960 assert(call_ptn->is_LocalVar(), "node should be registered");
961 assert(arg_ptn != NULL, "node should be registered");
962 add_edge(call_ptn, arg_ptn);
963 }
964 }
965 if (at->isa_oopptr() != NULL &&
966 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
967 if (!call_analyzer->is_arg_stack(k)) {
968 // The argument global escapes
969 set_escape_state(arg_ptn, PointsToNode::GlobalEscape);
970 } else {
971 set_escape_state(arg_ptn, PointsToNode::ArgEscape);
972 if (!call_analyzer->is_arg_local(k)) {
973 // The argument itself doesn't escape, but any fields might
974 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape);
975 }
976 }
977 }
978 }
979 if (call_ptn != NULL && call_ptn->is_LocalVar()) {
980 // The call returns arguments.
981 assert(call_ptn->edge_count() > 0, "sanity");
982 if (!call_analyzer->is_return_local()) {
983 // Returns also unknown object.
984 add_edge(call_ptn, phantom_obj);
985 }
986 }
987 break;
988 }
989 }
990 default: {
991 // Fall-through here if not a Java method or no analyzer information
992 // or some other type of call, assume the worst case: all arguments
993 // globally escape.
994 const TypeTuple* d = call->tf()->domain();
995 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
996 const Type* at = d->field_at(i);
997 if (at->isa_oopptr() != NULL) {
998 Node* arg = call->in(i);
999 if (arg->is_AddP()) {
1000 arg = get_addp_base(arg);
1001 }
1002 assert(ptnode_adr(arg->_idx) != NULL, "should be defined already");
1003 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape);
1004 }
1005 }
1006 }
1007 }
1008 }
1011 // Finish Graph construction.
1012 bool ConnectionGraph::complete_connection_graph(
1013 GrowableArray<PointsToNode*>& ptnodes_worklist,
1014 GrowableArray<JavaObjectNode*>& non_escaped_worklist,
1015 GrowableArray<JavaObjectNode*>& java_objects_worklist,
1016 GrowableArray<FieldNode*>& oop_fields_worklist) {
1017 // Normally only 1-3 passes needed to build Connection Graph depending
1018 // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
1019 // Set limit to 20 to catch situation when something did go wrong and
1020 // bailout Escape Analysis.
1021 // Also limit build time to 30 sec (60 in debug VM).
1022 #define CG_BUILD_ITER_LIMIT 20
1023 #ifdef ASSERT
1024 #define CG_BUILD_TIME_LIMIT 60.0
1025 #else
1026 #define CG_BUILD_TIME_LIMIT 30.0
1027 #endif
1029 // Propagate GlobalEscape and ArgEscape escape states and check that
1030 // we still have non-escaping objects. The method pushs on _worklist
1031 // Field nodes which reference phantom_object.
1032 if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
1033 return false; // Nothing to do.
1034 }
1035 // Now propagate references to all JavaObject nodes.
1036 int java_objects_length = java_objects_worklist.length();
1037 elapsedTimer time;
1038 int new_edges = 1;
1039 int iterations = 0;
1040 do {
1041 while ((new_edges > 0) &&
1042 (iterations++ < CG_BUILD_ITER_LIMIT) &&
1043 (time.seconds() < CG_BUILD_TIME_LIMIT)) {
1044 time.start();
1045 new_edges = 0;
1046 // Propagate references to phantom_object for nodes pushed on _worklist
1047 // by find_non_escaped_objects() and find_field_value().
1048 new_edges += add_java_object_edges(phantom_obj, false);
1049 for (int next = 0; next < java_objects_length; ++next) {
1050 JavaObjectNode* ptn = java_objects_worklist.at(next);
1051 new_edges += add_java_object_edges(ptn, true);
1052 }
1053 if (new_edges > 0) {
1054 // Update escape states on each iteration if graph was updated.
1055 if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
1056 return false; // Nothing to do.
1057 }
1058 }
1059 time.stop();
1060 }
1061 if ((iterations < CG_BUILD_ITER_LIMIT) &&
1062 (time.seconds() < CG_BUILD_TIME_LIMIT)) {
1063 time.start();
1064 // Find fields which have unknown value.
1065 int fields_length = oop_fields_worklist.length();
1066 for (int next = 0; next < fields_length; next++) {
1067 FieldNode* field = oop_fields_worklist.at(next);
1068 if (field->edge_count() == 0) {
1069 new_edges += find_field_value(field);
1070 // This code may added new edges to phantom_object.
1071 // Need an other cycle to propagate references to phantom_object.
1072 }
1073 }
1074 time.stop();
1075 } else {
1076 new_edges = 0; // Bailout
1077 }
1078 } while (new_edges > 0);
1080 // Bailout if passed limits.
1081 if ((iterations >= CG_BUILD_ITER_LIMIT) ||
1082 (time.seconds() >= CG_BUILD_TIME_LIMIT)) {
1083 Compile* C = _compile;
1084 if (C->log() != NULL) {
1085 C->log()->begin_elem("connectionGraph_bailout reason='reached ");
1086 C->log()->text("%s", (iterations >= CG_BUILD_ITER_LIMIT) ? "iterations" : "time");
1087 C->log()->end_elem(" limit'");
1088 }
1089 assert(ExitEscapeAnalysisOnTimeout, err_msg_res("infinite EA connection graph build (%f sec, %d iterations) with %d nodes and worklist size %d",
1090 time.seconds(), iterations, nodes_size(), ptnodes_worklist.length()));
1091 // Possible infinite build_connection_graph loop,
1092 // bailout (no changes to ideal graph were made).
1093 return false;
1094 }
1095 #ifdef ASSERT
1096 if (Verbose && PrintEscapeAnalysis) {
1097 tty->print_cr("EA: %d iterations to build connection graph with %d nodes and worklist size %d",
1098 iterations, nodes_size(), ptnodes_worklist.length());
1099 }
1100 #endif
1102 #undef CG_BUILD_ITER_LIMIT
1103 #undef CG_BUILD_TIME_LIMIT
1105 // Find fields initialized by NULL for non-escaping Allocations.
1106 int non_escaped_length = non_escaped_worklist.length();
1107 for (int next = 0; next < non_escaped_length; next++) {
1108 JavaObjectNode* ptn = non_escaped_worklist.at(next);
1109 PointsToNode::EscapeState es = ptn->escape_state();
1110 assert(es <= PointsToNode::ArgEscape, "sanity");
1111 if (es == PointsToNode::NoEscape) {
1112 if (find_init_values(ptn, null_obj, _igvn) > 0) {
1113 // Adding references to NULL object does not change escape states
1114 // since it does not escape. Also no fields are added to NULL object.
1115 add_java_object_edges(null_obj, false);
1116 }
1117 }
1118 Node* n = ptn->ideal_node();
1119 if (n->is_Allocate()) {
1120 // The object allocated by this Allocate node will never be
1121 // seen by an other thread. Mark it so that when it is
1122 // expanded no MemBarStoreStore is added.
1123 InitializeNode* ini = n->as_Allocate()->initialization();
1124 if (ini != NULL)
1125 ini->set_does_not_escape();
1126 }
1127 }
1128 return true; // Finished graph construction.
1129 }
1131 // Propagate GlobalEscape and ArgEscape escape states to all nodes
1132 // and check that we still have non-escaping java objects.
1133 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
1134 GrowableArray<JavaObjectNode*>& non_escaped_worklist) {
1135 GrowableArray<PointsToNode*> escape_worklist;
1136 // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
1137 int ptnodes_length = ptnodes_worklist.length();
1138 for (int next = 0; next < ptnodes_length; ++next) {
1139 PointsToNode* ptn = ptnodes_worklist.at(next);
1140 if (ptn->escape_state() >= PointsToNode::ArgEscape ||
1141 ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
1142 escape_worklist.push(ptn);
1143 }
1144 }
1145 // Set escape states to referenced nodes (edges list).
1146 while (escape_worklist.length() > 0) {
1147 PointsToNode* ptn = escape_worklist.pop();
1148 PointsToNode::EscapeState es = ptn->escape_state();
1149 PointsToNode::EscapeState field_es = ptn->fields_escape_state();
1150 if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
1151 es >= PointsToNode::ArgEscape) {
1152 // GlobalEscape or ArgEscape state of field means it has unknown value.
1153 if (add_edge(ptn, phantom_obj)) {
1154 // New edge was added
1155 add_field_uses_to_worklist(ptn->as_Field());
1156 }
1157 }
1158 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1159 PointsToNode* e = i.get();
1160 if (e->is_Arraycopy()) {
1161 assert(ptn->arraycopy_dst(), "sanity");
1162 // Propagate only fields escape state through arraycopy edge.
1163 if (e->fields_escape_state() < field_es) {
1164 set_fields_escape_state(e, field_es);
1165 escape_worklist.push(e);
1166 }
1167 } else if (es >= field_es) {
1168 // fields_escape_state is also set to 'es' if it is less than 'es'.
1169 if (e->escape_state() < es) {
1170 set_escape_state(e, es);
1171 escape_worklist.push(e);
1172 }
1173 } else {
1174 // Propagate field escape state.
1175 bool es_changed = false;
1176 if (e->fields_escape_state() < field_es) {
1177 set_fields_escape_state(e, field_es);
1178 es_changed = true;
1179 }
1180 if ((e->escape_state() < field_es) &&
1181 e->is_Field() && ptn->is_JavaObject() &&
1182 e->as_Field()->is_oop()) {
1183 // Change escape state of referenced fileds.
1184 set_escape_state(e, field_es);
1185 es_changed = true;;
1186 } else if (e->escape_state() < es) {
1187 set_escape_state(e, es);
1188 es_changed = true;;
1189 }
1190 if (es_changed) {
1191 escape_worklist.push(e);
1192 }
1193 }
1194 }
1195 }
1196 // Remove escaped objects from non_escaped list.
1197 for (int next = non_escaped_worklist.length()-1; next >= 0 ; --next) {
1198 JavaObjectNode* ptn = non_escaped_worklist.at(next);
1199 if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
1200 non_escaped_worklist.delete_at(next);
1201 }
1202 if (ptn->escape_state() == PointsToNode::NoEscape) {
1203 // Find fields in non-escaped allocations which have unknown value.
1204 find_init_values(ptn, phantom_obj, NULL);
1205 }
1206 }
1207 return (non_escaped_worklist.length() > 0);
1208 }
1210 // Add all references to JavaObject node by walking over all uses.
1211 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
1212 int new_edges = 0;
1213 if (populate_worklist) {
1214 // Populate _worklist by uses of jobj's uses.
1215 for (UseIterator i(jobj); i.has_next(); i.next()) {
1216 PointsToNode* use = i.get();
1217 if (use->is_Arraycopy())
1218 continue;
1219 add_uses_to_worklist(use);
1220 if (use->is_Field() && use->as_Field()->is_oop()) {
1221 // Put on worklist all field's uses (loads) and
1222 // related field nodes (same base and offset).
1223 add_field_uses_to_worklist(use->as_Field());
1224 }
1225 }
1226 }
1227 while(_worklist.length() > 0) {
1228 PointsToNode* use = _worklist.pop();
1229 if (PointsToNode::is_base_use(use)) {
1230 // Add reference from jobj to field and from field to jobj (field's base).
1231 use = PointsToNode::get_use_node(use)->as_Field();
1232 if (add_base(use->as_Field(), jobj)) {
1233 new_edges++;
1234 }
1235 continue;
1236 }
1237 assert(!use->is_JavaObject(), "sanity");
1238 if (use->is_Arraycopy()) {
1239 if (jobj == null_obj) // NULL object does not have field edges
1240 continue;
1241 // Added edge from Arraycopy node to arraycopy's source java object
1242 if (add_edge(use, jobj)) {
1243 jobj->set_arraycopy_src();
1244 new_edges++;
1245 }
1246 // and stop here.
1247 continue;
1248 }
1249 if (!add_edge(use, jobj))
1250 continue; // No new edge added, there was such edge already.
1251 new_edges++;
1252 if (use->is_LocalVar()) {
1253 add_uses_to_worklist(use);
1254 if (use->arraycopy_dst()) {
1255 for (EdgeIterator i(use); i.has_next(); i.next()) {
1256 PointsToNode* e = i.get();
1257 if (e->is_Arraycopy()) {
1258 if (jobj == null_obj) // NULL object does not have field edges
1259 continue;
1260 // Add edge from arraycopy's destination java object to Arraycopy node.
1261 if (add_edge(jobj, e)) {
1262 new_edges++;
1263 jobj->set_arraycopy_dst();
1264 }
1265 }
1266 }
1267 }
1268 } else {
1269 // Added new edge to stored in field values.
1270 // Put on worklist all field's uses (loads) and
1271 // related field nodes (same base and offset).
1272 add_field_uses_to_worklist(use->as_Field());
1273 }
1274 }
1275 return new_edges;
1276 }
1278 // Put on worklist all related field nodes.
1279 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
1280 assert(field->is_oop(), "sanity");
1281 int offset = field->offset();
1282 add_uses_to_worklist(field);
1283 // Loop over all bases of this field and push on worklist Field nodes
1284 // with the same offset and base (since they may reference the same field).
1285 for (BaseIterator i(field); i.has_next(); i.next()) {
1286 PointsToNode* base = i.get();
1287 add_fields_to_worklist(field, base);
1288 // Check if the base was source object of arraycopy and go over arraycopy's
1289 // destination objects since values stored to a field of source object are
1290 // accessable by uses (loads) of fields of destination objects.
1291 if (base->arraycopy_src()) {
1292 for (UseIterator j(base); j.has_next(); j.next()) {
1293 PointsToNode* arycp = j.get();
1294 if (arycp->is_Arraycopy()) {
1295 for (UseIterator k(arycp); k.has_next(); k.next()) {
1296 PointsToNode* abase = k.get();
1297 if (abase->arraycopy_dst() && abase != base) {
1298 // Look for the same arracopy reference.
1299 add_fields_to_worklist(field, abase);
1300 }
1301 }
1302 }
1303 }
1304 }
1305 }
1306 }
1308 // Put on worklist all related field nodes.
1309 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
1310 int offset = field->offset();
1311 if (base->is_LocalVar()) {
1312 for (UseIterator j(base); j.has_next(); j.next()) {
1313 PointsToNode* f = j.get();
1314 if (PointsToNode::is_base_use(f)) { // Field
1315 f = PointsToNode::get_use_node(f);
1316 if (f == field || !f->as_Field()->is_oop())
1317 continue;
1318 int offs = f->as_Field()->offset();
1319 if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1320 add_to_worklist(f);
1321 }
1322 }
1323 }
1324 } else {
1325 assert(base->is_JavaObject(), "sanity");
1326 if (// Skip phantom_object since it is only used to indicate that
1327 // this field's content globally escapes.
1328 (base != phantom_obj) &&
1329 // NULL object node does not have fields.
1330 (base != null_obj)) {
1331 for (EdgeIterator i(base); i.has_next(); i.next()) {
1332 PointsToNode* f = i.get();
1333 // Skip arraycopy edge since store to destination object field
1334 // does not update value in source object field.
1335 if (f->is_Arraycopy()) {
1336 assert(base->arraycopy_dst(), "sanity");
1337 continue;
1338 }
1339 if (f == field || !f->as_Field()->is_oop())
1340 continue;
1341 int offs = f->as_Field()->offset();
1342 if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1343 add_to_worklist(f);
1344 }
1345 }
1346 }
1347 }
1348 }
1350 // Find fields which have unknown value.
1351 int ConnectionGraph::find_field_value(FieldNode* field) {
1352 // Escaped fields should have init value already.
1353 assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
1354 int new_edges = 0;
1355 for (BaseIterator i(field); i.has_next(); i.next()) {
1356 PointsToNode* base = i.get();
1357 if (base->is_JavaObject()) {
1358 // Skip Allocate's fields which will be processed later.
1359 if (base->ideal_node()->is_Allocate())
1360 return 0;
1361 assert(base == null_obj, "only NULL ptr base expected here");
1362 }
1363 }
1364 if (add_edge(field, phantom_obj)) {
1365 // New edge was added
1366 new_edges++;
1367 add_field_uses_to_worklist(field);
1368 }
1369 return new_edges;
1370 }
1372 // Find fields initializing values for allocations.
1373 int ConnectionGraph::find_init_values(JavaObjectNode* pta, PointsToNode* init_val, PhaseTransform* phase) {
1374 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
1375 int new_edges = 0;
1376 Node* alloc = pta->ideal_node();
1377 if (init_val == phantom_obj) {
1378 // Do nothing for Allocate nodes since its fields values are "known".
1379 if (alloc->is_Allocate())
1380 return 0;
1381 assert(alloc->as_CallStaticJava(), "sanity");
1382 #ifdef ASSERT
1383 if (alloc->as_CallStaticJava()->method() == NULL) {
1384 const char* name = alloc->as_CallStaticJava()->_name;
1385 assert(strncmp(name, "_multianewarray", 15) == 0, "sanity");
1386 }
1387 #endif
1388 // Non-escaped allocation returned from Java or runtime call have
1389 // unknown values in fields.
1390 for (EdgeIterator i(pta); i.has_next(); i.next()) {
1391 PointsToNode* field = i.get();
1392 if (field->is_Field() && field->as_Field()->is_oop()) {
1393 if (add_edge(field, phantom_obj)) {
1394 // New edge was added
1395 new_edges++;
1396 add_field_uses_to_worklist(field->as_Field());
1397 }
1398 }
1399 }
1400 return new_edges;
1401 }
1402 assert(init_val == null_obj, "sanity");
1403 // Do nothing for Call nodes since its fields values are unknown.
1404 if (!alloc->is_Allocate())
1405 return 0;
1407 InitializeNode* ini = alloc->as_Allocate()->initialization();
1408 Compile* C = _compile;
1409 bool visited_bottom_offset = false;
1410 GrowableArray<int> offsets_worklist;
1412 // Check if an oop field's initializing value is recorded and add
1413 // a corresponding NULL if field's value if it is not recorded.
1414 // Connection Graph does not record a default initialization by NULL
1415 // captured by Initialize node.
1416 //
1417 for (EdgeIterator i(pta); i.has_next(); i.next()) {
1418 PointsToNode* field = i.get(); // Field (AddP)
1419 if (!field->is_Field() || !field->as_Field()->is_oop())
1420 continue; // Not oop field
1421 int offset = field->as_Field()->offset();
1422 if (offset == Type::OffsetBot) {
1423 if (!visited_bottom_offset) {
1424 // OffsetBot is used to reference array's element,
1425 // always add reference to NULL to all Field nodes since we don't
1426 // known which element is referenced.
1427 if (add_edge(field, null_obj)) {
1428 // New edge was added
1429 new_edges++;
1430 add_field_uses_to_worklist(field->as_Field());
1431 visited_bottom_offset = true;
1432 }
1433 }
1434 } else {
1435 // Check only oop fields.
1436 const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type();
1437 if (adr_type->isa_rawptr()) {
1438 #ifdef ASSERT
1439 // Raw pointers are used for initializing stores so skip it
1440 // since it should be recorded already
1441 Node* base = get_addp_base(field->ideal_node());
1442 assert(adr_type->isa_rawptr() && base->is_Proj() &&
1443 (base->in(0) == alloc),"unexpected pointer type");
1444 #endif
1445 continue;
1446 }
1447 if (!offsets_worklist.contains(offset)) {
1448 offsets_worklist.append(offset);
1449 Node* value = NULL;
1450 if (ini != NULL) {
1451 // StoreP::memory_type() == T_ADDRESS
1452 BasicType ft = UseCompressedOops ? T_NARROWOOP : T_ADDRESS;
1453 Node* store = ini->find_captured_store(offset, type2aelembytes(ft, true), phase);
1454 // Make sure initializing store has the same type as this AddP.
1455 // This AddP may reference non existing field because it is on a
1456 // dead branch of bimorphic call which is not eliminated yet.
1457 if (store != NULL && store->is_Store() &&
1458 store->as_Store()->memory_type() == ft) {
1459 value = store->in(MemNode::ValueIn);
1460 #ifdef ASSERT
1461 if (VerifyConnectionGraph) {
1462 // Verify that AddP already points to all objects the value points to.
1463 PointsToNode* val = ptnode_adr(value->_idx);
1464 assert((val != NULL), "should be processed already");
1465 PointsToNode* missed_obj = NULL;
1466 if (val->is_JavaObject()) {
1467 if (!field->points_to(val->as_JavaObject())) {
1468 missed_obj = val;
1469 }
1470 } else {
1471 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
1472 tty->print_cr("----------init store has invalid value -----");
1473 store->dump();
1474 val->dump();
1475 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
1476 }
1477 for (EdgeIterator j(val); j.has_next(); j.next()) {
1478 PointsToNode* obj = j.get();
1479 if (obj->is_JavaObject()) {
1480 if (!field->points_to(obj->as_JavaObject())) {
1481 missed_obj = obj;
1482 break;
1483 }
1484 }
1485 }
1486 }
1487 if (missed_obj != NULL) {
1488 tty->print_cr("----------field---------------------------------");
1489 field->dump();
1490 tty->print_cr("----------missed referernce to object-----------");
1491 missed_obj->dump();
1492 tty->print_cr("----------object referernced by init store -----");
1493 store->dump();
1494 val->dump();
1495 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
1496 }
1497 }
1498 #endif
1499 } else {
1500 // There could be initializing stores which follow allocation.
1501 // For example, a volatile field store is not collected
1502 // by Initialize node.
1503 //
1504 // Need to check for dependent loads to separate such stores from
1505 // stores which follow loads. For now, add initial value NULL so
1506 // that compare pointers optimization works correctly.
1507 }
1508 }
1509 if (value == NULL) {
1510 // A field's initializing value was not recorded. Add NULL.
1511 if (add_edge(field, null_obj)) {
1512 // New edge was added
1513 new_edges++;
1514 add_field_uses_to_worklist(field->as_Field());
1515 }
1516 }
1517 }
1518 }
1519 }
1520 return new_edges;
1521 }
1523 // Adjust scalar_replaceable state after Connection Graph is built.
1524 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj) {
1525 // Search for non-escaping objects which are not scalar replaceable
1526 // and mark them to propagate the state to referenced objects.
1528 // 1. An object is not scalar replaceable if the field into which it is
1529 // stored has unknown offset (stored into unknown element of an array).
1530 //
1531 for (UseIterator i(jobj); i.has_next(); i.next()) {
1532 PointsToNode* use = i.get();
1533 assert(!use->is_Arraycopy(), "sanity");
1534 if (use->is_Field()) {
1535 FieldNode* field = use->as_Field();
1536 assert(field->is_oop() && field->scalar_replaceable() &&
1537 field->fields_escape_state() == PointsToNode::NoEscape, "sanity");
1538 if (field->offset() == Type::OffsetBot) {
1539 jobj->set_scalar_replaceable(false);
1540 return;
1541 }
1542 }
1543 assert(use->is_Field() || use->is_LocalVar(), "sanity");
1544 // 2. An object is not scalar replaceable if it is merged with other objects.
1545 for (EdgeIterator j(use); j.has_next(); j.next()) {
1546 PointsToNode* ptn = j.get();
1547 if (ptn->is_JavaObject() && ptn != jobj) {
1548 // Mark all objects.
1549 jobj->set_scalar_replaceable(false);
1550 ptn->set_scalar_replaceable(false);
1551 }
1552 }
1553 if (!jobj->scalar_replaceable()) {
1554 return;
1555 }
1556 }
1558 for (EdgeIterator j(jobj); j.has_next(); j.next()) {
1559 // Non-escaping object node should point only to field nodes.
1560 FieldNode* field = j.get()->as_Field();
1561 int offset = field->as_Field()->offset();
1563 // 3. An object is not scalar replaceable if it has a field with unknown
1564 // offset (array's element is accessed in loop).
1565 if (offset == Type::OffsetBot) {
1566 jobj->set_scalar_replaceable(false);
1567 return;
1568 }
1569 // 4. Currently an object is not scalar replaceable if a LoadStore node
1570 // access its field since the field value is unknown after it.
1571 //
1572 Node* n = field->ideal_node();
1573 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1574 if (n->fast_out(i)->is_LoadStore()) {
1575 jobj->set_scalar_replaceable(false);
1576 return;
1577 }
1578 }
1580 // 5. Or the address may point to more then one object. This may produce
1581 // the false positive result (set not scalar replaceable)
1582 // since the flow-insensitive escape analysis can't separate
1583 // the case when stores overwrite the field's value from the case
1584 // when stores happened on different control branches.
1585 //
1586 // Note: it will disable scalar replacement in some cases:
1587 //
1588 // Point p[] = new Point[1];
1589 // p[0] = new Point(); // Will be not scalar replaced
1590 //
1591 // but it will save us from incorrect optimizations in next cases:
1592 //
1593 // Point p[] = new Point[1];
1594 // if ( x ) p[0] = new Point(); // Will be not scalar replaced
1595 //
1596 if (field->base_count() > 1) {
1597 for (BaseIterator i(field); i.has_next(); i.next()) {
1598 PointsToNode* base = i.get();
1599 // Don't take into account LocalVar nodes which
1600 // may point to only one object which should be also
1601 // this field's base by now.
1602 if (base->is_JavaObject() && base != jobj) {
1603 // Mark all bases.
1604 jobj->set_scalar_replaceable(false);
1605 base->set_scalar_replaceable(false);
1606 }
1607 }
1608 }
1609 }
1610 }
1612 #ifdef ASSERT
1613 void ConnectionGraph::verify_connection_graph(
1614 GrowableArray<PointsToNode*>& ptnodes_worklist,
1615 GrowableArray<JavaObjectNode*>& non_escaped_worklist,
1616 GrowableArray<JavaObjectNode*>& java_objects_worklist,
1617 GrowableArray<Node*>& addp_worklist) {
1618 // Verify that graph is complete - no new edges could be added.
1619 int java_objects_length = java_objects_worklist.length();
1620 int non_escaped_length = non_escaped_worklist.length();
1621 int new_edges = 0;
1622 for (int next = 0; next < java_objects_length; ++next) {
1623 JavaObjectNode* ptn = java_objects_worklist.at(next);
1624 new_edges += add_java_object_edges(ptn, true);
1625 }
1626 assert(new_edges == 0, "graph was not complete");
1627 // Verify that escape state is final.
1628 int length = non_escaped_worklist.length();
1629 find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist);
1630 assert((non_escaped_length == non_escaped_worklist.length()) &&
1631 (non_escaped_length == length) &&
1632 (_worklist.length() == 0), "escape state was not final");
1634 // Verify fields information.
1635 int addp_length = addp_worklist.length();
1636 for (int next = 0; next < addp_length; ++next ) {
1637 Node* n = addp_worklist.at(next);
1638 FieldNode* field = ptnode_adr(n->_idx)->as_Field();
1639 if (field->is_oop()) {
1640 // Verify that field has all bases
1641 Node* base = get_addp_base(n);
1642 PointsToNode* ptn = ptnode_adr(base->_idx);
1643 if (ptn->is_JavaObject()) {
1644 assert(field->has_base(ptn->as_JavaObject()), "sanity");
1645 } else {
1646 assert(ptn->is_LocalVar(), "sanity");
1647 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1648 PointsToNode* e = i.get();
1649 if (e->is_JavaObject()) {
1650 assert(field->has_base(e->as_JavaObject()), "sanity");
1651 }
1652 }
1653 }
1654 // Verify that all fields have initializing values.
1655 if (field->edge_count() == 0) {
1656 tty->print_cr("----------field does not have references----------");
1657 field->dump();
1658 for (BaseIterator i(field); i.has_next(); i.next()) {
1659 PointsToNode* base = i.get();
1660 tty->print_cr("----------field has next base---------------------");
1661 base->dump();
1662 if (base->is_JavaObject() && (base != phantom_obj) && (base != null_obj)) {
1663 tty->print_cr("----------base has fields-------------------------");
1664 for (EdgeIterator j(base); j.has_next(); j.next()) {
1665 j.get()->dump();
1666 }
1667 tty->print_cr("----------base has references---------------------");
1668 for (UseIterator j(base); j.has_next(); j.next()) {
1669 j.get()->dump();
1670 }
1671 }
1672 }
1673 for (UseIterator i(field); i.has_next(); i.next()) {
1674 i.get()->dump();
1675 }
1676 assert(field->edge_count() > 0, "sanity");
1677 }
1678 }
1679 }
1680 }
1681 #endif
1683 // Optimize ideal graph.
1684 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
1685 GrowableArray<Node*>& storestore_worklist) {
1686 Compile* C = _compile;
1687 PhaseIterGVN* igvn = _igvn;
1688 if (EliminateLocks) {
1689 // Mark locks before changing ideal graph.
1690 int cnt = C->macro_count();
1691 for( int i=0; i < cnt; i++ ) {
1692 Node *n = C->macro_node(i);
1693 if (n->is_AbstractLock()) { // Lock and Unlock nodes
1694 AbstractLockNode* alock = n->as_AbstractLock();
1695 if (!alock->is_non_esc_obj()) {
1696 if (not_global_escape(alock->obj_node())) {
1697 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
1698 // The lock could be marked eliminated by lock coarsening
1699 // code during first IGVN before EA. Replace coarsened flag
1700 // to eliminate all associated locks/unlocks.
1701 alock->set_non_esc_obj();
1702 }
1703 }
1704 }
1705 }
1706 }
1708 if (OptimizePtrCompare) {
1709 // Add ConI(#CC_GT) and ConI(#CC_EQ).
1710 _pcmp_neq = igvn->makecon(TypeInt::CC_GT);
1711 _pcmp_eq = igvn->makecon(TypeInt::CC_EQ);
1712 // Optimize objects compare.
1713 while (ptr_cmp_worklist.length() != 0) {
1714 Node *n = ptr_cmp_worklist.pop();
1715 Node *res = optimize_ptr_compare(n);
1716 if (res != NULL) {
1717 #ifndef PRODUCT
1718 if (PrintOptimizePtrCompare) {
1719 tty->print_cr("++++ Replaced: %d %s(%d,%d) --> %s", n->_idx, (n->Opcode() == Op_CmpP ? "CmpP" : "CmpN"), n->in(1)->_idx, n->in(2)->_idx, (res == _pcmp_eq ? "EQ" : "NotEQ"));
1720 if (Verbose) {
1721 n->dump(1);
1722 }
1723 }
1724 #endif
1725 igvn->replace_node(n, res);
1726 }
1727 }
1728 // cleanup
1729 if (_pcmp_neq->outcnt() == 0)
1730 igvn->hash_delete(_pcmp_neq);
1731 if (_pcmp_eq->outcnt() == 0)
1732 igvn->hash_delete(_pcmp_eq);
1733 }
1735 // For MemBarStoreStore nodes added in library_call.cpp, check
1736 // escape status of associated AllocateNode and optimize out
1737 // MemBarStoreStore node if the allocated object never escapes.
1738 while (storestore_worklist.length() != 0) {
1739 Node *n = storestore_worklist.pop();
1740 MemBarStoreStoreNode *storestore = n ->as_MemBarStoreStore();
1741 Node *alloc = storestore->in(MemBarNode::Precedent)->in(0);
1742 assert (alloc->is_Allocate(), "storestore should point to AllocateNode");
1743 if (not_global_escape(alloc)) {
1744 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
1745 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
1746 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
1747 igvn->register_new_node_with_optimizer(mb);
1748 igvn->replace_node(storestore, mb);
1749 }
1750 }
1751 }
1753 // Optimize objects compare.
1754 Node* ConnectionGraph::optimize_ptr_compare(Node* n) {
1755 assert(OptimizePtrCompare, "sanity");
1756 PointsToNode* ptn1 = ptnode_adr(n->in(1)->_idx);
1757 PointsToNode* ptn2 = ptnode_adr(n->in(2)->_idx);
1758 JavaObjectNode* jobj1 = unique_java_object(n->in(1));
1759 JavaObjectNode* jobj2 = unique_java_object(n->in(2));
1760 assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
1761 assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
1763 // Check simple cases first.
1764 if (jobj1 != NULL) {
1765 if (jobj1->escape_state() == PointsToNode::NoEscape) {
1766 if (jobj1 == jobj2) {
1767 // Comparing the same not escaping object.
1768 return _pcmp_eq;
1769 }
1770 Node* obj = jobj1->ideal_node();
1771 // Comparing not escaping allocation.
1772 if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
1773 !ptn2->points_to(jobj1)) {
1774 return _pcmp_neq; // This includes nullness check.
1775 }
1776 }
1777 }
1778 if (jobj2 != NULL) {
1779 if (jobj2->escape_state() == PointsToNode::NoEscape) {
1780 Node* obj = jobj2->ideal_node();
1781 // Comparing not escaping allocation.
1782 if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
1783 !ptn1->points_to(jobj2)) {
1784 return _pcmp_neq; // This includes nullness check.
1785 }
1786 }
1787 }
1788 if (jobj1 != NULL && jobj1 != phantom_obj &&
1789 jobj2 != NULL && jobj2 != phantom_obj &&
1790 jobj1->ideal_node()->is_Con() &&
1791 jobj2->ideal_node()->is_Con()) {
1792 // Klass or String constants compare. Need to be careful with
1793 // compressed pointers - compare types of ConN and ConP instead of nodes.
1794 const Type* t1 = jobj1->ideal_node()->bottom_type()->make_ptr();
1795 const Type* t2 = jobj2->ideal_node()->bottom_type()->make_ptr();
1796 assert(t1 != NULL && t2 != NULL, "sanity");
1797 if (t1->make_ptr() == t2->make_ptr()) {
1798 return _pcmp_eq;
1799 } else {
1800 return _pcmp_neq;
1801 }
1802 }
1803 if (ptn1->meet(ptn2)) {
1804 return NULL; // Sets are not disjoint
1805 }
1807 // Sets are disjoint.
1808 bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
1809 bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
1810 bool set1_has_null_ptr = ptn1->points_to(null_obj);
1811 bool set2_has_null_ptr = ptn2->points_to(null_obj);
1812 if (set1_has_unknown_ptr && set2_has_null_ptr ||
1813 set2_has_unknown_ptr && set1_has_null_ptr) {
1814 // Check nullness of unknown object.
1815 return NULL;
1816 }
1818 // Disjointness by itself is not sufficient since
1819 // alias analysis is not complete for escaped objects.
1820 // Disjoint sets are definitely unrelated only when
1821 // at least one set has only not escaping allocations.
1822 if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
1823 if (ptn1->non_escaping_allocation()) {
1824 return _pcmp_neq;
1825 }
1826 }
1827 if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
1828 if (ptn2->non_escaping_allocation()) {
1829 return _pcmp_neq;
1830 }
1831 }
1832 return NULL;
1833 }
1835 // Connection Graph constuction functions.
1837 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
1838 PointsToNode* ptadr = _nodes.at(n->_idx);
1839 if (ptadr != NULL) {
1840 assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
1841 return;
1842 }
1843 Compile* C = _compile;
1844 ptadr = new (C->comp_arena()) LocalVarNode(C, n, es);
1845 _nodes.at_put(n->_idx, ptadr);
1846 }
1848 void ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
1849 PointsToNode* ptadr = _nodes.at(n->_idx);
1850 if (ptadr != NULL) {
1851 assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
1852 return;
1853 }
1854 Compile* C = _compile;
1855 ptadr = new (C->comp_arena()) JavaObjectNode(C, n, es);
1856 _nodes.at_put(n->_idx, ptadr);
1857 }
1859 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
1860 PointsToNode* ptadr = _nodes.at(n->_idx);
1861 if (ptadr != NULL) {
1862 assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
1863 return;
1864 }
1865 bool unsafe = false;
1866 bool is_oop = is_oop_field(n, offset, &unsafe);
1867 if (unsafe) {
1868 es = PointsToNode::GlobalEscape;
1869 }
1870 Compile* C = _compile;
1871 FieldNode* field = new (C->comp_arena()) FieldNode(C, n, es, offset, is_oop);
1872 _nodes.at_put(n->_idx, field);
1873 }
1875 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
1876 PointsToNode* src, PointsToNode* dst) {
1877 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
1878 assert((src != null_obj) && (dst != null_obj), "not for ConP NULL");
1879 PointsToNode* ptadr = _nodes.at(n->_idx);
1880 if (ptadr != NULL) {
1881 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
1882 return;
1883 }
1884 Compile* C = _compile;
1885 ptadr = new (C->comp_arena()) ArraycopyNode(C, n, es);
1886 _nodes.at_put(n->_idx, ptadr);
1887 // Add edge from arraycopy node to source object.
1888 (void)add_edge(ptadr, src);
1889 src->set_arraycopy_src();
1890 // Add edge from destination object to arraycopy node.
1891 (void)add_edge(dst, ptadr);
1892 dst->set_arraycopy_dst();
1893 }
1895 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
1896 const Type* adr_type = n->as_AddP()->bottom_type();
1897 BasicType bt = T_INT;
1898 if (offset == Type::OffsetBot) {
1899 // Check only oop fields.
1900 if (!adr_type->isa_aryptr() ||
1901 (adr_type->isa_aryptr()->klass() == NULL) ||
1902 adr_type->isa_aryptr()->klass()->is_obj_array_klass()) {
1903 // OffsetBot is used to reference array's element. Ignore first AddP.
1904 if (find_second_addp(n, n->in(AddPNode::Base)) == NULL) {
1905 bt = T_OBJECT;
1906 }
1907 }
1908 } else if (offset != oopDesc::klass_offset_in_bytes()) {
1909 if (adr_type->isa_instptr()) {
1910 ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
1911 if (field != NULL) {
1912 bt = field->layout_type();
1913 } else {
1914 // Check for unsafe oop field access
1915 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1916 int opcode = n->fast_out(i)->Opcode();
1917 if (opcode == Op_StoreP || opcode == Op_LoadP ||
1918 opcode == Op_StoreN || opcode == Op_LoadN) {
1919 bt = T_OBJECT;
1920 (*unsafe) = true;
1921 break;
1922 }
1923 }
1924 }
1925 } else if (adr_type->isa_aryptr()) {
1926 if (offset == arrayOopDesc::length_offset_in_bytes()) {
1927 // Ignore array length load.
1928 } else if (find_second_addp(n, n->in(AddPNode::Base)) != NULL) {
1929 // Ignore first AddP.
1930 } else {
1931 const Type* elemtype = adr_type->isa_aryptr()->elem();
1932 bt = elemtype->array_element_basic_type();
1933 }
1934 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
1935 // Allocation initialization, ThreadLocal field access, unsafe access
1936 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1937 int opcode = n->fast_out(i)->Opcode();
1938 if (opcode == Op_StoreP || opcode == Op_LoadP ||
1939 opcode == Op_StoreN || opcode == Op_LoadN) {
1940 bt = T_OBJECT;
1941 break;
1942 }
1943 }
1944 }
1945 }
1946 return (bt == T_OBJECT || bt == T_NARROWOOP || bt == T_ARRAY);
1947 }
1949 // Returns unique pointed java object or NULL.
1950 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) {
1951 assert(!_collecting, "should not call when contructed graph");
1952 // If the node was created after the escape computation we can't answer.
1953 uint idx = n->_idx;
1954 if (idx >= nodes_size()) {
1955 return NULL;
1956 }
1957 PointsToNode* ptn = ptnode_adr(idx);
1958 if (ptn->is_JavaObject()) {
1959 return ptn->as_JavaObject();
1960 }
1961 assert(ptn->is_LocalVar(), "sanity");
1962 // Check all java objects it points to.
1963 JavaObjectNode* jobj = NULL;
1964 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1965 PointsToNode* e = i.get();
1966 if (e->is_JavaObject()) {
1967 if (jobj == NULL) {
1968 jobj = e->as_JavaObject();
1969 } else if (jobj != e) {
1970 return NULL;
1971 }
1972 }
1973 }
1974 return jobj;
1975 }
1977 // Return true if this node points only to non-escaping allocations.
1978 bool PointsToNode::non_escaping_allocation() {
1979 if (is_JavaObject()) {
1980 Node* n = ideal_node();
1981 if (n->is_Allocate() || n->is_CallStaticJava()) {
1982 return (escape_state() == PointsToNode::NoEscape);
1983 } else {
1984 return false;
1985 }
1986 }
1987 assert(is_LocalVar(), "sanity");
1988 // Check all java objects it points to.
1989 for (EdgeIterator i(this); i.has_next(); i.next()) {
1990 PointsToNode* e = i.get();
1991 if (e->is_JavaObject()) {
1992 Node* n = e->ideal_node();
1993 if ((e->escape_state() != PointsToNode::NoEscape) ||
1994 !(n->is_Allocate() || n->is_CallStaticJava())) {
1995 return false;
1996 }
1997 }
1998 }
1999 return true;
2000 }
2002 // Return true if we know the node does not escape globally.
2003 bool ConnectionGraph::not_global_escape(Node *n) {
2004 assert(!_collecting, "should not call during graph construction");
2005 // If the node was created after the escape computation we can't answer.
2006 uint idx = n->_idx;
2007 if (idx >= nodes_size()) {
2008 return false;
2009 }
2010 PointsToNode* ptn = ptnode_adr(idx);
2011 PointsToNode::EscapeState es = ptn->escape_state();
2012 // If we have already computed a value, return it.
2013 if (es >= PointsToNode::GlobalEscape)
2014 return false;
2015 if (ptn->is_JavaObject()) {
2016 return true; // (es < PointsToNode::GlobalEscape);
2017 }
2018 assert(ptn->is_LocalVar(), "sanity");
2019 // Check all java objects it points to.
2020 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2021 if (i.get()->escape_state() >= PointsToNode::GlobalEscape)
2022 return false;
2023 }
2024 return true;
2025 }
2028 // Helper functions
2030 // Return true if this node points to specified node or nodes it points to.
2031 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
2032 if (is_JavaObject()) {
2033 return (this == ptn);
2034 }
2035 assert(is_LocalVar() || is_Field(), "sanity");
2036 for (EdgeIterator i(this); i.has_next(); i.next()) {
2037 if (i.get() == ptn)
2038 return true;
2039 }
2040 return false;
2041 }
2043 // Return true if one node points to an other.
2044 bool PointsToNode::meet(PointsToNode* ptn) {
2045 if (this == ptn) {
2046 return true;
2047 } else if (ptn->is_JavaObject()) {
2048 return this->points_to(ptn->as_JavaObject());
2049 } else if (this->is_JavaObject()) {
2050 return ptn->points_to(this->as_JavaObject());
2051 }
2052 assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
2053 int ptn_count = ptn->edge_count();
2054 for (EdgeIterator i(this); i.has_next(); i.next()) {
2055 PointsToNode* this_e = i.get();
2056 for (int j = 0; j < ptn_count; j++) {
2057 if (this_e == ptn->edge(j))
2058 return true;
2059 }
2060 }
2061 return false;
2062 }
2064 #ifdef ASSERT
2065 // Return true if bases point to this java object.
2066 bool FieldNode::has_base(JavaObjectNode* jobj) const {
2067 for (BaseIterator i(this); i.has_next(); i.next()) {
2068 if (i.get() == jobj)
2069 return true;
2070 }
2071 return false;
2072 }
2073 #endif
2075 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
2076 const Type *adr_type = phase->type(adr);
2077 if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
2078 adr->in(AddPNode::Address)->is_Proj() &&
2079 adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
2080 // We are computing a raw address for a store captured by an Initialize
2081 // compute an appropriate address type. AddP cases #3 and #5 (see below).
2082 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
2083 assert(offs != Type::OffsetBot ||
2084 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
2085 "offset must be a constant or it is initialization of array");
2086 return offs;
2087 }
2088 const TypePtr *t_ptr = adr_type->isa_ptr();
2089 assert(t_ptr != NULL, "must be a pointer type");
2090 return t_ptr->offset();
2091 }
2093 Node* ConnectionGraph::get_addp_base(Node *addp) {
2094 assert(addp->is_AddP(), "must be AddP");
2095 //
2096 // AddP cases for Base and Address inputs:
2097 // case #1. Direct object's field reference:
2098 // Allocate
2099 // |
2100 // Proj #5 ( oop result )
2101 // |
2102 // CheckCastPP (cast to instance type)
2103 // | |
2104 // AddP ( base == address )
2105 //
2106 // case #2. Indirect object's field reference:
2107 // Phi
2108 // |
2109 // CastPP (cast to instance type)
2110 // | |
2111 // AddP ( base == address )
2112 //
2113 // case #3. Raw object's field reference for Initialize node:
2114 // Allocate
2115 // |
2116 // Proj #5 ( oop result )
2117 // top |
2118 // \ |
2119 // AddP ( base == top )
2120 //
2121 // case #4. Array's element reference:
2122 // {CheckCastPP | CastPP}
2123 // | | |
2124 // | AddP ( array's element offset )
2125 // | |
2126 // AddP ( array's offset )
2127 //
2128 // case #5. Raw object's field reference for arraycopy stub call:
2129 // The inline_native_clone() case when the arraycopy stub is called
2130 // after the allocation before Initialize and CheckCastPP nodes.
2131 // Allocate
2132 // |
2133 // Proj #5 ( oop result )
2134 // | |
2135 // AddP ( base == address )
2136 //
2137 // case #6. Constant Pool, ThreadLocal, CastX2P or
2138 // Raw object's field reference:
2139 // {ConP, ThreadLocal, CastX2P, raw Load}
2140 // top |
2141 // \ |
2142 // AddP ( base == top )
2143 //
2144 // case #7. Klass's field reference.
2145 // LoadKlass
2146 // | |
2147 // AddP ( base == address )
2148 //
2149 // case #8. narrow Klass's field reference.
2150 // LoadNKlass
2151 // |
2152 // DecodeN
2153 // | |
2154 // AddP ( base == address )
2155 //
2156 Node *base = addp->in(AddPNode::Base);
2157 if (base->uncast()->is_top()) { // The AddP case #3 and #6.
2158 base = addp->in(AddPNode::Address);
2159 while (base->is_AddP()) {
2160 // Case #6 (unsafe access) may have several chained AddP nodes.
2161 assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
2162 base = base->in(AddPNode::Address);
2163 }
2164 Node* uncast_base = base->uncast();
2165 int opcode = uncast_base->Opcode();
2166 assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
2167 opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
2168 (uncast_base->is_Mem() && uncast_base->bottom_type() == TypeRawPtr::NOTNULL) ||
2169 (uncast_base->is_Proj() && uncast_base->in(0)->is_Allocate()), "sanity");
2170 }
2171 return base;
2172 }
2174 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
2175 assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
2176 Node* addp2 = addp->raw_out(0);
2177 if (addp->outcnt() == 1 && addp2->is_AddP() &&
2178 addp2->in(AddPNode::Base) == n &&
2179 addp2->in(AddPNode::Address) == addp) {
2180 assert(addp->in(AddPNode::Base) == n, "expecting the same base");
2181 //
2182 // Find array's offset to push it on worklist first and
2183 // as result process an array's element offset first (pushed second)
2184 // to avoid CastPP for the array's offset.
2185 // Otherwise the inserted CastPP (LocalVar) will point to what
2186 // the AddP (Field) points to. Which would be wrong since
2187 // the algorithm expects the CastPP has the same point as
2188 // as AddP's base CheckCastPP (LocalVar).
2189 //
2190 // ArrayAllocation
2191 // |
2192 // CheckCastPP
2193 // |
2194 // memProj (from ArrayAllocation CheckCastPP)
2195 // | ||
2196 // | || Int (element index)
2197 // | || | ConI (log(element size))
2198 // | || | /
2199 // | || LShift
2200 // | || /
2201 // | AddP (array's element offset)
2202 // | |
2203 // | | ConI (array's offset: #12(32-bits) or #24(64-bits))
2204 // | / /
2205 // AddP (array's offset)
2206 // |
2207 // Load/Store (memory operation on array's element)
2208 //
2209 return addp2;
2210 }
2211 return NULL;
2212 }
2214 //
2215 // Adjust the type and inputs of an AddP which computes the
2216 // address of a field of an instance
2217 //
2218 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
2219 PhaseGVN* igvn = _igvn;
2220 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
2221 assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
2222 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
2223 if (t == NULL) {
2224 // We are computing a raw address for a store captured by an Initialize
2225 // compute an appropriate address type (cases #3 and #5).
2226 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
2227 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
2228 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
2229 assert(offs != Type::OffsetBot, "offset must be a constant");
2230 t = base_t->add_offset(offs)->is_oopptr();
2231 }
2232 int inst_id = base_t->instance_id();
2233 assert(!t->is_known_instance() || t->instance_id() == inst_id,
2234 "old type must be non-instance or match new type");
2236 // The type 't' could be subclass of 'base_t'.
2237 // As result t->offset() could be large then base_t's size and it will
2238 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
2239 // constructor verifies correctness of the offset.
2240 //
2241 // It could happened on subclass's branch (from the type profiling
2242 // inlining) which was not eliminated during parsing since the exactness
2243 // of the allocation type was not propagated to the subclass type check.
2244 //
2245 // Or the type 't' could be not related to 'base_t' at all.
2246 // It could happened when CHA type is different from MDO type on a dead path
2247 // (for example, from instanceof check) which is not collapsed during parsing.
2248 //
2249 // Do nothing for such AddP node and don't process its users since
2250 // this code branch will go away.
2251 //
2252 if (!t->is_known_instance() &&
2253 !base_t->klass()->is_subtype_of(t->klass())) {
2254 return false; // bail out
2255 }
2256 const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
2257 // Do NOT remove the next line: ensure a new alias index is allocated
2258 // for the instance type. Note: C++ will not remove it since the call
2259 // has side effect.
2260 int alias_idx = _compile->get_alias_index(tinst);
2261 igvn->set_type(addp, tinst);
2262 // record the allocation in the node map
2263 set_map(addp, get_map(base->_idx));
2264 // Set addp's Base and Address to 'base'.
2265 Node *abase = addp->in(AddPNode::Base);
2266 Node *adr = addp->in(AddPNode::Address);
2267 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
2268 adr->in(0)->_idx == (uint)inst_id) {
2269 // Skip AddP cases #3 and #5.
2270 } else {
2271 assert(!abase->is_top(), "sanity"); // AddP case #3
2272 if (abase != base) {
2273 igvn->hash_delete(addp);
2274 addp->set_req(AddPNode::Base, base);
2275 if (abase == adr) {
2276 addp->set_req(AddPNode::Address, base);
2277 } else {
2278 // AddP case #4 (adr is array's element offset AddP node)
2279 #ifdef ASSERT
2280 const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
2281 assert(adr->is_AddP() && atype != NULL &&
2282 atype->instance_id() == inst_id, "array's element offset should be processed first");
2283 #endif
2284 }
2285 igvn->hash_insert(addp);
2286 }
2287 }
2288 // Put on IGVN worklist since at least addp's type was changed above.
2289 record_for_optimizer(addp);
2290 return true;
2291 }
2293 //
2294 // Create a new version of orig_phi if necessary. Returns either the newly
2295 // created phi or an existing phi. Sets create_new to indicate whether a new
2296 // phi was created. Cache the last newly created phi in the node map.
2297 //
2298 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *> &orig_phi_worklist, bool &new_created) {
2299 Compile *C = _compile;
2300 PhaseGVN* igvn = _igvn;
2301 new_created = false;
2302 int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
2303 // nothing to do if orig_phi is bottom memory or matches alias_idx
2304 if (phi_alias_idx == alias_idx) {
2305 return orig_phi;
2306 }
2307 // Have we recently created a Phi for this alias index?
2308 PhiNode *result = get_map_phi(orig_phi->_idx);
2309 if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
2310 return result;
2311 }
2312 // Previous check may fail when the same wide memory Phi was split into Phis
2313 // for different memory slices. Search all Phis for this region.
2314 if (result != NULL) {
2315 Node* region = orig_phi->in(0);
2316 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2317 Node* phi = region->fast_out(i);
2318 if (phi->is_Phi() &&
2319 C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
2320 assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
2321 return phi->as_Phi();
2322 }
2323 }
2324 }
2325 if ((int) (C->live_nodes() + 2*NodeLimitFudgeFactor) > MaxNodeLimit) {
2326 if (C->do_escape_analysis() == true && !C->failing()) {
2327 // Retry compilation without escape analysis.
2328 // If this is the first failure, the sentinel string will "stick"
2329 // to the Compile object, and the C2Compiler will see it and retry.
2330 C->record_failure(C2Compiler::retry_no_escape_analysis());
2331 }
2332 return NULL;
2333 }
2334 orig_phi_worklist.append_if_missing(orig_phi);
2335 const TypePtr *atype = C->get_adr_type(alias_idx);
2336 result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
2337 C->copy_node_notes_to(result, orig_phi);
2338 igvn->set_type(result, result->bottom_type());
2339 record_for_optimizer(result);
2340 set_map(orig_phi, result);
2341 new_created = true;
2342 return result;
2343 }
2345 //
2346 // Return a new version of Memory Phi "orig_phi" with the inputs having the
2347 // specified alias index.
2348 //
2349 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *> &orig_phi_worklist) {
2350 assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
2351 Compile *C = _compile;
2352 PhaseGVN* igvn = _igvn;
2353 bool new_phi_created;
2354 PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
2355 if (!new_phi_created) {
2356 return result;
2357 }
2358 GrowableArray<PhiNode *> phi_list;
2359 GrowableArray<uint> cur_input;
2360 PhiNode *phi = orig_phi;
2361 uint idx = 1;
2362 bool finished = false;
2363 while(!finished) {
2364 while (idx < phi->req()) {
2365 Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist);
2366 if (mem != NULL && mem->is_Phi()) {
2367 PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
2368 if (new_phi_created) {
2369 // found an phi for which we created a new split, push current one on worklist and begin
2370 // processing new one
2371 phi_list.push(phi);
2372 cur_input.push(idx);
2373 phi = mem->as_Phi();
2374 result = newphi;
2375 idx = 1;
2376 continue;
2377 } else {
2378 mem = newphi;
2379 }
2380 }
2381 if (C->failing()) {
2382 return NULL;
2383 }
2384 result->set_req(idx++, mem);
2385 }
2386 #ifdef ASSERT
2387 // verify that the new Phi has an input for each input of the original
2388 assert( phi->req() == result->req(), "must have same number of inputs.");
2389 assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
2390 #endif
2391 // Check if all new phi's inputs have specified alias index.
2392 // Otherwise use old phi.
2393 for (uint i = 1; i < phi->req(); i++) {
2394 Node* in = result->in(i);
2395 assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
2396 }
2397 // we have finished processing a Phi, see if there are any more to do
2398 finished = (phi_list.length() == 0 );
2399 if (!finished) {
2400 phi = phi_list.pop();
2401 idx = cur_input.pop();
2402 PhiNode *prev_result = get_map_phi(phi->_idx);
2403 prev_result->set_req(idx++, result);
2404 result = prev_result;
2405 }
2406 }
2407 return result;
2408 }
2410 //
2411 // The next methods are derived from methods in MemNode.
2412 //
2413 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
2414 Node *mem = mmem;
2415 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
2416 // means an array I have not precisely typed yet. Do not do any
2417 // alias stuff with it any time soon.
2418 if (toop->base() != Type::AnyPtr &&
2419 !(toop->klass() != NULL &&
2420 toop->klass()->is_java_lang_Object() &&
2421 toop->offset() == Type::OffsetBot)) {
2422 mem = mmem->memory_at(alias_idx);
2423 // Update input if it is progress over what we have now
2424 }
2425 return mem;
2426 }
2428 //
2429 // Move memory users to their memory slices.
2430 //
2431 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *> &orig_phis) {
2432 Compile* C = _compile;
2433 PhaseGVN* igvn = _igvn;
2434 const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
2435 assert(tp != NULL, "ptr type");
2436 int alias_idx = C->get_alias_index(tp);
2437 int general_idx = C->get_general_index(alias_idx);
2439 // Move users first
2440 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2441 Node* use = n->fast_out(i);
2442 if (use->is_MergeMem()) {
2443 MergeMemNode* mmem = use->as_MergeMem();
2444 assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
2445 if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
2446 continue; // Nothing to do
2447 }
2448 // Replace previous general reference to mem node.
2449 uint orig_uniq = C->unique();
2450 Node* m = find_inst_mem(n, general_idx, orig_phis);
2451 assert(orig_uniq == C->unique(), "no new nodes");
2452 mmem->set_memory_at(general_idx, m);
2453 --imax;
2454 --i;
2455 } else if (use->is_MemBar()) {
2456 assert(!use->is_Initialize(), "initializing stores should not be moved");
2457 if (use->req() > MemBarNode::Precedent &&
2458 use->in(MemBarNode::Precedent) == n) {
2459 // Don't move related membars.
2460 record_for_optimizer(use);
2461 continue;
2462 }
2463 tp = use->as_MemBar()->adr_type()->isa_ptr();
2464 if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
2465 alias_idx == general_idx) {
2466 continue; // Nothing to do
2467 }
2468 // Move to general memory slice.
2469 uint orig_uniq = C->unique();
2470 Node* m = find_inst_mem(n, general_idx, orig_phis);
2471 assert(orig_uniq == C->unique(), "no new nodes");
2472 igvn->hash_delete(use);
2473 imax -= use->replace_edge(n, m);
2474 igvn->hash_insert(use);
2475 record_for_optimizer(use);
2476 --i;
2477 #ifdef ASSERT
2478 } else if (use->is_Mem()) {
2479 if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
2480 // Don't move related cardmark.
2481 continue;
2482 }
2483 // Memory nodes should have new memory input.
2484 tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
2485 assert(tp != NULL, "ptr type");
2486 int idx = C->get_alias_index(tp);
2487 assert(get_map(use->_idx) != NULL || idx == alias_idx,
2488 "Following memory nodes should have new memory input or be on the same memory slice");
2489 } else if (use->is_Phi()) {
2490 // Phi nodes should be split and moved already.
2491 tp = use->as_Phi()->adr_type()->isa_ptr();
2492 assert(tp != NULL, "ptr type");
2493 int idx = C->get_alias_index(tp);
2494 assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
2495 } else {
2496 use->dump();
2497 assert(false, "should not be here");
2498 #endif
2499 }
2500 }
2501 }
2503 //
2504 // Search memory chain of "mem" to find a MemNode whose address
2505 // is the specified alias index.
2506 //
2507 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *> &orig_phis) {
2508 if (orig_mem == NULL)
2509 return orig_mem;
2510 Compile* C = _compile;
2511 PhaseGVN* igvn = _igvn;
2512 const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
2513 bool is_instance = (toop != NULL) && toop->is_known_instance();
2514 Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
2515 Node *prev = NULL;
2516 Node *result = orig_mem;
2517 while (prev != result) {
2518 prev = result;
2519 if (result == start_mem)
2520 break; // hit one of our sentinels
2521 if (result->is_Mem()) {
2522 const Type *at = igvn->type(result->in(MemNode::Address));
2523 if (at == Type::TOP)
2524 break; // Dead
2525 assert (at->isa_ptr() != NULL, "pointer type required.");
2526 int idx = C->get_alias_index(at->is_ptr());
2527 if (idx == alias_idx)
2528 break; // Found
2529 if (!is_instance && (at->isa_oopptr() == NULL ||
2530 !at->is_oopptr()->is_known_instance())) {
2531 break; // Do not skip store to general memory slice.
2532 }
2533 result = result->in(MemNode::Memory);
2534 }
2535 if (!is_instance)
2536 continue; // don't search further for non-instance types
2537 // skip over a call which does not affect this memory slice
2538 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
2539 Node *proj_in = result->in(0);
2540 if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
2541 break; // hit one of our sentinels
2542 } else if (proj_in->is_Call()) {
2543 CallNode *call = proj_in->as_Call();
2544 if (!call->may_modify(toop, igvn)) {
2545 result = call->in(TypeFunc::Memory);
2546 }
2547 } else if (proj_in->is_Initialize()) {
2548 AllocateNode* alloc = proj_in->as_Initialize()->allocation();
2549 // Stop if this is the initialization for the object instance which
2550 // which contains this memory slice, otherwise skip over it.
2551 if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
2552 result = proj_in->in(TypeFunc::Memory);
2553 }
2554 } else if (proj_in->is_MemBar()) {
2555 result = proj_in->in(TypeFunc::Memory);
2556 }
2557 } else if (result->is_MergeMem()) {
2558 MergeMemNode *mmem = result->as_MergeMem();
2559 result = step_through_mergemem(mmem, alias_idx, toop);
2560 if (result == mmem->base_memory()) {
2561 // Didn't find instance memory, search through general slice recursively.
2562 result = mmem->memory_at(C->get_general_index(alias_idx));
2563 result = find_inst_mem(result, alias_idx, orig_phis);
2564 if (C->failing()) {
2565 return NULL;
2566 }
2567 mmem->set_memory_at(alias_idx, result);
2568 }
2569 } else if (result->is_Phi() &&
2570 C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
2571 Node *un = result->as_Phi()->unique_input(igvn);
2572 if (un != NULL) {
2573 orig_phis.append_if_missing(result->as_Phi());
2574 result = un;
2575 } else {
2576 break;
2577 }
2578 } else if (result->is_ClearArray()) {
2579 if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
2580 // Can not bypass initialization of the instance
2581 // we are looking for.
2582 break;
2583 }
2584 // Otherwise skip it (the call updated 'result' value).
2585 } else if (result->Opcode() == Op_SCMemProj) {
2586 Node* mem = result->in(0);
2587 Node* adr = NULL;
2588 if (mem->is_LoadStore()) {
2589 adr = mem->in(MemNode::Address);
2590 } else {
2591 assert(mem->Opcode() == Op_EncodeISOArray, "sanity");
2592 adr = mem->in(3); // Memory edge corresponds to destination array
2593 }
2594 const Type *at = igvn->type(adr);
2595 if (at != Type::TOP) {
2596 assert (at->isa_ptr() != NULL, "pointer type required.");
2597 int idx = C->get_alias_index(at->is_ptr());
2598 assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
2599 break;
2600 }
2601 result = mem->in(MemNode::Memory);
2602 }
2603 }
2604 if (result->is_Phi()) {
2605 PhiNode *mphi = result->as_Phi();
2606 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
2607 const TypePtr *t = mphi->adr_type();
2608 if (!is_instance) {
2609 // Push all non-instance Phis on the orig_phis worklist to update inputs
2610 // during Phase 4 if needed.
2611 orig_phis.append_if_missing(mphi);
2612 } else if (C->get_alias_index(t) != alias_idx) {
2613 // Create a new Phi with the specified alias index type.
2614 result = split_memory_phi(mphi, alias_idx, orig_phis);
2615 }
2616 }
2617 // the result is either MemNode, PhiNode, InitializeNode.
2618 return result;
2619 }
2621 //
2622 // Convert the types of unescaped object to instance types where possible,
2623 // propagate the new type information through the graph, and update memory
2624 // edges and MergeMem inputs to reflect the new type.
2625 //
2626 // We start with allocations (and calls which may be allocations) on alloc_worklist.
2627 // The processing is done in 4 phases:
2628 //
2629 // Phase 1: Process possible allocations from alloc_worklist. Create instance
2630 // types for the CheckCastPP for allocations where possible.
2631 // Propagate the the new types through users as follows:
2632 // casts and Phi: push users on alloc_worklist
2633 // AddP: cast Base and Address inputs to the instance type
2634 // push any AddP users on alloc_worklist and push any memnode
2635 // users onto memnode_worklist.
2636 // Phase 2: Process MemNode's from memnode_worklist. compute new address type and
2637 // search the Memory chain for a store with the appropriate type
2638 // address type. If a Phi is found, create a new version with
2639 // the appropriate memory slices from each of the Phi inputs.
2640 // For stores, process the users as follows:
2641 // MemNode: push on memnode_worklist
2642 // MergeMem: push on mergemem_worklist
2643 // Phase 3: Process MergeMem nodes from mergemem_worklist. Walk each memory slice
2644 // moving the first node encountered of each instance type to the
2645 // the input corresponding to its alias index.
2646 // appropriate memory slice.
2647 // Phase 4: Update the inputs of non-instance memory Phis and the Memory input of memnodes.
2648 //
2649 // In the following example, the CheckCastPP nodes are the cast of allocation
2650 // results and the allocation of node 29 is unescaped and eligible to be an
2651 // instance type.
2652 //
2653 // We start with:
2654 //
2655 // 7 Parm #memory
2656 // 10 ConI "12"
2657 // 19 CheckCastPP "Foo"
2658 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
2659 // 29 CheckCastPP "Foo"
2660 // 30 AddP _ 29 29 10 Foo+12 alias_index=4
2661 //
2662 // 40 StoreP 25 7 20 ... alias_index=4
2663 // 50 StoreP 35 40 30 ... alias_index=4
2664 // 60 StoreP 45 50 20 ... alias_index=4
2665 // 70 LoadP _ 60 30 ... alias_index=4
2666 // 80 Phi 75 50 60 Memory alias_index=4
2667 // 90 LoadP _ 80 30 ... alias_index=4
2668 // 100 LoadP _ 80 20 ... alias_index=4
2669 //
2670 //
2671 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
2672 // and creating a new alias index for node 30. This gives:
2673 //
2674 // 7 Parm #memory
2675 // 10 ConI "12"
2676 // 19 CheckCastPP "Foo"
2677 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
2678 // 29 CheckCastPP "Foo" iid=24
2679 // 30 AddP _ 29 29 10 Foo+12 alias_index=6 iid=24
2680 //
2681 // 40 StoreP 25 7 20 ... alias_index=4
2682 // 50 StoreP 35 40 30 ... alias_index=6
2683 // 60 StoreP 45 50 20 ... alias_index=4
2684 // 70 LoadP _ 60 30 ... alias_index=6
2685 // 80 Phi 75 50 60 Memory alias_index=4
2686 // 90 LoadP _ 80 30 ... alias_index=6
2687 // 100 LoadP _ 80 20 ... alias_index=4
2688 //
2689 // In phase 2, new memory inputs are computed for the loads and stores,
2690 // And a new version of the phi is created. In phase 4, the inputs to
2691 // node 80 are updated and then the memory nodes are updated with the
2692 // values computed in phase 2. This results in:
2693 //
2694 // 7 Parm #memory
2695 // 10 ConI "12"
2696 // 19 CheckCastPP "Foo"
2697 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
2698 // 29 CheckCastPP "Foo" iid=24
2699 // 30 AddP _ 29 29 10 Foo+12 alias_index=6 iid=24
2700 //
2701 // 40 StoreP 25 7 20 ... alias_index=4
2702 // 50 StoreP 35 7 30 ... alias_index=6
2703 // 60 StoreP 45 40 20 ... alias_index=4
2704 // 70 LoadP _ 50 30 ... alias_index=6
2705 // 80 Phi 75 40 60 Memory alias_index=4
2706 // 120 Phi 75 50 50 Memory alias_index=6
2707 // 90 LoadP _ 120 30 ... alias_index=6
2708 // 100 LoadP _ 80 20 ... alias_index=4
2709 //
2710 void ConnectionGraph::split_unique_types(GrowableArray<Node *> &alloc_worklist) {
2711 GrowableArray<Node *> memnode_worklist;
2712 GrowableArray<PhiNode *> orig_phis;
2713 PhaseIterGVN *igvn = _igvn;
2714 uint new_index_start = (uint) _compile->num_alias_types();
2715 Arena* arena = Thread::current()->resource_area();
2716 VectorSet visited(arena);
2717 ideal_nodes.clear(); // Reset for use with set_map/get_map.
2718 uint unique_old = _compile->unique();
2720 // Phase 1: Process possible allocations from alloc_worklist.
2721 // Create instance types for the CheckCastPP for allocations where possible.
2722 //
2723 // (Note: don't forget to change the order of the second AddP node on
2724 // the alloc_worklist if the order of the worklist processing is changed,
2725 // see the comment in find_second_addp().)
2726 //
2727 while (alloc_worklist.length() != 0) {
2728 Node *n = alloc_worklist.pop();
2729 uint ni = n->_idx;
2730 if (n->is_Call()) {
2731 CallNode *alloc = n->as_Call();
2732 // copy escape information to call node
2733 PointsToNode* ptn = ptnode_adr(alloc->_idx);
2734 PointsToNode::EscapeState es = ptn->escape_state();
2735 // We have an allocation or call which returns a Java object,
2736 // see if it is unescaped.
2737 if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable())
2738 continue;
2739 // Find CheckCastPP for the allocate or for the return value of a call
2740 n = alloc->result_cast();
2741 if (n == NULL) { // No uses except Initialize node
2742 if (alloc->is_Allocate()) {
2743 // Set the scalar_replaceable flag for allocation
2744 // so it could be eliminated if it has no uses.
2745 alloc->as_Allocate()->_is_scalar_replaceable = true;
2746 }
2747 continue;
2748 }
2749 if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
2750 assert(!alloc->is_Allocate(), "allocation should have unique type");
2751 continue;
2752 }
2754 // The inline code for Object.clone() casts the allocation result to
2755 // java.lang.Object and then to the actual type of the allocated
2756 // object. Detect this case and use the second cast.
2757 // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
2758 // the allocation result is cast to java.lang.Object and then
2759 // to the actual Array type.
2760 if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
2761 && (alloc->is_AllocateArray() ||
2762 igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
2763 Node *cast2 = NULL;
2764 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2765 Node *use = n->fast_out(i);
2766 if (use->is_CheckCastPP()) {
2767 cast2 = use;
2768 break;
2769 }
2770 }
2771 if (cast2 != NULL) {
2772 n = cast2;
2773 } else {
2774 // Non-scalar replaceable if the allocation type is unknown statically
2775 // (reflection allocation), the object can't be restored during
2776 // deoptimization without precise type.
2777 continue;
2778 }
2779 }
2780 if (alloc->is_Allocate()) {
2781 // Set the scalar_replaceable flag for allocation
2782 // so it could be eliminated.
2783 alloc->as_Allocate()->_is_scalar_replaceable = true;
2784 }
2785 set_escape_state(ptnode_adr(n->_idx), es); // CheckCastPP escape state
2786 // in order for an object to be scalar-replaceable, it must be:
2787 // - a direct allocation (not a call returning an object)
2788 // - non-escaping
2789 // - eligible to be a unique type
2790 // - not determined to be ineligible by escape analysis
2791 set_map(alloc, n);
2792 set_map(n, alloc);
2793 const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
2794 if (t == NULL)
2795 continue; // not a TypeOopPtr
2796 const TypeOopPtr* tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni);
2797 igvn->hash_delete(n);
2798 igvn->set_type(n, tinst);
2799 n->raise_bottom_type(tinst);
2800 igvn->hash_insert(n);
2801 record_for_optimizer(n);
2802 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
2804 // First, put on the worklist all Field edges from Connection Graph
2805 // which is more accurate then putting immediate users from Ideal Graph.
2806 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
2807 PointsToNode* tgt = e.get();
2808 Node* use = tgt->ideal_node();
2809 assert(tgt->is_Field() && use->is_AddP(),
2810 "only AddP nodes are Field edges in CG");
2811 if (use->outcnt() > 0) { // Don't process dead nodes
2812 Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
2813 if (addp2 != NULL) {
2814 assert(alloc->is_AllocateArray(),"array allocation was expected");
2815 alloc_worklist.append_if_missing(addp2);
2816 }
2817 alloc_worklist.append_if_missing(use);
2818 }
2819 }
2821 // An allocation may have an Initialize which has raw stores. Scan
2822 // the users of the raw allocation result and push AddP users
2823 // on alloc_worklist.
2824 Node *raw_result = alloc->proj_out(TypeFunc::Parms);
2825 assert (raw_result != NULL, "must have an allocation result");
2826 for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
2827 Node *use = raw_result->fast_out(i);
2828 if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
2829 Node* addp2 = find_second_addp(use, raw_result);
2830 if (addp2 != NULL) {
2831 assert(alloc->is_AllocateArray(),"array allocation was expected");
2832 alloc_worklist.append_if_missing(addp2);
2833 }
2834 alloc_worklist.append_if_missing(use);
2835 } else if (use->is_MemBar()) {
2836 memnode_worklist.append_if_missing(use);
2837 }
2838 }
2839 }
2840 } else if (n->is_AddP()) {
2841 JavaObjectNode* jobj = unique_java_object(get_addp_base(n));
2842 if (jobj == NULL || jobj == phantom_obj) {
2843 #ifdef ASSERT
2844 ptnode_adr(get_addp_base(n)->_idx)->dump();
2845 ptnode_adr(n->_idx)->dump();
2846 assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
2847 #endif
2848 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
2849 return;
2850 }
2851 Node *base = get_map(jobj->idx()); // CheckCastPP node
2852 if (!split_AddP(n, base)) continue; // wrong type from dead path
2853 } else if (n->is_Phi() ||
2854 n->is_CheckCastPP() ||
2855 n->is_EncodeP() ||
2856 n->is_DecodeN() ||
2857 (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
2858 if (visited.test_set(n->_idx)) {
2859 assert(n->is_Phi(), "loops only through Phi's");
2860 continue; // already processed
2861 }
2862 JavaObjectNode* jobj = unique_java_object(n);
2863 if (jobj == NULL || jobj == phantom_obj) {
2864 #ifdef ASSERT
2865 ptnode_adr(n->_idx)->dump();
2866 assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
2867 #endif
2868 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
2869 return;
2870 } else {
2871 Node *val = get_map(jobj->idx()); // CheckCastPP node
2872 TypeNode *tn = n->as_Type();
2873 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
2874 assert(tinst != NULL && tinst->is_known_instance() &&
2875 tinst->instance_id() == jobj->idx() , "instance type expected.");
2877 const Type *tn_type = igvn->type(tn);
2878 const TypeOopPtr *tn_t;
2879 if (tn_type->isa_narrowoop()) {
2880 tn_t = tn_type->make_ptr()->isa_oopptr();
2881 } else {
2882 tn_t = tn_type->isa_oopptr();
2883 }
2884 if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
2885 if (tn_type->isa_narrowoop()) {
2886 tn_type = tinst->make_narrowoop();
2887 } else {
2888 tn_type = tinst;
2889 }
2890 igvn->hash_delete(tn);
2891 igvn->set_type(tn, tn_type);
2892 tn->set_type(tn_type);
2893 igvn->hash_insert(tn);
2894 record_for_optimizer(n);
2895 } else {
2896 assert(tn_type == TypePtr::NULL_PTR ||
2897 tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
2898 "unexpected type");
2899 continue; // Skip dead path with different type
2900 }
2901 }
2902 } else {
2903 debug_only(n->dump();)
2904 assert(false, "EA: unexpected node");
2905 continue;
2906 }
2907 // push allocation's users on appropriate worklist
2908 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2909 Node *use = n->fast_out(i);
2910 if(use->is_Mem() && use->in(MemNode::Address) == n) {
2911 // Load/store to instance's field
2912 memnode_worklist.append_if_missing(use);
2913 } else if (use->is_MemBar()) {
2914 memnode_worklist.append_if_missing(use);
2915 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
2916 Node* addp2 = find_second_addp(use, n);
2917 if (addp2 != NULL) {
2918 alloc_worklist.append_if_missing(addp2);
2919 }
2920 alloc_worklist.append_if_missing(use);
2921 } else if (use->is_Phi() ||
2922 use->is_CheckCastPP() ||
2923 use->is_EncodeNarrowPtr() ||
2924 use->is_DecodeNarrowPtr() ||
2925 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
2926 alloc_worklist.append_if_missing(use);
2927 #ifdef ASSERT
2928 } else if (use->is_Mem()) {
2929 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
2930 } else if (use->is_MergeMem()) {
2931 assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
2932 } else if (use->is_SafePoint()) {
2933 // Look for MergeMem nodes for calls which reference unique allocation
2934 // (through CheckCastPP nodes) even for debug info.
2935 Node* m = use->in(TypeFunc::Memory);
2936 if (m->is_MergeMem()) {
2937 assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
2938 }
2939 } else if (use->Opcode() == Op_EncodeISOArray) {
2940 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
2941 // EncodeISOArray overwrites destination array
2942 memnode_worklist.append_if_missing(use);
2943 }
2944 } else {
2945 uint op = use->Opcode();
2946 if (!(op == Op_CmpP || op == Op_Conv2B ||
2947 op == Op_CastP2X || op == Op_StoreCM ||
2948 op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
2949 op == Op_StrEquals || op == Op_StrIndexOf)) {
2950 n->dump();
2951 use->dump();
2952 assert(false, "EA: missing allocation reference path");
2953 }
2954 #endif
2955 }
2956 }
2958 }
2959 // New alias types were created in split_AddP().
2960 uint new_index_end = (uint) _compile->num_alias_types();
2961 assert(unique_old == _compile->unique(), "there should be no new ideal nodes after Phase 1");
2963 // Phase 2: Process MemNode's from memnode_worklist. compute new address type and
2964 // compute new values for Memory inputs (the Memory inputs are not
2965 // actually updated until phase 4.)
2966 if (memnode_worklist.length() == 0)
2967 return; // nothing to do
2968 while (memnode_worklist.length() != 0) {
2969 Node *n = memnode_worklist.pop();
2970 if (visited.test_set(n->_idx))
2971 continue;
2972 if (n->is_Phi() || n->is_ClearArray()) {
2973 // we don't need to do anything, but the users must be pushed
2974 } else if (n->is_MemBar()) { // Initialize, MemBar nodes
2975 // we don't need to do anything, but the users must be pushed
2976 n = n->as_MemBar()->proj_out(TypeFunc::Memory);
2977 if (n == NULL)
2978 continue;
2979 } else if (n->Opcode() == Op_EncodeISOArray) {
2980 // get the memory projection
2981 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2982 Node *use = n->fast_out(i);
2983 if (use->Opcode() == Op_SCMemProj) {
2984 n = use;
2985 break;
2986 }
2987 }
2988 assert(n->Opcode() == Op_SCMemProj, "memory projection required");
2989 } else {
2990 assert(n->is_Mem(), "memory node required.");
2991 Node *addr = n->in(MemNode::Address);
2992 const Type *addr_t = igvn->type(addr);
2993 if (addr_t == Type::TOP)
2994 continue;
2995 assert (addr_t->isa_ptr() != NULL, "pointer type required.");
2996 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
2997 assert ((uint)alias_idx < new_index_end, "wrong alias index");
2998 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
2999 if (_compile->failing()) {
3000 return;
3001 }
3002 if (mem != n->in(MemNode::Memory)) {
3003 // We delay the memory edge update since we need old one in
3004 // MergeMem code below when instances memory slices are separated.
3005 set_map(n, mem);
3006 }
3007 if (n->is_Load()) {
3008 continue; // don't push users
3009 } else if (n->is_LoadStore()) {
3010 // get the memory projection
3011 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3012 Node *use = n->fast_out(i);
3013 if (use->Opcode() == Op_SCMemProj) {
3014 n = use;
3015 break;
3016 }
3017 }
3018 assert(n->Opcode() == Op_SCMemProj, "memory projection required");
3019 }
3020 }
3021 // push user on appropriate worklist
3022 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3023 Node *use = n->fast_out(i);
3024 if (use->is_Phi() || use->is_ClearArray()) {
3025 memnode_worklist.append_if_missing(use);
3026 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
3027 if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
3028 continue;
3029 memnode_worklist.append_if_missing(use);
3030 } else if (use->is_MemBar()) {
3031 memnode_worklist.append_if_missing(use);
3032 #ifdef ASSERT
3033 } else if(use->is_Mem()) {
3034 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
3035 } else if (use->is_MergeMem()) {
3036 assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3037 } else if (use->Opcode() == Op_EncodeISOArray) {
3038 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
3039 // EncodeISOArray overwrites destination array
3040 memnode_worklist.append_if_missing(use);
3041 }
3042 } else {
3043 uint op = use->Opcode();
3044 if (!(op == Op_StoreCM ||
3045 (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
3046 strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
3047 op == Op_AryEq || op == Op_StrComp ||
3048 op == Op_StrEquals || op == Op_StrIndexOf)) {
3049 n->dump();
3050 use->dump();
3051 assert(false, "EA: missing memory path");
3052 }
3053 #endif
3054 }
3055 }
3056 }
3058 // Phase 3: Process MergeMem nodes from mergemem_worklist.
3059 // Walk each memory slice moving the first node encountered of each
3060 // instance type to the the input corresponding to its alias index.
3061 uint length = _mergemem_worklist.length();
3062 for( uint next = 0; next < length; ++next ) {
3063 MergeMemNode* nmm = _mergemem_worklist.at(next);
3064 assert(!visited.test_set(nmm->_idx), "should not be visited before");
3065 // Note: we don't want to use MergeMemStream here because we only want to
3066 // scan inputs which exist at the start, not ones we add during processing.
3067 // Note 2: MergeMem may already contains instance memory slices added
3068 // during find_inst_mem() call when memory nodes were processed above.
3069 igvn->hash_delete(nmm);
3070 uint nslices = nmm->req();
3071 for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
3072 Node* mem = nmm->in(i);
3073 Node* cur = NULL;
3074 if (mem == NULL || mem->is_top())
3075 continue;
3076 // First, update mergemem by moving memory nodes to corresponding slices
3077 // if their type became more precise since this mergemem was created.
3078 while (mem->is_Mem()) {
3079 const Type *at = igvn->type(mem->in(MemNode::Address));
3080 if (at != Type::TOP) {
3081 assert (at->isa_ptr() != NULL, "pointer type required.");
3082 uint idx = (uint)_compile->get_alias_index(at->is_ptr());
3083 if (idx == i) {
3084 if (cur == NULL)
3085 cur = mem;
3086 } else {
3087 if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
3088 nmm->set_memory_at(idx, mem);
3089 }
3090 }
3091 }
3092 mem = mem->in(MemNode::Memory);
3093 }
3094 nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
3095 // Find any instance of the current type if we haven't encountered
3096 // already a memory slice of the instance along the memory chain.
3097 for (uint ni = new_index_start; ni < new_index_end; ni++) {
3098 if((uint)_compile->get_general_index(ni) == i) {
3099 Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
3100 if (nmm->is_empty_memory(m)) {
3101 Node* result = find_inst_mem(mem, ni, orig_phis);
3102 if (_compile->failing()) {
3103 return;
3104 }
3105 nmm->set_memory_at(ni, result);
3106 }
3107 }
3108 }
3109 }
3110 // Find the rest of instances values
3111 for (uint ni = new_index_start; ni < new_index_end; ni++) {
3112 const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
3113 Node* result = step_through_mergemem(nmm, ni, tinst);
3114 if (result == nmm->base_memory()) {
3115 // Didn't find instance memory, search through general slice recursively.
3116 result = nmm->memory_at(_compile->get_general_index(ni));
3117 result = find_inst_mem(result, ni, orig_phis);
3118 if (_compile->failing()) {
3119 return;
3120 }
3121 nmm->set_memory_at(ni, result);
3122 }
3123 }
3124 igvn->hash_insert(nmm);
3125 record_for_optimizer(nmm);
3126 }
3128 // Phase 4: Update the inputs of non-instance memory Phis and
3129 // the Memory input of memnodes
3130 // First update the inputs of any non-instance Phi's from
3131 // which we split out an instance Phi. Note we don't have
3132 // to recursively process Phi's encounted on the input memory
3133 // chains as is done in split_memory_phi() since they will
3134 // also be processed here.
3135 for (int j = 0; j < orig_phis.length(); j++) {
3136 PhiNode *phi = orig_phis.at(j);
3137 int alias_idx = _compile->get_alias_index(phi->adr_type());
3138 igvn->hash_delete(phi);
3139 for (uint i = 1; i < phi->req(); i++) {
3140 Node *mem = phi->in(i);
3141 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
3142 if (_compile->failing()) {
3143 return;
3144 }
3145 if (mem != new_mem) {
3146 phi->set_req(i, new_mem);
3147 }
3148 }
3149 igvn->hash_insert(phi);
3150 record_for_optimizer(phi);
3151 }
3153 // Update the memory inputs of MemNodes with the value we computed
3154 // in Phase 2 and move stores memory users to corresponding memory slices.
3155 // Disable memory split verification code until the fix for 6984348.
3156 // Currently it produces false negative results since it does not cover all cases.
3157 #if 0 // ifdef ASSERT
3158 visited.Reset();
3159 Node_Stack old_mems(arena, _compile->unique() >> 2);
3160 #endif
3161 for (uint i = 0; i < ideal_nodes.size(); i++) {
3162 Node* n = ideal_nodes.at(i);
3163 Node* nmem = get_map(n->_idx);
3164 assert(nmem != NULL, "sanity");
3165 if (n->is_Mem()) {
3166 #if 0 // ifdef ASSERT
3167 Node* old_mem = n->in(MemNode::Memory);
3168 if (!visited.test_set(old_mem->_idx)) {
3169 old_mems.push(old_mem, old_mem->outcnt());
3170 }
3171 #endif
3172 assert(n->in(MemNode::Memory) != nmem, "sanity");
3173 if (!n->is_Load()) {
3174 // Move memory users of a store first.
3175 move_inst_mem(n, orig_phis);
3176 }
3177 // Now update memory input
3178 igvn->hash_delete(n);
3179 n->set_req(MemNode::Memory, nmem);
3180 igvn->hash_insert(n);
3181 record_for_optimizer(n);
3182 } else {
3183 assert(n->is_Allocate() || n->is_CheckCastPP() ||
3184 n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
3185 }
3186 }
3187 #if 0 // ifdef ASSERT
3188 // Verify that memory was split correctly
3189 while (old_mems.is_nonempty()) {
3190 Node* old_mem = old_mems.node();
3191 uint old_cnt = old_mems.index();
3192 old_mems.pop();
3193 assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
3194 }
3195 #endif
3196 }
3198 #ifndef PRODUCT
3199 static const char *node_type_names[] = {
3200 "UnknownType",
3201 "JavaObject",
3202 "LocalVar",
3203 "Field",
3204 "Arraycopy"
3205 };
3207 static const char *esc_names[] = {
3208 "UnknownEscape",
3209 "NoEscape",
3210 "ArgEscape",
3211 "GlobalEscape"
3212 };
3214 void PointsToNode::dump(bool print_state) const {
3215 NodeType nt = node_type();
3216 tty->print("%s ", node_type_names[(int) nt]);
3217 if (print_state) {
3218 EscapeState es = escape_state();
3219 EscapeState fields_es = fields_escape_state();
3220 tty->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
3221 if (nt == PointsToNode::JavaObject && !this->scalar_replaceable())
3222 tty->print("NSR ");
3223 }
3224 if (is_Field()) {
3225 FieldNode* f = (FieldNode*)this;
3226 if (f->is_oop())
3227 tty->print("oop ");
3228 if (f->offset() > 0)
3229 tty->print("+%d ", f->offset());
3230 tty->print("(");
3231 for (BaseIterator i(f); i.has_next(); i.next()) {
3232 PointsToNode* b = i.get();
3233 tty->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
3234 }
3235 tty->print(" )");
3236 }
3237 tty->print("[");
3238 for (EdgeIterator i(this); i.has_next(); i.next()) {
3239 PointsToNode* e = i.get();
3240 tty->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
3241 }
3242 tty->print(" [");
3243 for (UseIterator i(this); i.has_next(); i.next()) {
3244 PointsToNode* u = i.get();
3245 bool is_base = false;
3246 if (PointsToNode::is_base_use(u)) {
3247 is_base = true;
3248 u = PointsToNode::get_use_node(u)->as_Field();
3249 }
3250 tty->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
3251 }
3252 tty->print(" ]] ");
3253 if (_node == NULL)
3254 tty->print_cr("<null>");
3255 else
3256 _node->dump();
3257 }
3259 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
3260 bool first = true;
3261 int ptnodes_length = ptnodes_worklist.length();
3262 for (int i = 0; i < ptnodes_length; i++) {
3263 PointsToNode *ptn = ptnodes_worklist.at(i);
3264 if (ptn == NULL || !ptn->is_JavaObject())
3265 continue;
3266 PointsToNode::EscapeState es = ptn->escape_state();
3267 if (ptn->ideal_node()->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) {
3268 if (first) {
3269 tty->cr();
3270 tty->print("======== Connection graph for ");
3271 _compile->method()->print_short_name();
3272 tty->cr();
3273 first = false;
3274 }
3275 ptn->dump();
3276 // Print all locals and fields which reference this allocation
3277 for (UseIterator j(ptn); j.has_next(); j.next()) {
3278 PointsToNode* use = j.get();
3279 if (use->is_LocalVar()) {
3280 use->dump(Verbose);
3281 } else if (Verbose) {
3282 use->dump();
3283 }
3284 }
3285 tty->cr();
3286 }
3287 }
3288 }
3289 #endif