1 /*
2 * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/collectedHeap.inline.hpp"
28 #include "libadt/vectset.hpp"
29 #include "memory/universe.hpp"
30 #include "opto/addnode.hpp"
31 #include "opto/arraycopynode.hpp"
32 #include "opto/callnode.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/cfgnode.hpp"
35 #include "opto/compile.hpp"
36 #include "opto/convertnode.hpp"
37 #include "opto/graphKit.hpp"
38 #include "opto/intrinsicnode.hpp"
39 #include "opto/locknode.hpp"
40 #include "opto/loopnode.hpp"
41 #include "opto/macro.hpp"
42 #include "opto/memnode.hpp"
43 #include "opto/narrowptrnode.hpp"
44 #include "opto/node.hpp"
45 #include "opto/opaquenode.hpp"
46 #include "opto/phaseX.hpp"
47 #include "opto/rootnode.hpp"
48 #include "opto/runtime.hpp"
49 #include "opto/subnode.hpp"
50 #include "opto/subtypenode.hpp"
51 #include "opto/type.hpp"
52 #include "runtime/sharedRuntime.hpp"
53 #include "utilities/macros.hpp"
54 #include "utilities/powerOfTwo.hpp"
55 #if INCLUDE_G1GC
56 #include "gc/g1/g1ThreadLocalData.hpp"
57 #endif // INCLUDE_G1GC
58 #if INCLUDE_SHENANDOAHGC
59 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
60 #endif
61
62
63 //
64 // Replace any references to "oldref" in inputs to "use" with "newref".
65 // Returns the number of replacements made.
66 //
replace_input(Node * use,Node * oldref,Node * newref)67 int PhaseMacroExpand::replace_input(Node *use, Node *oldref, Node *newref) {
68 int nreplacements = 0;
69 uint req = use->req();
70 for (uint j = 0; j < use->len(); j++) {
71 Node *uin = use->in(j);
72 if (uin == oldref) {
73 if (j < req)
74 use->set_req(j, newref);
75 else
76 use->set_prec(j, newref);
77 nreplacements++;
78 } else if (j >= req && uin == NULL) {
79 break;
80 }
81 }
82 return nreplacements;
83 }
84
migrate_outs(Node * old,Node * target)85 void PhaseMacroExpand::migrate_outs(Node *old, Node *target) {
86 assert(old != NULL, "sanity");
87 for (DUIterator_Fast imax, i = old->fast_outs(imax); i < imax; i++) {
88 Node* use = old->fast_out(i);
89 _igvn.rehash_node_delayed(use);
90 imax -= replace_input(use, old, target);
91 // back up iterator
92 --i;
93 }
94 assert(old->outcnt() == 0, "all uses must be deleted");
95 }
96
copy_call_debug_info(CallNode * oldcall,CallNode * newcall)97 void PhaseMacroExpand::copy_call_debug_info(CallNode *oldcall, CallNode * newcall) {
98 // Copy debug information and adjust JVMState information
99 uint old_dbg_start = oldcall->tf()->domain()->cnt();
100 uint new_dbg_start = newcall->tf()->domain()->cnt();
101 int jvms_adj = new_dbg_start - old_dbg_start;
102 assert (new_dbg_start == newcall->req(), "argument count mismatch");
103
104 // SafePointScalarObject node could be referenced several times in debug info.
105 // Use Dict to record cloned nodes.
106 Dict* sosn_map = new Dict(cmpkey,hashkey);
107 for (uint i = old_dbg_start; i < oldcall->req(); i++) {
108 Node* old_in = oldcall->in(i);
109 // Clone old SafePointScalarObjectNodes, adjusting their field contents.
110 if (old_in != NULL && old_in->is_SafePointScalarObject()) {
111 SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
112 uint old_unique = C->unique();
113 Node* new_in = old_sosn->clone(sosn_map);
114 if (old_unique != C->unique()) { // New node?
115 new_in->set_req(0, C->root()); // reset control edge
116 new_in = transform_later(new_in); // Register new node.
117 }
118 old_in = new_in;
119 }
120 newcall->add_req(old_in);
121 }
122
123 // JVMS may be shared so clone it before we modify it
124 newcall->set_jvms(oldcall->jvms() != NULL ? oldcall->jvms()->clone_deep(C) : NULL);
125 for (JVMState *jvms = newcall->jvms(); jvms != NULL; jvms = jvms->caller()) {
126 jvms->set_map(newcall);
127 jvms->set_locoff(jvms->locoff()+jvms_adj);
128 jvms->set_stkoff(jvms->stkoff()+jvms_adj);
129 jvms->set_monoff(jvms->monoff()+jvms_adj);
130 jvms->set_scloff(jvms->scloff()+jvms_adj);
131 jvms->set_endoff(jvms->endoff()+jvms_adj);
132 }
133 }
134
opt_bits_test(Node * ctrl,Node * region,int edge,Node * word,int mask,int bits,bool return_fast_path)135 Node* PhaseMacroExpand::opt_bits_test(Node* ctrl, Node* region, int edge, Node* word, int mask, int bits, bool return_fast_path) {
136 Node* cmp;
137 if (mask != 0) {
138 Node* and_node = transform_later(new AndXNode(word, MakeConX(mask)));
139 cmp = transform_later(new CmpXNode(and_node, MakeConX(bits)));
140 } else {
141 cmp = word;
142 }
143 Node* bol = transform_later(new BoolNode(cmp, BoolTest::ne));
144 IfNode* iff = new IfNode( ctrl, bol, PROB_MIN, COUNT_UNKNOWN );
145 transform_later(iff);
146
147 // Fast path taken.
148 Node *fast_taken = transform_later(new IfFalseNode(iff));
149
150 // Fast path not-taken, i.e. slow path
151 Node *slow_taken = transform_later(new IfTrueNode(iff));
152
153 if (return_fast_path) {
154 region->init_req(edge, slow_taken); // Capture slow-control
155 return fast_taken;
156 } else {
157 region->init_req(edge, fast_taken); // Capture fast-control
158 return slow_taken;
159 }
160 }
161
162 //--------------------copy_predefined_input_for_runtime_call--------------------
copy_predefined_input_for_runtime_call(Node * ctrl,CallNode * oldcall,CallNode * call)163 void PhaseMacroExpand::copy_predefined_input_for_runtime_call(Node * ctrl, CallNode* oldcall, CallNode* call) {
164 // Set fixed predefined input arguments
165 call->init_req( TypeFunc::Control, ctrl );
166 call->init_req( TypeFunc::I_O , oldcall->in( TypeFunc::I_O) );
167 call->init_req( TypeFunc::Memory , oldcall->in( TypeFunc::Memory ) ); // ?????
168 call->init_req( TypeFunc::ReturnAdr, oldcall->in( TypeFunc::ReturnAdr ) );
169 call->init_req( TypeFunc::FramePtr, oldcall->in( TypeFunc::FramePtr ) );
170 }
171
172 //------------------------------make_slow_call---------------------------------
make_slow_call(CallNode * oldcall,const TypeFunc * slow_call_type,address slow_call,const char * leaf_name,Node * slow_path,Node * parm0,Node * parm1,Node * parm2)173 CallNode* PhaseMacroExpand::make_slow_call(CallNode *oldcall, const TypeFunc* slow_call_type,
174 address slow_call, const char* leaf_name, Node* slow_path,
175 Node* parm0, Node* parm1, Node* parm2) {
176
177 // Slow-path call
178 CallNode *call = leaf_name
179 ? (CallNode*)new CallLeafNode ( slow_call_type, slow_call, leaf_name, TypeRawPtr::BOTTOM )
180 : (CallNode*)new CallStaticJavaNode( slow_call_type, slow_call, OptoRuntime::stub_name(slow_call), oldcall->jvms()->bci(), TypeRawPtr::BOTTOM );
181
182 // Slow path call has no side-effects, uses few values
183 copy_predefined_input_for_runtime_call(slow_path, oldcall, call );
184 if (parm0 != NULL) call->init_req(TypeFunc::Parms+0, parm0);
185 if (parm1 != NULL) call->init_req(TypeFunc::Parms+1, parm1);
186 if (parm2 != NULL) call->init_req(TypeFunc::Parms+2, parm2);
187 copy_call_debug_info(oldcall, call);
188 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
189 _igvn.replace_node(oldcall, call);
190 transform_later(call);
191
192 return call;
193 }
194
extract_call_projections(CallNode * call)195 void PhaseMacroExpand::extract_call_projections(CallNode *call) {
196 _fallthroughproj = NULL;
197 _fallthroughcatchproj = NULL;
198 _ioproj_fallthrough = NULL;
199 _ioproj_catchall = NULL;
200 _catchallcatchproj = NULL;
201 _memproj_fallthrough = NULL;
202 _memproj_catchall = NULL;
203 _resproj = NULL;
204 for (DUIterator_Fast imax, i = call->fast_outs(imax); i < imax; i++) {
205 ProjNode *pn = call->fast_out(i)->as_Proj();
206 switch (pn->_con) {
207 case TypeFunc::Control:
208 {
209 // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
210 _fallthroughproj = pn;
211 DUIterator_Fast jmax, j = pn->fast_outs(jmax);
212 const Node *cn = pn->fast_out(j);
213 if (cn->is_Catch()) {
214 ProjNode *cpn = NULL;
215 for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
216 cpn = cn->fast_out(k)->as_Proj();
217 assert(cpn->is_CatchProj(), "must be a CatchProjNode");
218 if (cpn->_con == CatchProjNode::fall_through_index)
219 _fallthroughcatchproj = cpn;
220 else {
221 assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
222 _catchallcatchproj = cpn;
223 }
224 }
225 }
226 break;
227 }
228 case TypeFunc::I_O:
229 if (pn->_is_io_use)
230 _ioproj_catchall = pn;
231 else
232 _ioproj_fallthrough = pn;
233 break;
234 case TypeFunc::Memory:
235 if (pn->_is_io_use)
236 _memproj_catchall = pn;
237 else
238 _memproj_fallthrough = pn;
239 break;
240 case TypeFunc::Parms:
241 _resproj = pn;
242 break;
243 default:
244 assert(false, "unexpected projection from allocation node.");
245 }
246 }
247
248 }
249
eliminate_gc_barrier(Node * p2x)250 void PhaseMacroExpand::eliminate_gc_barrier(Node* p2x) {
251 BarrierSetC2 *bs = BarrierSet::barrier_set()->barrier_set_c2();
252 bs->eliminate_gc_barrier(this, p2x);
253 }
254
255 // Search for a memory operation for the specified memory slice.
scan_mem_chain(Node * mem,int alias_idx,int offset,Node * start_mem,Node * alloc,PhaseGVN * phase)256 static Node *scan_mem_chain(Node *mem, int alias_idx, int offset, Node *start_mem, Node *alloc, PhaseGVN *phase) {
257 Node *orig_mem = mem;
258 Node *alloc_mem = alloc->in(TypeFunc::Memory);
259 const TypeOopPtr *tinst = phase->C->get_adr_type(alias_idx)->isa_oopptr();
260 while (true) {
261 if (mem == alloc_mem || mem == start_mem ) {
262 return mem; // hit one of our sentinels
263 } else if (mem->is_MergeMem()) {
264 mem = mem->as_MergeMem()->memory_at(alias_idx);
265 } else if (mem->is_Proj() && mem->as_Proj()->_con == TypeFunc::Memory) {
266 Node *in = mem->in(0);
267 // we can safely skip over safepoints, calls, locks and membars because we
268 // already know that the object is safe to eliminate.
269 if (in->is_Initialize() && in->as_Initialize()->allocation() == alloc) {
270 return in;
271 } else if (in->is_Call()) {
272 CallNode *call = in->as_Call();
273 if (call->may_modify(tinst, phase)) {
274 assert(call->is_ArrayCopy(), "ArrayCopy is the only call node that doesn't make allocation escape");
275 if (call->as_ArrayCopy()->modifies(offset, offset, phase, false)) {
276 return in;
277 }
278 }
279 mem = in->in(TypeFunc::Memory);
280 } else if (in->is_MemBar()) {
281 ArrayCopyNode* ac = NULL;
282 if (ArrayCopyNode::may_modify(tinst, in->as_MemBar(), phase, ac)) {
283 assert(ac != NULL && ac->is_clonebasic(), "Only basic clone is a non escaping clone");
284 return ac;
285 }
286 mem = in->in(TypeFunc::Memory);
287 } else {
288 assert(false, "unexpected projection");
289 }
290 } else if (mem->is_Store()) {
291 const TypePtr* atype = mem->as_Store()->adr_type();
292 int adr_idx = phase->C->get_alias_index(atype);
293 if (adr_idx == alias_idx) {
294 assert(atype->isa_oopptr(), "address type must be oopptr");
295 int adr_offset = atype->offset();
296 uint adr_iid = atype->is_oopptr()->instance_id();
297 // Array elements references have the same alias_idx
298 // but different offset and different instance_id.
299 if (adr_offset == offset && adr_iid == alloc->_idx)
300 return mem;
301 } else {
302 assert(adr_idx == Compile::AliasIdxRaw, "address must match or be raw");
303 }
304 mem = mem->in(MemNode::Memory);
305 } else if (mem->is_ClearArray()) {
306 if (!ClearArrayNode::step_through(&mem, alloc->_idx, phase)) {
307 // Can not bypass initialization of the instance
308 // we are looking.
309 debug_only(intptr_t offset;)
310 assert(alloc == AllocateNode::Ideal_allocation(mem->in(3), phase, offset), "sanity");
311 InitializeNode* init = alloc->as_Allocate()->initialization();
312 // We are looking for stored value, return Initialize node
313 // or memory edge from Allocate node.
314 if (init != NULL)
315 return init;
316 else
317 return alloc->in(TypeFunc::Memory); // It will produce zero value (see callers).
318 }
319 // Otherwise skip it (the call updated 'mem' value).
320 } else if (mem->Opcode() == Op_SCMemProj) {
321 mem = mem->in(0);
322 Node* adr = NULL;
323 if (mem->is_LoadStore()) {
324 adr = mem->in(MemNode::Address);
325 } else {
326 assert(mem->Opcode() == Op_EncodeISOArray ||
327 mem->Opcode() == Op_StrCompressedCopy, "sanity");
328 adr = mem->in(3); // Destination array
329 }
330 const TypePtr* atype = adr->bottom_type()->is_ptr();
331 int adr_idx = phase->C->get_alias_index(atype);
332 if (adr_idx == alias_idx) {
333 DEBUG_ONLY(mem->dump();)
334 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
335 return NULL;
336 }
337 mem = mem->in(MemNode::Memory);
338 } else if (mem->Opcode() == Op_StrInflatedCopy) {
339 Node* adr = mem->in(3); // Destination array
340 const TypePtr* atype = adr->bottom_type()->is_ptr();
341 int adr_idx = phase->C->get_alias_index(atype);
342 if (adr_idx == alias_idx) {
343 DEBUG_ONLY(mem->dump();)
344 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
345 return NULL;
346 }
347 mem = mem->in(MemNode::Memory);
348 } else {
349 return mem;
350 }
351 assert(mem != orig_mem, "dead memory loop");
352 }
353 }
354
355 // Generate loads from source of the arraycopy for fields of
356 // destination needed at a deoptimization point
make_arraycopy_load(ArrayCopyNode * ac,intptr_t offset,Node * ctl,Node * mem,BasicType ft,const Type * ftype,AllocateNode * alloc)357 Node* PhaseMacroExpand::make_arraycopy_load(ArrayCopyNode* ac, intptr_t offset, Node* ctl, Node* mem, BasicType ft, const Type *ftype, AllocateNode *alloc) {
358 BasicType bt = ft;
359 const Type *type = ftype;
360 if (ft == T_NARROWOOP) {
361 bt = T_OBJECT;
362 type = ftype->make_oopptr();
363 }
364 Node* res = NULL;
365 if (ac->is_clonebasic()) {
366 assert(ac->in(ArrayCopyNode::Src) != ac->in(ArrayCopyNode::Dest), "clone source equals destination");
367 Node* base = ac->in(ArrayCopyNode::Src);
368 Node* adr = _igvn.transform(new AddPNode(base, base, MakeConX(offset)));
369 const TypePtr* adr_type = _igvn.type(base)->is_ptr()->add_offset(offset);
370 MergeMemNode* mergemen = MergeMemNode::make(mem);
371 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
372 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
373 } else {
374 if (ac->modifies(offset, offset, &_igvn, true)) {
375 assert(ac->in(ArrayCopyNode::Dest) == alloc->result_cast(), "arraycopy destination should be allocation's result");
376 uint shift = exact_log2(type2aelembytes(bt));
377 Node* src_pos = ac->in(ArrayCopyNode::SrcPos);
378 Node* dest_pos = ac->in(ArrayCopyNode::DestPos);
379 const TypeInt* src_pos_t = _igvn.type(src_pos)->is_int();
380 const TypeInt* dest_pos_t = _igvn.type(dest_pos)->is_int();
381
382 Node* adr = NULL;
383 const TypePtr* adr_type = NULL;
384 if (src_pos_t->is_con() && dest_pos_t->is_con()) {
385 intptr_t off = ((src_pos_t->get_con() - dest_pos_t->get_con()) << shift) + offset;
386 Node* base = ac->in(ArrayCopyNode::Src);
387 adr = _igvn.transform(new AddPNode(base, base, MakeConX(off)));
388 adr_type = _igvn.type(base)->is_ptr()->add_offset(off);
389 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
390 // Don't emit a new load from src if src == dst but try to get the value from memory instead
391 return value_from_mem(ac->in(TypeFunc::Memory), ctl, ft, ftype, adr_type->isa_oopptr(), alloc);
392 }
393 } else {
394 Node* diff = _igvn.transform(new SubINode(ac->in(ArrayCopyNode::SrcPos), ac->in(ArrayCopyNode::DestPos)));
395 #ifdef _LP64
396 diff = _igvn.transform(new ConvI2LNode(diff));
397 #endif
398 diff = _igvn.transform(new LShiftXNode(diff, intcon(shift)));
399
400 Node* off = _igvn.transform(new AddXNode(MakeConX(offset), diff));
401 Node* base = ac->in(ArrayCopyNode::Src);
402 adr = _igvn.transform(new AddPNode(base, base, off));
403 adr_type = _igvn.type(base)->is_ptr()->add_offset(Type::OffsetBot);
404 if (ac->in(ArrayCopyNode::Src) == ac->in(ArrayCopyNode::Dest)) {
405 // Non constant offset in the array: we can't statically
406 // determine the value
407 return NULL;
408 }
409 }
410 MergeMemNode* mergemen = MergeMemNode::make(mem);
411 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
412 res = ArrayCopyNode::load(bs, &_igvn, ctl, mergemen, adr, adr_type, type, bt);
413 }
414 }
415 if (res != NULL) {
416 if (ftype->isa_narrowoop()) {
417 // PhaseMacroExpand::scalar_replacement adds DecodeN nodes
418 res = _igvn.transform(new EncodePNode(res, ftype));
419 }
420 return res;
421 }
422 return NULL;
423 }
424
425 //
426 // Given a Memory Phi, compute a value Phi containing the values from stores
427 // on the input paths.
428 // Note: this function is recursive, its depth is limited by the "level" argument
429 // Returns the computed Phi, or NULL if it cannot compute it.
value_from_mem_phi(Node * mem,BasicType ft,const Type * phi_type,const TypeOopPtr * adr_t,AllocateNode * alloc,Node_Stack * value_phis,int level)430 Node *PhaseMacroExpand::value_from_mem_phi(Node *mem, BasicType ft, const Type *phi_type, const TypeOopPtr *adr_t, AllocateNode *alloc, Node_Stack *value_phis, int level) {
431 assert(mem->is_Phi(), "sanity");
432 int alias_idx = C->get_alias_index(adr_t);
433 int offset = adr_t->offset();
434 int instance_id = adr_t->instance_id();
435
436 // Check if an appropriate value phi already exists.
437 Node* region = mem->in(0);
438 for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
439 Node* phi = region->fast_out(k);
440 if (phi->is_Phi() && phi != mem &&
441 phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
442 return phi;
443 }
444 }
445 // Check if an appropriate new value phi already exists.
446 Node* new_phi = value_phis->find(mem->_idx);
447 if (new_phi != NULL)
448 return new_phi;
449
450 if (level <= 0) {
451 return NULL; // Give up: phi tree too deep
452 }
453 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
454 Node *alloc_mem = alloc->in(TypeFunc::Memory);
455
456 uint length = mem->req();
457 GrowableArray <Node *> values(length, length, NULL, false);
458
459 // create a new Phi for the value
460 PhiNode *phi = new PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
461 transform_later(phi);
462 value_phis->push(phi, mem->_idx);
463
464 for (uint j = 1; j < length; j++) {
465 Node *in = mem->in(j);
466 if (in == NULL || in->is_top()) {
467 values.at_put(j, in);
468 } else {
469 Node *val = scan_mem_chain(in, alias_idx, offset, start_mem, alloc, &_igvn);
470 if (val == start_mem || val == alloc_mem) {
471 // hit a sentinel, return appropriate 0 value
472 values.at_put(j, _igvn.zerocon(ft));
473 continue;
474 }
475 if (val->is_Initialize()) {
476 val = val->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
477 }
478 if (val == NULL) {
479 return NULL; // can't find a value on this path
480 }
481 if (val == mem) {
482 values.at_put(j, mem);
483 } else if (val->is_Store()) {
484 Node* n = val->in(MemNode::ValueIn);
485 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
486 n = bs->step_over_gc_barrier(n);
487 values.at_put(j, n);
488 } else if(val->is_Proj() && val->in(0) == alloc) {
489 values.at_put(j, _igvn.zerocon(ft));
490 } else if (val->is_Phi()) {
491 val = value_from_mem_phi(val, ft, phi_type, adr_t, alloc, value_phis, level-1);
492 if (val == NULL) {
493 return NULL;
494 }
495 values.at_put(j, val);
496 } else if (val->Opcode() == Op_SCMemProj) {
497 assert(val->in(0)->is_LoadStore() ||
498 val->in(0)->Opcode() == Op_EncodeISOArray ||
499 val->in(0)->Opcode() == Op_StrCompressedCopy, "sanity");
500 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
501 return NULL;
502 } else if (val->is_ArrayCopy()) {
503 Node* res = make_arraycopy_load(val->as_ArrayCopy(), offset, val->in(0), val->in(TypeFunc::Memory), ft, phi_type, alloc);
504 if (res == NULL) {
505 return NULL;
506 }
507 values.at_put(j, res);
508 } else {
509 #ifdef ASSERT
510 val->dump();
511 assert(false, "unknown node on this path");
512 #endif
513 return NULL; // unknown node on this path
514 }
515 }
516 }
517 // Set Phi's inputs
518 for (uint j = 1; j < length; j++) {
519 if (values.at(j) == mem) {
520 phi->init_req(j, phi);
521 } else {
522 phi->init_req(j, values.at(j));
523 }
524 }
525 return phi;
526 }
527
528 // Search the last value stored into the object's field.
value_from_mem(Node * sfpt_mem,Node * sfpt_ctl,BasicType ft,const Type * ftype,const TypeOopPtr * adr_t,AllocateNode * alloc)529 Node *PhaseMacroExpand::value_from_mem(Node *sfpt_mem, Node *sfpt_ctl, BasicType ft, const Type *ftype, const TypeOopPtr *adr_t, AllocateNode *alloc) {
530 assert(adr_t->is_known_instance_field(), "instance required");
531 int instance_id = adr_t->instance_id();
532 assert((uint)instance_id == alloc->_idx, "wrong allocation");
533
534 int alias_idx = C->get_alias_index(adr_t);
535 int offset = adr_t->offset();
536 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
537 Node *alloc_ctrl = alloc->in(TypeFunc::Control);
538 Node *alloc_mem = alloc->in(TypeFunc::Memory);
539 Arena *a = Thread::current()->resource_area();
540 VectorSet visited(a);
541
542 bool done = sfpt_mem == alloc_mem;
543 Node *mem = sfpt_mem;
544 while (!done) {
545 if (visited.test_set(mem->_idx)) {
546 return NULL; // found a loop, give up
547 }
548 mem = scan_mem_chain(mem, alias_idx, offset, start_mem, alloc, &_igvn);
549 if (mem == start_mem || mem == alloc_mem) {
550 done = true; // hit a sentinel, return appropriate 0 value
551 } else if (mem->is_Initialize()) {
552 mem = mem->as_Initialize()->find_captured_store(offset, type2aelembytes(ft), &_igvn);
553 if (mem == NULL) {
554 done = true; // Something go wrong.
555 } else if (mem->is_Store()) {
556 const TypePtr* atype = mem->as_Store()->adr_type();
557 assert(C->get_alias_index(atype) == Compile::AliasIdxRaw, "store is correct memory slice");
558 done = true;
559 }
560 } else if (mem->is_Store()) {
561 const TypeOopPtr* atype = mem->as_Store()->adr_type()->isa_oopptr();
562 assert(atype != NULL, "address type must be oopptr");
563 assert(C->get_alias_index(atype) == alias_idx &&
564 atype->is_known_instance_field() && atype->offset() == offset &&
565 atype->instance_id() == instance_id, "store is correct memory slice");
566 done = true;
567 } else if (mem->is_Phi()) {
568 // try to find a phi's unique input
569 Node *unique_input = NULL;
570 Node *top = C->top();
571 for (uint i = 1; i < mem->req(); i++) {
572 Node *n = scan_mem_chain(mem->in(i), alias_idx, offset, start_mem, alloc, &_igvn);
573 if (n == NULL || n == top || n == mem) {
574 continue;
575 } else if (unique_input == NULL) {
576 unique_input = n;
577 } else if (unique_input != n) {
578 unique_input = top;
579 break;
580 }
581 }
582 if (unique_input != NULL && unique_input != top) {
583 mem = unique_input;
584 } else {
585 done = true;
586 }
587 } else if (mem->is_ArrayCopy()) {
588 done = true;
589 } else {
590 assert(false, "unexpected node");
591 }
592 }
593 if (mem != NULL) {
594 if (mem == start_mem || mem == alloc_mem) {
595 // hit a sentinel, return appropriate 0 value
596 return _igvn.zerocon(ft);
597 } else if (mem->is_Store()) {
598 Node* n = mem->in(MemNode::ValueIn);
599 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
600 n = bs->step_over_gc_barrier(n);
601 return n;
602 } else if (mem->is_Phi()) {
603 // attempt to produce a Phi reflecting the values on the input paths of the Phi
604 Node_Stack value_phis(a, 8);
605 Node * phi = value_from_mem_phi(mem, ft, ftype, adr_t, alloc, &value_phis, ValueSearchLimit);
606 if (phi != NULL) {
607 return phi;
608 } else {
609 // Kill all new Phis
610 while(value_phis.is_nonempty()) {
611 Node* n = value_phis.node();
612 _igvn.replace_node(n, C->top());
613 value_phis.pop();
614 }
615 }
616 } else if (mem->is_ArrayCopy()) {
617 Node* ctl = mem->in(0);
618 Node* m = mem->in(TypeFunc::Memory);
619 if (sfpt_ctl->is_Proj() && sfpt_ctl->as_Proj()->is_uncommon_trap_proj(Deoptimization::Reason_none)) {
620 // pin the loads in the uncommon trap path
621 ctl = sfpt_ctl;
622 m = sfpt_mem;
623 }
624 return make_arraycopy_load(mem->as_ArrayCopy(), offset, ctl, m, ft, ftype, alloc);
625 }
626 }
627 // Something go wrong.
628 return NULL;
629 }
630
631 // Check the possibility of scalar replacement.
can_eliminate_allocation(AllocateNode * alloc,GrowableArray<SafePointNode * > & safepoints)632 bool PhaseMacroExpand::can_eliminate_allocation(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
633 // Scan the uses of the allocation to check for anything that would
634 // prevent us from eliminating it.
635 NOT_PRODUCT( const char* fail_eliminate = NULL; )
636 DEBUG_ONLY( Node* disq_node = NULL; )
637 bool can_eliminate = true;
638
639 Node* res = alloc->result_cast();
640 const TypeOopPtr* res_type = NULL;
641 if (res == NULL) {
642 // All users were eliminated.
643 } else if (!res->is_CheckCastPP()) {
644 NOT_PRODUCT(fail_eliminate = "Allocation does not have unique CheckCastPP";)
645 can_eliminate = false;
646 } else {
647 res_type = _igvn.type(res)->isa_oopptr();
648 if (res_type == NULL) {
649 NOT_PRODUCT(fail_eliminate = "Neither instance or array allocation";)
650 can_eliminate = false;
651 } else if (res_type->isa_aryptr()) {
652 int length = alloc->in(AllocateNode::ALength)->find_int_con(-1);
653 if (length < 0) {
654 NOT_PRODUCT(fail_eliminate = "Array's size is not constant";)
655 can_eliminate = false;
656 }
657 }
658 }
659
660 if (can_eliminate && res != NULL) {
661 for (DUIterator_Fast jmax, j = res->fast_outs(jmax);
662 j < jmax && can_eliminate; j++) {
663 Node* use = res->fast_out(j);
664
665 if (use->is_AddP()) {
666 const TypePtr* addp_type = _igvn.type(use)->is_ptr();
667 int offset = addp_type->offset();
668
669 if (offset == Type::OffsetTop || offset == Type::OffsetBot) {
670 NOT_PRODUCT(fail_eliminate = "Undefined field referrence";)
671 can_eliminate = false;
672 break;
673 }
674 for (DUIterator_Fast kmax, k = use->fast_outs(kmax);
675 k < kmax && can_eliminate; k++) {
676 Node* n = use->fast_out(k);
677 if (!n->is_Store() && n->Opcode() != Op_CastP2X
678 SHENANDOAHGC_ONLY(&& (!UseShenandoahGC || !ShenandoahBarrierSetC2::is_shenandoah_wb_pre_call(n))) ) {
679 DEBUG_ONLY(disq_node = n;)
680 if (n->is_Load() || n->is_LoadStore()) {
681 NOT_PRODUCT(fail_eliminate = "Field load";)
682 } else {
683 NOT_PRODUCT(fail_eliminate = "Not store field referrence";)
684 }
685 can_eliminate = false;
686 }
687 }
688 } else if (use->is_ArrayCopy() &&
689 (use->as_ArrayCopy()->is_clonebasic() ||
690 use->as_ArrayCopy()->is_arraycopy_validated() ||
691 use->as_ArrayCopy()->is_copyof_validated() ||
692 use->as_ArrayCopy()->is_copyofrange_validated()) &&
693 use->in(ArrayCopyNode::Dest) == res) {
694 // ok to eliminate
695 } else if (use->is_SafePoint()) {
696 SafePointNode* sfpt = use->as_SafePoint();
697 if (sfpt->is_Call() && sfpt->as_Call()->has_non_debug_use(res)) {
698 // Object is passed as argument.
699 DEBUG_ONLY(disq_node = use;)
700 NOT_PRODUCT(fail_eliminate = "Object is passed as argument";)
701 can_eliminate = false;
702 }
703 Node* sfptMem = sfpt->memory();
704 if (sfptMem == NULL || sfptMem->is_top()) {
705 DEBUG_ONLY(disq_node = use;)
706 NOT_PRODUCT(fail_eliminate = "NULL or TOP memory";)
707 can_eliminate = false;
708 } else {
709 safepoints.append_if_missing(sfpt);
710 }
711 } else if (use->Opcode() != Op_CastP2X) { // CastP2X is used by card mark
712 if (use->is_Phi()) {
713 if (use->outcnt() == 1 && use->unique_out()->Opcode() == Op_Return) {
714 NOT_PRODUCT(fail_eliminate = "Object is return value";)
715 } else {
716 NOT_PRODUCT(fail_eliminate = "Object is referenced by Phi";)
717 }
718 DEBUG_ONLY(disq_node = use;)
719 } else {
720 if (use->Opcode() == Op_Return) {
721 NOT_PRODUCT(fail_eliminate = "Object is return value";)
722 }else {
723 NOT_PRODUCT(fail_eliminate = "Object is referenced by node";)
724 }
725 DEBUG_ONLY(disq_node = use;)
726 }
727 can_eliminate = false;
728 }
729 }
730 }
731
732 #ifndef PRODUCT
733 if (PrintEliminateAllocations) {
734 if (can_eliminate) {
735 tty->print("Scalar ");
736 if (res == NULL)
737 alloc->dump();
738 else
739 res->dump();
740 } else if (alloc->_is_scalar_replaceable) {
741 tty->print("NotScalar (%s)", fail_eliminate);
742 if (res == NULL)
743 alloc->dump();
744 else
745 res->dump();
746 #ifdef ASSERT
747 if (disq_node != NULL) {
748 tty->print(" >>>> ");
749 disq_node->dump();
750 }
751 #endif /*ASSERT*/
752 }
753 }
754 #endif
755 return can_eliminate;
756 }
757
758 // Do scalar replacement.
scalar_replacement(AllocateNode * alloc,GrowableArray<SafePointNode * > & safepoints)759 bool PhaseMacroExpand::scalar_replacement(AllocateNode *alloc, GrowableArray <SafePointNode *>& safepoints) {
760 GrowableArray <SafePointNode *> safepoints_done;
761
762 ciKlass* klass = NULL;
763 ciInstanceKlass* iklass = NULL;
764 int nfields = 0;
765 int array_base = 0;
766 int element_size = 0;
767 BasicType basic_elem_type = T_ILLEGAL;
768 ciType* elem_type = NULL;
769
770 Node* res = alloc->result_cast();
771 assert(res == NULL || res->is_CheckCastPP(), "unexpected AllocateNode result");
772 const TypeOopPtr* res_type = NULL;
773 if (res != NULL) { // Could be NULL when there are no users
774 res_type = _igvn.type(res)->isa_oopptr();
775 }
776
777 if (res != NULL) {
778 klass = res_type->klass();
779 if (res_type->isa_instptr()) {
780 // find the fields of the class which will be needed for safepoint debug information
781 assert(klass->is_instance_klass(), "must be an instance klass.");
782 iklass = klass->as_instance_klass();
783 nfields = iklass->nof_nonstatic_fields();
784 } else {
785 // find the array's elements which will be needed for safepoint debug information
786 nfields = alloc->in(AllocateNode::ALength)->find_int_con(-1);
787 assert(klass->is_array_klass() && nfields >= 0, "must be an array klass.");
788 elem_type = klass->as_array_klass()->element_type();
789 basic_elem_type = elem_type->basic_type();
790 array_base = arrayOopDesc::base_offset_in_bytes(basic_elem_type);
791 element_size = type2aelembytes(basic_elem_type);
792 }
793 }
794 //
795 // Process the safepoint uses
796 //
797 while (safepoints.length() > 0) {
798 SafePointNode* sfpt = safepoints.pop();
799 Node* mem = sfpt->memory();
800 Node* ctl = sfpt->control();
801 assert(sfpt->jvms() != NULL, "missed JVMS");
802 // Fields of scalar objs are referenced only at the end
803 // of regular debuginfo at the last (youngest) JVMS.
804 // Record relative start index.
805 uint first_ind = (sfpt->req() - sfpt->jvms()->scloff());
806 SafePointScalarObjectNode* sobj = new SafePointScalarObjectNode(res_type,
807 #ifdef ASSERT
808 alloc,
809 #endif
810 first_ind, nfields);
811 sobj->init_req(0, C->root());
812 transform_later(sobj);
813
814 // Scan object's fields adding an input to the safepoint for each field.
815 for (int j = 0; j < nfields; j++) {
816 intptr_t offset;
817 ciField* field = NULL;
818 if (iklass != NULL) {
819 field = iklass->nonstatic_field_at(j);
820 offset = field->offset();
821 elem_type = field->type();
822 basic_elem_type = field->layout_type();
823 } else {
824 offset = array_base + j * (intptr_t)element_size;
825 }
826
827 const Type *field_type;
828 // The next code is taken from Parse::do_get_xxx().
829 if (is_reference_type(basic_elem_type)) {
830 if (!elem_type->is_loaded()) {
831 field_type = TypeInstPtr::BOTTOM;
832 } else if (field != NULL && field->is_static_constant()) {
833 // This can happen if the constant oop is non-perm.
834 ciObject* con = field->constant_value().as_object();
835 // Do not "join" in the previous type; it doesn't add value,
836 // and may yield a vacuous result if the field is of interface type.
837 field_type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
838 assert(field_type != NULL, "field singleton type must be consistent");
839 } else {
840 field_type = TypeOopPtr::make_from_klass(elem_type->as_klass());
841 }
842 if (UseCompressedOops) {
843 field_type = field_type->make_narrowoop();
844 basic_elem_type = T_NARROWOOP;
845 }
846 } else {
847 field_type = Type::get_const_basic_type(basic_elem_type);
848 }
849
850 const TypeOopPtr *field_addr_type = res_type->add_offset(offset)->isa_oopptr();
851
852 Node *field_val = value_from_mem(mem, ctl, basic_elem_type, field_type, field_addr_type, alloc);
853 if (field_val == NULL) {
854 // We weren't able to find a value for this field,
855 // give up on eliminating this allocation.
856
857 // Remove any extra entries we added to the safepoint.
858 uint last = sfpt->req() - 1;
859 for (int k = 0; k < j; k++) {
860 sfpt->del_req(last--);
861 }
862 _igvn._worklist.push(sfpt);
863 // rollback processed safepoints
864 while (safepoints_done.length() > 0) {
865 SafePointNode* sfpt_done = safepoints_done.pop();
866 // remove any extra entries we added to the safepoint
867 last = sfpt_done->req() - 1;
868 for (int k = 0; k < nfields; k++) {
869 sfpt_done->del_req(last--);
870 }
871 JVMState *jvms = sfpt_done->jvms();
872 jvms->set_endoff(sfpt_done->req());
873 // Now make a pass over the debug information replacing any references
874 // to SafePointScalarObjectNode with the allocated object.
875 int start = jvms->debug_start();
876 int end = jvms->debug_end();
877 for (int i = start; i < end; i++) {
878 if (sfpt_done->in(i)->is_SafePointScalarObject()) {
879 SafePointScalarObjectNode* scobj = sfpt_done->in(i)->as_SafePointScalarObject();
880 if (scobj->first_index(jvms) == sfpt_done->req() &&
881 scobj->n_fields() == (uint)nfields) {
882 assert(scobj->alloc() == alloc, "sanity");
883 sfpt_done->set_req(i, res);
884 }
885 }
886 }
887 _igvn._worklist.push(sfpt_done);
888 }
889 #ifndef PRODUCT
890 if (PrintEliminateAllocations) {
891 if (field != NULL) {
892 tty->print("=== At SafePoint node %d can't find value of Field: ",
893 sfpt->_idx);
894 field->print();
895 int field_idx = C->get_alias_index(field_addr_type);
896 tty->print(" (alias_idx=%d)", field_idx);
897 } else { // Array's element
898 tty->print("=== At SafePoint node %d can't find value of array element [%d]",
899 sfpt->_idx, j);
900 }
901 tty->print(", which prevents elimination of: ");
902 if (res == NULL)
903 alloc->dump();
904 else
905 res->dump();
906 }
907 #endif
908 return false;
909 }
910 if (UseCompressedOops && field_type->isa_narrowoop()) {
911 // Enable "DecodeN(EncodeP(Allocate)) --> Allocate" transformation
912 // to be able scalar replace the allocation.
913 if (field_val->is_EncodeP()) {
914 field_val = field_val->in(1);
915 } else {
916 field_val = transform_later(new DecodeNNode(field_val, field_val->get_ptr_type()));
917 }
918 }
919 sfpt->add_req(field_val);
920 }
921 JVMState *jvms = sfpt->jvms();
922 jvms->set_endoff(sfpt->req());
923 // Now make a pass over the debug information replacing any references
924 // to the allocated object with "sobj"
925 int start = jvms->debug_start();
926 int end = jvms->debug_end();
927 sfpt->replace_edges_in_range(res, sobj, start, end);
928 _igvn._worklist.push(sfpt);
929 safepoints_done.append_if_missing(sfpt); // keep it for rollback
930 }
931 return true;
932 }
933
disconnect_projections(MultiNode * n,PhaseIterGVN & igvn)934 static void disconnect_projections(MultiNode* n, PhaseIterGVN& igvn) {
935 Node* ctl_proj = n->proj_out_or_null(TypeFunc::Control);
936 Node* mem_proj = n->proj_out_or_null(TypeFunc::Memory);
937 if (ctl_proj != NULL) {
938 igvn.replace_node(ctl_proj, n->in(0));
939 }
940 if (mem_proj != NULL) {
941 igvn.replace_node(mem_proj, n->in(TypeFunc::Memory));
942 }
943 }
944
945 // Process users of eliminated allocation.
process_users_of_allocation(CallNode * alloc)946 void PhaseMacroExpand::process_users_of_allocation(CallNode *alloc) {
947 Node* res = alloc->result_cast();
948 if (res != NULL) {
949 for (DUIterator_Last jmin, j = res->last_outs(jmin); j >= jmin; ) {
950 Node *use = res->last_out(j);
951 uint oc1 = res->outcnt();
952
953 if (use->is_AddP()) {
954 for (DUIterator_Last kmin, k = use->last_outs(kmin); k >= kmin; ) {
955 Node *n = use->last_out(k);
956 uint oc2 = use->outcnt();
957 if (n->is_Store()) {
958 #ifdef ASSERT
959 // Verify that there is no dependent MemBarVolatile nodes,
960 // they should be removed during IGVN, see MemBarNode::Ideal().
961 for (DUIterator_Fast pmax, p = n->fast_outs(pmax);
962 p < pmax; p++) {
963 Node* mb = n->fast_out(p);
964 assert(mb->is_Initialize() || !mb->is_MemBar() ||
965 mb->req() <= MemBarNode::Precedent ||
966 mb->in(MemBarNode::Precedent) != n,
967 "MemBarVolatile should be eliminated for non-escaping object");
968 }
969 #endif
970 _igvn.replace_node(n, n->in(MemNode::Memory));
971 } else {
972 eliminate_gc_barrier(n);
973 }
974 k -= (oc2 - use->outcnt());
975 }
976 _igvn.remove_dead_node(use);
977 } else if (use->is_ArrayCopy()) {
978 // Disconnect ArrayCopy node
979 ArrayCopyNode* ac = use->as_ArrayCopy();
980 if (ac->is_clonebasic()) {
981 Node* membar_after = ac->proj_out(TypeFunc::Control)->unique_ctrl_out();
982 disconnect_projections(ac, _igvn);
983 assert(alloc->in(TypeFunc::Memory)->is_Proj() && alloc->in(TypeFunc::Memory)->in(0)->Opcode() == Op_MemBarCPUOrder, "mem barrier expected before allocation");
984 Node* membar_before = alloc->in(TypeFunc::Memory)->in(0);
985 disconnect_projections(membar_before->as_MemBar(), _igvn);
986 if (membar_after->is_MemBar()) {
987 disconnect_projections(membar_after->as_MemBar(), _igvn);
988 }
989 } else {
990 assert(ac->is_arraycopy_validated() ||
991 ac->is_copyof_validated() ||
992 ac->is_copyofrange_validated(), "unsupported");
993 CallProjections callprojs;
994 ac->extract_projections(&callprojs, true);
995
996 _igvn.replace_node(callprojs.fallthrough_ioproj, ac->in(TypeFunc::I_O));
997 _igvn.replace_node(callprojs.fallthrough_memproj, ac->in(TypeFunc::Memory));
998 _igvn.replace_node(callprojs.fallthrough_catchproj, ac->in(TypeFunc::Control));
999
1000 // Set control to top. IGVN will remove the remaining projections
1001 ac->set_req(0, top());
1002 ac->replace_edge(res, top());
1003
1004 // Disconnect src right away: it can help find new
1005 // opportunities for allocation elimination
1006 Node* src = ac->in(ArrayCopyNode::Src);
1007 ac->replace_edge(src, top());
1008 // src can be top at this point if src and dest of the
1009 // arraycopy were the same
1010 if (src->outcnt() == 0 && !src->is_top()) {
1011 _igvn.remove_dead_node(src);
1012 }
1013 }
1014 _igvn._worklist.push(ac);
1015 } else {
1016 eliminate_gc_barrier(use);
1017 }
1018 j -= (oc1 - res->outcnt());
1019 }
1020 assert(res->outcnt() == 0, "all uses of allocated objects must be deleted");
1021 _igvn.remove_dead_node(res);
1022 }
1023
1024 //
1025 // Process other users of allocation's projections
1026 //
1027 if (_resproj != NULL && _resproj->outcnt() != 0) {
1028 // First disconnect stores captured by Initialize node.
1029 // If Initialize node is eliminated first in the following code,
1030 // it will kill such stores and DUIterator_Last will assert.
1031 for (DUIterator_Fast jmax, j = _resproj->fast_outs(jmax); j < jmax; j++) {
1032 Node *use = _resproj->fast_out(j);
1033 if (use->is_AddP()) {
1034 // raw memory addresses used only by the initialization
1035 _igvn.replace_node(use, C->top());
1036 --j; --jmax;
1037 }
1038 }
1039 for (DUIterator_Last jmin, j = _resproj->last_outs(jmin); j >= jmin; ) {
1040 Node *use = _resproj->last_out(j);
1041 uint oc1 = _resproj->outcnt();
1042 if (use->is_Initialize()) {
1043 // Eliminate Initialize node.
1044 InitializeNode *init = use->as_Initialize();
1045 assert(init->outcnt() <= 2, "only a control and memory projection expected");
1046 Node *ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1047 if (ctrl_proj != NULL) {
1048 _igvn.replace_node(ctrl_proj, init->in(TypeFunc::Control));
1049 #ifdef ASSERT
1050 Node* tmp = init->in(TypeFunc::Control);
1051 assert(tmp == _fallthroughcatchproj, "allocation control projection");
1052 #endif
1053 }
1054 Node *mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1055 if (mem_proj != NULL) {
1056 Node *mem = init->in(TypeFunc::Memory);
1057 #ifdef ASSERT
1058 if (mem->is_MergeMem()) {
1059 assert(mem->in(TypeFunc::Memory) == _memproj_fallthrough, "allocation memory projection");
1060 } else {
1061 assert(mem == _memproj_fallthrough, "allocation memory projection");
1062 }
1063 #endif
1064 _igvn.replace_node(mem_proj, mem);
1065 }
1066 } else {
1067 assert(false, "only Initialize or AddP expected");
1068 }
1069 j -= (oc1 - _resproj->outcnt());
1070 }
1071 }
1072 if (_fallthroughcatchproj != NULL) {
1073 _igvn.replace_node(_fallthroughcatchproj, alloc->in(TypeFunc::Control));
1074 }
1075 if (_memproj_fallthrough != NULL) {
1076 _igvn.replace_node(_memproj_fallthrough, alloc->in(TypeFunc::Memory));
1077 }
1078 if (_memproj_catchall != NULL) {
1079 _igvn.replace_node(_memproj_catchall, C->top());
1080 }
1081 if (_ioproj_fallthrough != NULL) {
1082 _igvn.replace_node(_ioproj_fallthrough, alloc->in(TypeFunc::I_O));
1083 }
1084 if (_ioproj_catchall != NULL) {
1085 _igvn.replace_node(_ioproj_catchall, C->top());
1086 }
1087 if (_catchallcatchproj != NULL) {
1088 _igvn.replace_node(_catchallcatchproj, C->top());
1089 }
1090 }
1091
eliminate_allocate_node(AllocateNode * alloc)1092 bool PhaseMacroExpand::eliminate_allocate_node(AllocateNode *alloc) {
1093 // Don't do scalar replacement if the frame can be popped by JVMTI:
1094 // if reallocation fails during deoptimization we'll pop all
1095 // interpreter frames for this compiled frame and that won't play
1096 // nice with JVMTI popframe.
1097 if (!EliminateAllocations || JvmtiExport::can_pop_frame() || !alloc->_is_non_escaping) {
1098 return false;
1099 }
1100 Node* klass = alloc->in(AllocateNode::KlassNode);
1101 const TypeKlassPtr* tklass = _igvn.type(klass)->is_klassptr();
1102 Node* res = alloc->result_cast();
1103 // Eliminate boxing allocations which are not used
1104 // regardless scalar replacable status.
1105 bool boxing_alloc = C->eliminate_boxing() &&
1106 tklass->klass()->is_instance_klass() &&
1107 tklass->klass()->as_instance_klass()->is_box_klass();
1108 if (!alloc->_is_scalar_replaceable && (!boxing_alloc || (res != NULL))) {
1109 return false;
1110 }
1111
1112 extract_call_projections(alloc);
1113
1114 GrowableArray <SafePointNode *> safepoints;
1115 if (!can_eliminate_allocation(alloc, safepoints)) {
1116 return false;
1117 }
1118
1119 if (!alloc->_is_scalar_replaceable) {
1120 assert(res == NULL, "sanity");
1121 // We can only eliminate allocation if all debug info references
1122 // are already replaced with SafePointScalarObject because
1123 // we can't search for a fields value without instance_id.
1124 if (safepoints.length() > 0) {
1125 return false;
1126 }
1127 }
1128
1129 if (!scalar_replacement(alloc, safepoints)) {
1130 return false;
1131 }
1132
1133 CompileLog* log = C->log();
1134 if (log != NULL) {
1135 log->head("eliminate_allocation type='%d'",
1136 log->identify(tklass->klass()));
1137 JVMState* p = alloc->jvms();
1138 while (p != NULL) {
1139 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1140 p = p->caller();
1141 }
1142 log->tail("eliminate_allocation");
1143 }
1144
1145 process_users_of_allocation(alloc);
1146
1147 #ifndef PRODUCT
1148 if (PrintEliminateAllocations) {
1149 if (alloc->is_AllocateArray())
1150 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1151 else
1152 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1153 }
1154 #endif
1155
1156 return true;
1157 }
1158
eliminate_boxing_node(CallStaticJavaNode * boxing)1159 bool PhaseMacroExpand::eliminate_boxing_node(CallStaticJavaNode *boxing) {
1160 // EA should remove all uses of non-escaping boxing node.
1161 if (!C->eliminate_boxing() || boxing->proj_out_or_null(TypeFunc::Parms) != NULL) {
1162 return false;
1163 }
1164
1165 assert(boxing->result_cast() == NULL, "unexpected boxing node result");
1166
1167 extract_call_projections(boxing);
1168
1169 const TypeTuple* r = boxing->tf()->range();
1170 assert(r->cnt() > TypeFunc::Parms, "sanity");
1171 const TypeInstPtr* t = r->field_at(TypeFunc::Parms)->isa_instptr();
1172 assert(t != NULL, "sanity");
1173
1174 CompileLog* log = C->log();
1175 if (log != NULL) {
1176 log->head("eliminate_boxing type='%d'",
1177 log->identify(t->klass()));
1178 JVMState* p = boxing->jvms();
1179 while (p != NULL) {
1180 log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1181 p = p->caller();
1182 }
1183 log->tail("eliminate_boxing");
1184 }
1185
1186 process_users_of_allocation(boxing);
1187
1188 #ifndef PRODUCT
1189 if (PrintEliminateAllocations) {
1190 tty->print("++++ Eliminated: %d ", boxing->_idx);
1191 boxing->method()->print_short_name(tty);
1192 tty->cr();
1193 }
1194 #endif
1195
1196 return true;
1197 }
1198
1199 //---------------------------set_eden_pointers-------------------------
set_eden_pointers(Node * & eden_top_adr,Node * & eden_end_adr)1200 void PhaseMacroExpand::set_eden_pointers(Node* &eden_top_adr, Node* &eden_end_adr) {
1201 if (UseTLAB) { // Private allocation: load from TLS
1202 Node* thread = transform_later(new ThreadLocalNode());
1203 int tlab_top_offset = in_bytes(JavaThread::tlab_top_offset());
1204 int tlab_end_offset = in_bytes(JavaThread::tlab_end_offset());
1205 eden_top_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_top_offset);
1206 eden_end_adr = basic_plus_adr(top()/*not oop*/, thread, tlab_end_offset);
1207 } else { // Shared allocation: load from globals
1208 CollectedHeap* ch = Universe::heap();
1209 address top_adr = (address)ch->top_addr();
1210 address end_adr = (address)ch->end_addr();
1211 eden_top_adr = makecon(TypeRawPtr::make(top_adr));
1212 eden_end_adr = basic_plus_adr(eden_top_adr, end_adr - top_adr);
1213 }
1214 }
1215
1216
make_load(Node * ctl,Node * mem,Node * base,int offset,const Type * value_type,BasicType bt)1217 Node* PhaseMacroExpand::make_load(Node* ctl, Node* mem, Node* base, int offset, const Type* value_type, BasicType bt) {
1218 Node* adr = basic_plus_adr(base, offset);
1219 const TypePtr* adr_type = adr->bottom_type()->is_ptr();
1220 Node* value = LoadNode::make(_igvn, ctl, mem, adr, adr_type, value_type, bt, MemNode::unordered);
1221 transform_later(value);
1222 return value;
1223 }
1224
1225
make_store(Node * ctl,Node * mem,Node * base,int offset,Node * value,BasicType bt)1226 Node* PhaseMacroExpand::make_store(Node* ctl, Node* mem, Node* base, int offset, Node* value, BasicType bt) {
1227 Node* adr = basic_plus_adr(base, offset);
1228 mem = StoreNode::make(_igvn, ctl, mem, adr, NULL, value, bt, MemNode::unordered);
1229 transform_later(mem);
1230 return mem;
1231 }
1232
1233 //=============================================================================
1234 //
1235 // A L L O C A T I O N
1236 //
1237 // Allocation attempts to be fast in the case of frequent small objects.
1238 // It breaks down like this:
1239 //
1240 // 1) Size in doublewords is computed. This is a constant for objects and
1241 // variable for most arrays. Doubleword units are used to avoid size
1242 // overflow of huge doubleword arrays. We need doublewords in the end for
1243 // rounding.
1244 //
1245 // 2) Size is checked for being 'too large'. Too-large allocations will go
1246 // the slow path into the VM. The slow path can throw any required
1247 // exceptions, and does all the special checks for very large arrays. The
1248 // size test can constant-fold away for objects. For objects with
1249 // finalizers it constant-folds the otherway: you always go slow with
1250 // finalizers.
1251 //
1252 // 3) If NOT using TLABs, this is the contended loop-back point.
1253 // Load-Locked the heap top. If using TLABs normal-load the heap top.
1254 //
1255 // 4) Check that heap top + size*8 < max. If we fail go the slow ` route.
1256 // NOTE: "top+size*8" cannot wrap the 4Gig line! Here's why: for largish
1257 // "size*8" we always enter the VM, where "largish" is a constant picked small
1258 // enough that there's always space between the eden max and 4Gig (old space is
1259 // there so it's quite large) and large enough that the cost of entering the VM
1260 // is dwarfed by the cost to initialize the space.
1261 //
1262 // 5) If NOT using TLABs, Store-Conditional the adjusted heap top back
1263 // down. If contended, repeat at step 3. If using TLABs normal-store
1264 // adjusted heap top back down; there is no contention.
1265 //
1266 // 6) If !ZeroTLAB then Bulk-clear the object/array. Fill in klass & mark
1267 // fields.
1268 //
1269 // 7) Merge with the slow-path; cast the raw memory pointer to the correct
1270 // oop flavor.
1271 //
1272 //=============================================================================
1273 // FastAllocateSizeLimit value is in DOUBLEWORDS.
1274 // Allocations bigger than this always go the slow route.
1275 // This value must be small enough that allocation attempts that need to
1276 // trigger exceptions go the slow route. Also, it must be small enough so
1277 // that heap_top + size_in_bytes does not wrap around the 4Gig limit.
1278 //=============================================================================j//
1279 // %%% Here is an old comment from parseHelper.cpp; is it outdated?
1280 // The allocator will coalesce int->oop copies away. See comment in
1281 // coalesce.cpp about how this works. It depends critically on the exact
1282 // code shape produced here, so if you are changing this code shape
1283 // make sure the GC info for the heap-top is correct in and around the
1284 // slow-path call.
1285 //
1286
expand_allocate_common(AllocateNode * alloc,Node * length,const TypeFunc * slow_call_type,address slow_call_address)1287 void PhaseMacroExpand::expand_allocate_common(
1288 AllocateNode* alloc, // allocation node to be expanded
1289 Node* length, // array length for an array allocation
1290 const TypeFunc* slow_call_type, // Type of slow call
1291 address slow_call_address // Address of slow call
1292 )
1293 {
1294 Node* ctrl = alloc->in(TypeFunc::Control);
1295 Node* mem = alloc->in(TypeFunc::Memory);
1296 Node* i_o = alloc->in(TypeFunc::I_O);
1297 Node* size_in_bytes = alloc->in(AllocateNode::AllocSize);
1298 Node* klass_node = alloc->in(AllocateNode::KlassNode);
1299 Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
1300 assert(ctrl != NULL, "must have control");
1301
1302 // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
1303 // they will not be used if "always_slow" is set
1304 enum { slow_result_path = 1, fast_result_path = 2 };
1305 Node *result_region = NULL;
1306 Node *result_phi_rawmem = NULL;
1307 Node *result_phi_rawoop = NULL;
1308 Node *result_phi_i_o = NULL;
1309
1310 // The initial slow comparison is a size check, the comparison
1311 // we want to do is a BoolTest::gt
1312 bool expand_fast_path = true;
1313 int tv = _igvn.find_int_con(initial_slow_test, -1);
1314 if (tv >= 0) {
1315 // InitialTest has constant result
1316 // 0 - can fit in TLAB
1317 // 1 - always too big or negative
1318 assert(tv <= 1, "0 or 1 if a constant");
1319 expand_fast_path = (tv == 0);
1320 initial_slow_test = NULL;
1321 } else {
1322 initial_slow_test = BoolNode::make_predicate(initial_slow_test, &_igvn);
1323 }
1324
1325 if (C->env()->dtrace_alloc_probes() ||
1326 (!UseTLAB && !Universe::heap()->supports_inline_contig_alloc())) {
1327 // Force slow-path allocation
1328 expand_fast_path = false;
1329 initial_slow_test = NULL;
1330 }
1331
1332 bool allocation_has_use = (alloc->result_cast() != NULL);
1333 if (!allocation_has_use) {
1334 InitializeNode* init = alloc->initialization();
1335 if (init != NULL) {
1336 init->remove(&_igvn);
1337 }
1338 if (expand_fast_path && (initial_slow_test == NULL)) {
1339 // Remove allocation node and return.
1340 // Size is a non-negative constant -> no initial check needed -> directly to fast path.
1341 // Also, no usages -> empty fast path -> no fall out to slow path -> nothing left.
1342 #ifndef PRODUCT
1343 if (PrintEliminateAllocations) {
1344 tty->print("NotUsed ");
1345 Node* res = alloc->proj_out_or_null(TypeFunc::Parms);
1346 if (res != NULL) {
1347 res->dump();
1348 } else {
1349 alloc->dump();
1350 }
1351 }
1352 #endif
1353 yank_alloc_node(alloc);
1354 return;
1355 }
1356 }
1357
1358 enum { too_big_or_final_path = 1, need_gc_path = 2 };
1359 Node *slow_region = NULL;
1360 Node *toobig_false = ctrl;
1361
1362 // generate the initial test if necessary
1363 if (initial_slow_test != NULL ) {
1364 assert (expand_fast_path, "Only need test if there is a fast path");
1365 slow_region = new RegionNode(3);
1366
1367 // Now make the initial failure test. Usually a too-big test but
1368 // might be a TRUE for finalizers or a fancy class check for
1369 // newInstance0.
1370 IfNode *toobig_iff = new IfNode(ctrl, initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
1371 transform_later(toobig_iff);
1372 // Plug the failing-too-big test into the slow-path region
1373 Node *toobig_true = new IfTrueNode( toobig_iff );
1374 transform_later(toobig_true);
1375 slow_region ->init_req( too_big_or_final_path, toobig_true );
1376 toobig_false = new IfFalseNode( toobig_iff );
1377 transform_later(toobig_false);
1378 } else {
1379 // No initial test, just fall into next case
1380 assert(allocation_has_use || !expand_fast_path, "Should already have been handled");
1381 toobig_false = ctrl;
1382 debug_only(slow_region = NodeSentinel);
1383 }
1384
1385 // If we are here there are several possibilities
1386 // - expand_fast_path is false - then only a slow path is expanded. That's it.
1387 // no_initial_check means a constant allocation.
1388 // - If check always evaluates to false -> expand_fast_path is false (see above)
1389 // - If check always evaluates to true -> directly into fast path (but may bailout to slowpath)
1390 // if !allocation_has_use the fast path is empty
1391 // if !allocation_has_use && no_initial_check
1392 // - Then there are no fastpath that can fall out to slowpath -> no allocation code at all.
1393 // removed by yank_alloc_node above.
1394
1395 Node *slow_mem = mem; // save the current memory state for slow path
1396 // generate the fast allocation code unless we know that the initial test will always go slow
1397 if (expand_fast_path) {
1398 // Fast path modifies only raw memory.
1399 if (mem->is_MergeMem()) {
1400 mem = mem->as_MergeMem()->memory_at(Compile::AliasIdxRaw);
1401 }
1402
1403 // allocate the Region and Phi nodes for the result
1404 result_region = new RegionNode(3);
1405 result_phi_rawmem = new PhiNode(result_region, Type::MEMORY, TypeRawPtr::BOTTOM);
1406 result_phi_i_o = new PhiNode(result_region, Type::ABIO); // I/O is used for Prefetch
1407
1408 // Grab regular I/O before optional prefetch may change it.
1409 // Slow-path does no I/O so just set it to the original I/O.
1410 result_phi_i_o->init_req(slow_result_path, i_o);
1411
1412 // Name successful fast-path variables
1413 Node* fast_oop_ctrl;
1414 Node* fast_oop_rawmem;
1415 if (allocation_has_use) {
1416 Node* needgc_ctrl = NULL;
1417 result_phi_rawoop = new PhiNode(result_region, TypeRawPtr::BOTTOM);
1418
1419 intx prefetch_lines = length != NULL ? AllocatePrefetchLines : AllocateInstancePrefetchLines;
1420 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1421 Node* fast_oop = bs->obj_allocate(this, ctrl, mem, toobig_false, size_in_bytes, i_o, needgc_ctrl,
1422 fast_oop_ctrl, fast_oop_rawmem,
1423 prefetch_lines);
1424
1425 if (initial_slow_test != NULL) {
1426 // This completes all paths into the slow merge point
1427 slow_region->init_req(need_gc_path, needgc_ctrl);
1428 transform_later(slow_region);
1429 } else {
1430 // No initial slow path needed!
1431 // Just fall from the need-GC path straight into the VM call.
1432 slow_region = needgc_ctrl;
1433 }
1434
1435 InitializeNode* init = alloc->initialization();
1436 fast_oop_rawmem = initialize_object(alloc,
1437 fast_oop_ctrl, fast_oop_rawmem, fast_oop,
1438 klass_node, length, size_in_bytes);
1439 expand_initialize_membar(alloc, init, fast_oop_ctrl, fast_oop_rawmem);
1440 expand_dtrace_alloc_probe(alloc, fast_oop, fast_oop_ctrl, fast_oop_rawmem);
1441
1442 result_phi_rawoop->init_req(fast_result_path, fast_oop);
1443 } else {
1444 assert (initial_slow_test != NULL, "sanity");
1445 fast_oop_ctrl = toobig_false;
1446 fast_oop_rawmem = mem;
1447 transform_later(slow_region);
1448 }
1449
1450 // Plug in the successful fast-path into the result merge point
1451 result_region ->init_req(fast_result_path, fast_oop_ctrl);
1452 result_phi_i_o ->init_req(fast_result_path, i_o);
1453 result_phi_rawmem->init_req(fast_result_path, fast_oop_rawmem);
1454 } else {
1455 slow_region = ctrl;
1456 result_phi_i_o = i_o; // Rename it to use in the following code.
1457 }
1458
1459 // Generate slow-path call
1460 CallNode *call = new CallStaticJavaNode(slow_call_type, slow_call_address,
1461 OptoRuntime::stub_name(slow_call_address),
1462 alloc->jvms()->bci(),
1463 TypePtr::BOTTOM);
1464 call->init_req(TypeFunc::Control, slow_region);
1465 call->init_req(TypeFunc::I_O, top()); // does no i/o
1466 call->init_req(TypeFunc::Memory, slow_mem); // may gc ptrs
1467 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1468 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1469
1470 call->init_req(TypeFunc::Parms+0, klass_node);
1471 if (length != NULL) {
1472 call->init_req(TypeFunc::Parms+1, length);
1473 }
1474
1475 // Copy debug information and adjust JVMState information, then replace
1476 // allocate node with the call
1477 copy_call_debug_info((CallNode *) alloc, call);
1478 if (expand_fast_path) {
1479 call->set_cnt(PROB_UNLIKELY_MAG(4)); // Same effect as RC_UNCOMMON.
1480 } else {
1481 // Hook i_o projection to avoid its elimination during allocation
1482 // replacement (when only a slow call is generated).
1483 call->set_req(TypeFunc::I_O, result_phi_i_o);
1484 }
1485 _igvn.replace_node(alloc, call);
1486 transform_later(call);
1487
1488 // Identify the output projections from the allocate node and
1489 // adjust any references to them.
1490 // The control and io projections look like:
1491 //
1492 // v---Proj(ctrl) <-----+ v---CatchProj(ctrl)
1493 // Allocate Catch
1494 // ^---Proj(io) <-------+ ^---CatchProj(io)
1495 //
1496 // We are interested in the CatchProj nodes.
1497 //
1498 extract_call_projections(call);
1499
1500 // An allocate node has separate memory projections for the uses on
1501 // the control and i_o paths. Replace the control memory projection with
1502 // result_phi_rawmem (unless we are only generating a slow call when
1503 // both memory projections are combined)
1504 if (expand_fast_path && _memproj_fallthrough != NULL) {
1505 migrate_outs(_memproj_fallthrough, result_phi_rawmem);
1506 }
1507 // Now change uses of _memproj_catchall to use _memproj_fallthrough and delete
1508 // _memproj_catchall so we end up with a call that has only 1 memory projection.
1509 if (_memproj_catchall != NULL ) {
1510 if (_memproj_fallthrough == NULL) {
1511 _memproj_fallthrough = new ProjNode(call, TypeFunc::Memory);
1512 transform_later(_memproj_fallthrough);
1513 }
1514 migrate_outs(_memproj_catchall, _memproj_fallthrough);
1515 _igvn.remove_dead_node(_memproj_catchall);
1516 }
1517
1518 // An allocate node has separate i_o projections for the uses on the control
1519 // and i_o paths. Always replace the control i_o projection with result i_o
1520 // otherwise incoming i_o become dead when only a slow call is generated
1521 // (it is different from memory projections where both projections are
1522 // combined in such case).
1523 if (_ioproj_fallthrough != NULL) {
1524 migrate_outs(_ioproj_fallthrough, result_phi_i_o);
1525 }
1526 // Now change uses of _ioproj_catchall to use _ioproj_fallthrough and delete
1527 // _ioproj_catchall so we end up with a call that has only 1 i_o projection.
1528 if (_ioproj_catchall != NULL ) {
1529 if (_ioproj_fallthrough == NULL) {
1530 _ioproj_fallthrough = new ProjNode(call, TypeFunc::I_O);
1531 transform_later(_ioproj_fallthrough);
1532 }
1533 migrate_outs(_ioproj_catchall, _ioproj_fallthrough);
1534 _igvn.remove_dead_node(_ioproj_catchall);
1535 }
1536
1537 // if we generated only a slow call, we are done
1538 if (!expand_fast_path) {
1539 // Now we can unhook i_o.
1540 if (result_phi_i_o->outcnt() > 1) {
1541 call->set_req(TypeFunc::I_O, top());
1542 } else {
1543 assert(result_phi_i_o->unique_ctrl_out() == call, "sanity");
1544 // Case of new array with negative size known during compilation.
1545 // AllocateArrayNode::Ideal() optimization disconnect unreachable
1546 // following code since call to runtime will throw exception.
1547 // As result there will be no users of i_o after the call.
1548 // Leave i_o attached to this call to avoid problems in preceding graph.
1549 }
1550 return;
1551 }
1552
1553 if (_fallthroughcatchproj != NULL) {
1554 ctrl = _fallthroughcatchproj->clone();
1555 transform_later(ctrl);
1556 _igvn.replace_node(_fallthroughcatchproj, result_region);
1557 } else {
1558 ctrl = top();
1559 }
1560 Node *slow_result;
1561 if (_resproj == NULL) {
1562 // no uses of the allocation result
1563 slow_result = top();
1564 } else {
1565 slow_result = _resproj->clone();
1566 transform_later(slow_result);
1567 _igvn.replace_node(_resproj, result_phi_rawoop);
1568 }
1569
1570 // Plug slow-path into result merge point
1571 result_region->init_req( slow_result_path, ctrl);
1572 transform_later(result_region);
1573 if (allocation_has_use) {
1574 result_phi_rawoop->init_req(slow_result_path, slow_result);
1575 transform_later(result_phi_rawoop);
1576 }
1577 result_phi_rawmem->init_req(slow_result_path, _memproj_fallthrough);
1578 transform_later(result_phi_rawmem);
1579 transform_later(result_phi_i_o);
1580 // This completes all paths into the result merge point
1581 }
1582
1583 // Remove alloc node that has no uses.
yank_alloc_node(AllocateNode * alloc)1584 void PhaseMacroExpand::yank_alloc_node(AllocateNode* alloc) {
1585 Node* ctrl = alloc->in(TypeFunc::Control);
1586 Node* mem = alloc->in(TypeFunc::Memory);
1587 Node* i_o = alloc->in(TypeFunc::I_O);
1588
1589 extract_call_projections(alloc);
1590 if (_resproj != NULL) {
1591 for (DUIterator_Fast imax, i = _resproj->fast_outs(imax); i < imax; i++) {
1592 Node* use = _resproj->fast_out(i);
1593 use->isa_MemBar()->remove(&_igvn);
1594 --imax;
1595 --i; // back up iterator
1596 }
1597 assert(_resproj->outcnt() == 0, "all uses must be deleted");
1598 _igvn.remove_dead_node(_resproj);
1599 }
1600 if (_fallthroughcatchproj != NULL) {
1601 migrate_outs(_fallthroughcatchproj, ctrl);
1602 _igvn.remove_dead_node(_fallthroughcatchproj);
1603 }
1604 if (_catchallcatchproj != NULL) {
1605 _igvn.rehash_node_delayed(_catchallcatchproj);
1606 _catchallcatchproj->set_req(0, top());
1607 }
1608 if (_fallthroughproj != NULL) {
1609 Node* catchnode = _fallthroughproj->unique_ctrl_out();
1610 _igvn.remove_dead_node(catchnode);
1611 _igvn.remove_dead_node(_fallthroughproj);
1612 }
1613 if (_memproj_fallthrough != NULL) {
1614 migrate_outs(_memproj_fallthrough, mem);
1615 _igvn.remove_dead_node(_memproj_fallthrough);
1616 }
1617 if (_ioproj_fallthrough != NULL) {
1618 migrate_outs(_ioproj_fallthrough, i_o);
1619 _igvn.remove_dead_node(_ioproj_fallthrough);
1620 }
1621 if (_memproj_catchall != NULL) {
1622 _igvn.rehash_node_delayed(_memproj_catchall);
1623 _memproj_catchall->set_req(0, top());
1624 }
1625 if (_ioproj_catchall != NULL) {
1626 _igvn.rehash_node_delayed(_ioproj_catchall);
1627 _ioproj_catchall->set_req(0, top());
1628 }
1629 #ifndef PRODUCT
1630 if (PrintEliminateAllocations) {
1631 if (alloc->is_AllocateArray()) {
1632 tty->print_cr("++++ Eliminated: %d AllocateArray", alloc->_idx);
1633 } else {
1634 tty->print_cr("++++ Eliminated: %d Allocate", alloc->_idx);
1635 }
1636 }
1637 #endif
1638 _igvn.remove_dead_node(alloc);
1639 }
1640
expand_initialize_membar(AllocateNode * alloc,InitializeNode * init,Node * & fast_oop_ctrl,Node * & fast_oop_rawmem)1641 void PhaseMacroExpand::expand_initialize_membar(AllocateNode* alloc, InitializeNode* init,
1642 Node*& fast_oop_ctrl, Node*& fast_oop_rawmem) {
1643 // If initialization is performed by an array copy, any required
1644 // MemBarStoreStore was already added. If the object does not
1645 // escape no need for a MemBarStoreStore. If the object does not
1646 // escape in its initializer and memory barrier (MemBarStoreStore or
1647 // stronger) is already added at exit of initializer, also no need
1648 // for a MemBarStoreStore. Otherwise we need a MemBarStoreStore
1649 // so that stores that initialize this object can't be reordered
1650 // with a subsequent store that makes this object accessible by
1651 // other threads.
1652 // Other threads include java threads and JVM internal threads
1653 // (for example concurrent GC threads). Current concurrent GC
1654 // implementation: G1 will not scan newly created object,
1655 // so it's safe to skip storestore barrier when allocation does
1656 // not escape.
1657 if (!alloc->does_not_escape_thread() &&
1658 !alloc->is_allocation_MemBar_redundant() &&
1659 (init == NULL || !init->is_complete_with_arraycopy())) {
1660 if (init == NULL || init->req() < InitializeNode::RawStores) {
1661 // No InitializeNode or no stores captured by zeroing
1662 // elimination. Simply add the MemBarStoreStore after object
1663 // initialization.
1664 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1665 transform_later(mb);
1666
1667 mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
1668 mb->init_req(TypeFunc::Control, fast_oop_ctrl);
1669 fast_oop_ctrl = new ProjNode(mb, TypeFunc::Control);
1670 transform_later(fast_oop_ctrl);
1671 fast_oop_rawmem = new ProjNode(mb, TypeFunc::Memory);
1672 transform_later(fast_oop_rawmem);
1673 } else {
1674 // Add the MemBarStoreStore after the InitializeNode so that
1675 // all stores performing the initialization that were moved
1676 // before the InitializeNode happen before the storestore
1677 // barrier.
1678
1679 Node* init_ctrl = init->proj_out_or_null(TypeFunc::Control);
1680 Node* init_mem = init->proj_out_or_null(TypeFunc::Memory);
1681
1682 MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
1683 transform_later(mb);
1684
1685 Node* ctrl = new ProjNode(init, TypeFunc::Control);
1686 transform_later(ctrl);
1687 Node* mem = new ProjNode(init, TypeFunc::Memory);
1688 transform_later(mem);
1689
1690 // The MemBarStoreStore depends on control and memory coming
1691 // from the InitializeNode
1692 mb->init_req(TypeFunc::Memory, mem);
1693 mb->init_req(TypeFunc::Control, ctrl);
1694
1695 ctrl = new ProjNode(mb, TypeFunc::Control);
1696 transform_later(ctrl);
1697 mem = new ProjNode(mb, TypeFunc::Memory);
1698 transform_later(mem);
1699
1700 // All nodes that depended on the InitializeNode for control
1701 // and memory must now depend on the MemBarNode that itself
1702 // depends on the InitializeNode
1703 if (init_ctrl != NULL) {
1704 _igvn.replace_node(init_ctrl, ctrl);
1705 }
1706 if (init_mem != NULL) {
1707 _igvn.replace_node(init_mem, mem);
1708 }
1709 }
1710 }
1711 }
1712
expand_dtrace_alloc_probe(AllocateNode * alloc,Node * oop,Node * & ctrl,Node * & rawmem)1713 void PhaseMacroExpand::expand_dtrace_alloc_probe(AllocateNode* alloc, Node* oop,
1714 Node*& ctrl, Node*& rawmem) {
1715 if (C->env()->dtrace_extended_probes()) {
1716 // Slow-path call
1717 int size = TypeFunc::Parms + 2;
1718 CallLeafNode *call = new CallLeafNode(OptoRuntime::dtrace_object_alloc_Type(),
1719 CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_object_alloc_base),
1720 "dtrace_object_alloc",
1721 TypeRawPtr::BOTTOM);
1722
1723 // Get base of thread-local storage area
1724 Node* thread = new ThreadLocalNode();
1725 transform_later(thread);
1726
1727 call->init_req(TypeFunc::Parms + 0, thread);
1728 call->init_req(TypeFunc::Parms + 1, oop);
1729 call->init_req(TypeFunc::Control, ctrl);
1730 call->init_req(TypeFunc::I_O , top()); // does no i/o
1731 call->init_req(TypeFunc::Memory , ctrl);
1732 call->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1733 call->init_req(TypeFunc::FramePtr, alloc->in(TypeFunc::FramePtr));
1734 transform_later(call);
1735 ctrl = new ProjNode(call, TypeFunc::Control);
1736 transform_later(ctrl);
1737 rawmem = new ProjNode(call, TypeFunc::Memory);
1738 transform_later(rawmem);
1739 }
1740 }
1741
1742 // Helper for PhaseMacroExpand::expand_allocate_common.
1743 // Initializes the newly-allocated storage.
1744 Node*
initialize_object(AllocateNode * alloc,Node * control,Node * rawmem,Node * object,Node * klass_node,Node * length,Node * size_in_bytes)1745 PhaseMacroExpand::initialize_object(AllocateNode* alloc,
1746 Node* control, Node* rawmem, Node* object,
1747 Node* klass_node, Node* length,
1748 Node* size_in_bytes) {
1749 InitializeNode* init = alloc->initialization();
1750 // Store the klass & mark bits
1751 Node* mark_node = alloc->make_ideal_mark(&_igvn, object, control, rawmem);
1752 if (!mark_node->is_Con()) {
1753 transform_later(mark_node);
1754 }
1755 rawmem = make_store(control, rawmem, object, oopDesc::mark_offset_in_bytes(), mark_node, TypeX_X->basic_type());
1756
1757 rawmem = make_store(control, rawmem, object, oopDesc::klass_offset_in_bytes(), klass_node, T_METADATA);
1758 int header_size = alloc->minimum_header_size(); // conservatively small
1759
1760 // Array length
1761 if (length != NULL) { // Arrays need length field
1762 rawmem = make_store(control, rawmem, object, arrayOopDesc::length_offset_in_bytes(), length, T_INT);
1763 // conservatively small header size:
1764 header_size = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1765 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1766 if (k->is_array_klass()) // we know the exact header size in most cases:
1767 header_size = Klass::layout_helper_header_size(k->layout_helper());
1768 }
1769
1770 // Clear the object body, if necessary.
1771 if (init == NULL) {
1772 // The init has somehow disappeared; be cautious and clear everything.
1773 //
1774 // This can happen if a node is allocated but an uncommon trap occurs
1775 // immediately. In this case, the Initialize gets associated with the
1776 // trap, and may be placed in a different (outer) loop, if the Allocate
1777 // is in a loop. If (this is rare) the inner loop gets unrolled, then
1778 // there can be two Allocates to one Initialize. The answer in all these
1779 // edge cases is safety first. It is always safe to clear immediately
1780 // within an Allocate, and then (maybe or maybe not) clear some more later.
1781 if (!(UseTLAB && ZeroTLAB)) {
1782 rawmem = ClearArrayNode::clear_memory(control, rawmem, object,
1783 header_size, size_in_bytes,
1784 &_igvn);
1785 }
1786 } else {
1787 if (!init->is_complete()) {
1788 // Try to win by zeroing only what the init does not store.
1789 // We can also try to do some peephole optimizations,
1790 // such as combining some adjacent subword stores.
1791 rawmem = init->complete_stores(control, rawmem, object,
1792 header_size, size_in_bytes, &_igvn);
1793 }
1794 // We have no more use for this link, since the AllocateNode goes away:
1795 init->set_req(InitializeNode::RawAddress, top());
1796 // (If we keep the link, it just confuses the register allocator,
1797 // who thinks he sees a real use of the address by the membar.)
1798 }
1799
1800 return rawmem;
1801 }
1802
1803 // Generate prefetch instructions for next allocations.
prefetch_allocation(Node * i_o,Node * & needgc_false,Node * & contended_phi_rawmem,Node * old_eden_top,Node * new_eden_top,intx lines)1804 Node* PhaseMacroExpand::prefetch_allocation(Node* i_o, Node*& needgc_false,
1805 Node*& contended_phi_rawmem,
1806 Node* old_eden_top, Node* new_eden_top,
1807 intx lines) {
1808 enum { fall_in_path = 1, pf_path = 2 };
1809 if( UseTLAB && AllocatePrefetchStyle == 2 ) {
1810 // Generate prefetch allocation with watermark check.
1811 // As an allocation hits the watermark, we will prefetch starting
1812 // at a "distance" away from watermark.
1813
1814 Node *pf_region = new RegionNode(3);
1815 Node *pf_phi_rawmem = new PhiNode( pf_region, Type::MEMORY,
1816 TypeRawPtr::BOTTOM );
1817 // I/O is used for Prefetch
1818 Node *pf_phi_abio = new PhiNode( pf_region, Type::ABIO );
1819
1820 Node *thread = new ThreadLocalNode();
1821 transform_later(thread);
1822
1823 Node *eden_pf_adr = new AddPNode( top()/*not oop*/, thread,
1824 _igvn.MakeConX(in_bytes(JavaThread::tlab_pf_top_offset())) );
1825 transform_later(eden_pf_adr);
1826
1827 Node *old_pf_wm = new LoadPNode(needgc_false,
1828 contended_phi_rawmem, eden_pf_adr,
1829 TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM,
1830 MemNode::unordered);
1831 transform_later(old_pf_wm);
1832
1833 // check against new_eden_top
1834 Node *need_pf_cmp = new CmpPNode( new_eden_top, old_pf_wm );
1835 transform_later(need_pf_cmp);
1836 Node *need_pf_bol = new BoolNode( need_pf_cmp, BoolTest::ge );
1837 transform_later(need_pf_bol);
1838 IfNode *need_pf_iff = new IfNode( needgc_false, need_pf_bol,
1839 PROB_UNLIKELY_MAG(4), COUNT_UNKNOWN );
1840 transform_later(need_pf_iff);
1841
1842 // true node, add prefetchdistance
1843 Node *need_pf_true = new IfTrueNode( need_pf_iff );
1844 transform_later(need_pf_true);
1845
1846 Node *need_pf_false = new IfFalseNode( need_pf_iff );
1847 transform_later(need_pf_false);
1848
1849 Node *new_pf_wmt = new AddPNode( top(), old_pf_wm,
1850 _igvn.MakeConX(AllocatePrefetchDistance) );
1851 transform_later(new_pf_wmt );
1852 new_pf_wmt->set_req(0, need_pf_true);
1853
1854 Node *store_new_wmt = new StorePNode(need_pf_true,
1855 contended_phi_rawmem, eden_pf_adr,
1856 TypeRawPtr::BOTTOM, new_pf_wmt,
1857 MemNode::unordered);
1858 transform_later(store_new_wmt);
1859
1860 // adding prefetches
1861 pf_phi_abio->init_req( fall_in_path, i_o );
1862
1863 Node *prefetch_adr;
1864 Node *prefetch;
1865 uint step_size = AllocatePrefetchStepSize;
1866 uint distance = 0;
1867
1868 for ( intx i = 0; i < lines; i++ ) {
1869 prefetch_adr = new AddPNode( old_pf_wm, new_pf_wmt,
1870 _igvn.MakeConX(distance) );
1871 transform_later(prefetch_adr);
1872 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1873 transform_later(prefetch);
1874 distance += step_size;
1875 i_o = prefetch;
1876 }
1877 pf_phi_abio->set_req( pf_path, i_o );
1878
1879 pf_region->init_req( fall_in_path, need_pf_false );
1880 pf_region->init_req( pf_path, need_pf_true );
1881
1882 pf_phi_rawmem->init_req( fall_in_path, contended_phi_rawmem );
1883 pf_phi_rawmem->init_req( pf_path, store_new_wmt );
1884
1885 transform_later(pf_region);
1886 transform_later(pf_phi_rawmem);
1887 transform_later(pf_phi_abio);
1888
1889 needgc_false = pf_region;
1890 contended_phi_rawmem = pf_phi_rawmem;
1891 i_o = pf_phi_abio;
1892 } else if( UseTLAB && AllocatePrefetchStyle == 3 ) {
1893 // Insert a prefetch instruction for each allocation.
1894 // This code is used to generate 1 prefetch instruction per cache line.
1895
1896 // Generate several prefetch instructions.
1897 uint step_size = AllocatePrefetchStepSize;
1898 uint distance = AllocatePrefetchDistance;
1899
1900 // Next cache address.
1901 Node *cache_adr = new AddPNode(old_eden_top, old_eden_top,
1902 _igvn.MakeConX(step_size + distance));
1903 transform_later(cache_adr);
1904 cache_adr = new CastP2XNode(needgc_false, cache_adr);
1905 transform_later(cache_adr);
1906 // Address is aligned to execute prefetch to the beginning of cache line size
1907 // (it is important when BIS instruction is used on SPARC as prefetch).
1908 Node* mask = _igvn.MakeConX(~(intptr_t)(step_size-1));
1909 cache_adr = new AndXNode(cache_adr, mask);
1910 transform_later(cache_adr);
1911 cache_adr = new CastX2PNode(cache_adr);
1912 transform_later(cache_adr);
1913
1914 // Prefetch
1915 Node *prefetch = new PrefetchAllocationNode( contended_phi_rawmem, cache_adr );
1916 prefetch->set_req(0, needgc_false);
1917 transform_later(prefetch);
1918 contended_phi_rawmem = prefetch;
1919 Node *prefetch_adr;
1920 distance = step_size;
1921 for ( intx i = 1; i < lines; i++ ) {
1922 prefetch_adr = new AddPNode( cache_adr, cache_adr,
1923 _igvn.MakeConX(distance) );
1924 transform_later(prefetch_adr);
1925 prefetch = new PrefetchAllocationNode( contended_phi_rawmem, prefetch_adr );
1926 transform_later(prefetch);
1927 distance += step_size;
1928 contended_phi_rawmem = prefetch;
1929 }
1930 } else if( AllocatePrefetchStyle > 0 ) {
1931 // Insert a prefetch for each allocation only on the fast-path
1932 Node *prefetch_adr;
1933 Node *prefetch;
1934 // Generate several prefetch instructions.
1935 uint step_size = AllocatePrefetchStepSize;
1936 uint distance = AllocatePrefetchDistance;
1937 for ( intx i = 0; i < lines; i++ ) {
1938 prefetch_adr = new AddPNode( old_eden_top, new_eden_top,
1939 _igvn.MakeConX(distance) );
1940 transform_later(prefetch_adr);
1941 prefetch = new PrefetchAllocationNode( i_o, prefetch_adr );
1942 // Do not let it float too high, since if eden_top == eden_end,
1943 // both might be null.
1944 if( i == 0 ) { // Set control for first prefetch, next follows it
1945 prefetch->init_req(0, needgc_false);
1946 }
1947 transform_later(prefetch);
1948 distance += step_size;
1949 i_o = prefetch;
1950 }
1951 }
1952 return i_o;
1953 }
1954
1955
expand_allocate(AllocateNode * alloc)1956 void PhaseMacroExpand::expand_allocate(AllocateNode *alloc) {
1957 expand_allocate_common(alloc, NULL,
1958 OptoRuntime::new_instance_Type(),
1959 OptoRuntime::new_instance_Java());
1960 }
1961
expand_allocate_array(AllocateArrayNode * alloc)1962 void PhaseMacroExpand::expand_allocate_array(AllocateArrayNode *alloc) {
1963 Node* length = alloc->in(AllocateNode::ALength);
1964 InitializeNode* init = alloc->initialization();
1965 Node* klass_node = alloc->in(AllocateNode::KlassNode);
1966 ciKlass* k = _igvn.type(klass_node)->is_klassptr()->klass();
1967 address slow_call_address; // Address of slow call
1968 if (init != NULL && init->is_complete_with_arraycopy() &&
1969 k->is_type_array_klass()) {
1970 // Don't zero type array during slow allocation in VM since
1971 // it will be initialized later by arraycopy in compiled code.
1972 slow_call_address = OptoRuntime::new_array_nozero_Java();
1973 } else {
1974 slow_call_address = OptoRuntime::new_array_Java();
1975 }
1976 expand_allocate_common(alloc, length,
1977 OptoRuntime::new_array_Type(),
1978 slow_call_address);
1979 }
1980
1981 //-------------------mark_eliminated_box----------------------------------
1982 //
1983 // During EA obj may point to several objects but after few ideal graph
1984 // transformations (CCP) it may point to only one non escaping object
1985 // (but still using phi), corresponding locks and unlocks will be marked
1986 // for elimination. Later obj could be replaced with a new node (new phi)
1987 // and which does not have escape information. And later after some graph
1988 // reshape other locks and unlocks (which were not marked for elimination
1989 // before) are connected to this new obj (phi) but they still will not be
1990 // marked for elimination since new obj has no escape information.
1991 // Mark all associated (same box and obj) lock and unlock nodes for
1992 // elimination if some of them marked already.
mark_eliminated_box(Node * oldbox,Node * obj)1993 void PhaseMacroExpand::mark_eliminated_box(Node* oldbox, Node* obj) {
1994 if (oldbox->as_BoxLock()->is_eliminated())
1995 return; // This BoxLock node was processed already.
1996
1997 // New implementation (EliminateNestedLocks) has separate BoxLock
1998 // node for each locked region so mark all associated locks/unlocks as
1999 // eliminated even if different objects are referenced in one locked region
2000 // (for example, OSR compilation of nested loop inside locked scope).
2001 if (EliminateNestedLocks ||
2002 oldbox->as_BoxLock()->is_simple_lock_region(NULL, obj)) {
2003 // Box is used only in one lock region. Mark this box as eliminated.
2004 _igvn.hash_delete(oldbox);
2005 oldbox->as_BoxLock()->set_eliminated(); // This changes box's hash value
2006 _igvn.hash_insert(oldbox);
2007
2008 for (uint i = 0; i < oldbox->outcnt(); i++) {
2009 Node* u = oldbox->raw_out(i);
2010 if (u->is_AbstractLock() && !u->as_AbstractLock()->is_non_esc_obj()) {
2011 AbstractLockNode* alock = u->as_AbstractLock();
2012 // Check lock's box since box could be referenced by Lock's debug info.
2013 if (alock->box_node() == oldbox) {
2014 // Mark eliminated all related locks and unlocks.
2015 #ifdef ASSERT
2016 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc4");
2017 #endif
2018 alock->set_non_esc_obj();
2019 }
2020 }
2021 }
2022 return;
2023 }
2024
2025 // Create new "eliminated" BoxLock node and use it in monitor debug info
2026 // instead of oldbox for the same object.
2027 BoxLockNode* newbox = oldbox->clone()->as_BoxLock();
2028
2029 // Note: BoxLock node is marked eliminated only here and it is used
2030 // to indicate that all associated lock and unlock nodes are marked
2031 // for elimination.
2032 newbox->set_eliminated();
2033 transform_later(newbox);
2034
2035 // Replace old box node with new box for all users of the same object.
2036 for (uint i = 0; i < oldbox->outcnt();) {
2037 bool next_edge = true;
2038
2039 Node* u = oldbox->raw_out(i);
2040 if (u->is_AbstractLock()) {
2041 AbstractLockNode* alock = u->as_AbstractLock();
2042 if (alock->box_node() == oldbox && alock->obj_node()->eqv_uncast(obj)) {
2043 // Replace Box and mark eliminated all related locks and unlocks.
2044 #ifdef ASSERT
2045 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc5");
2046 #endif
2047 alock->set_non_esc_obj();
2048 _igvn.rehash_node_delayed(alock);
2049 alock->set_box_node(newbox);
2050 next_edge = false;
2051 }
2052 }
2053 if (u->is_FastLock() && u->as_FastLock()->obj_node()->eqv_uncast(obj)) {
2054 FastLockNode* flock = u->as_FastLock();
2055 assert(flock->box_node() == oldbox, "sanity");
2056 _igvn.rehash_node_delayed(flock);
2057 flock->set_box_node(newbox);
2058 next_edge = false;
2059 }
2060
2061 // Replace old box in monitor debug info.
2062 if (u->is_SafePoint() && u->as_SafePoint()->jvms()) {
2063 SafePointNode* sfn = u->as_SafePoint();
2064 JVMState* youngest_jvms = sfn->jvms();
2065 int max_depth = youngest_jvms->depth();
2066 for (int depth = 1; depth <= max_depth; depth++) {
2067 JVMState* jvms = youngest_jvms->of_depth(depth);
2068 int num_mon = jvms->nof_monitors();
2069 // Loop over monitors
2070 for (int idx = 0; idx < num_mon; idx++) {
2071 Node* obj_node = sfn->monitor_obj(jvms, idx);
2072 Node* box_node = sfn->monitor_box(jvms, idx);
2073 if (box_node == oldbox && obj_node->eqv_uncast(obj)) {
2074 int j = jvms->monitor_box_offset(idx);
2075 _igvn.replace_input_of(u, j, newbox);
2076 next_edge = false;
2077 }
2078 }
2079 }
2080 }
2081 if (next_edge) i++;
2082 }
2083 }
2084
2085 //-----------------------mark_eliminated_locking_nodes-----------------------
mark_eliminated_locking_nodes(AbstractLockNode * alock)2086 void PhaseMacroExpand::mark_eliminated_locking_nodes(AbstractLockNode *alock) {
2087 if (EliminateNestedLocks) {
2088 if (alock->is_nested()) {
2089 assert(alock->box_node()->as_BoxLock()->is_eliminated(), "sanity");
2090 return;
2091 } else if (!alock->is_non_esc_obj()) { // Not eliminated or coarsened
2092 // Only Lock node has JVMState needed here.
2093 // Not that preceding claim is documented anywhere else.
2094 if (alock->jvms() != NULL) {
2095 if (alock->as_Lock()->is_nested_lock_region()) {
2096 // Mark eliminated related nested locks and unlocks.
2097 Node* obj = alock->obj_node();
2098 BoxLockNode* box_node = alock->box_node()->as_BoxLock();
2099 assert(!box_node->is_eliminated(), "should not be marked yet");
2100 // Note: BoxLock node is marked eliminated only here
2101 // and it is used to indicate that all associated lock
2102 // and unlock nodes are marked for elimination.
2103 box_node->set_eliminated(); // Box's hash is always NO_HASH here
2104 for (uint i = 0; i < box_node->outcnt(); i++) {
2105 Node* u = box_node->raw_out(i);
2106 if (u->is_AbstractLock()) {
2107 alock = u->as_AbstractLock();
2108 if (alock->box_node() == box_node) {
2109 // Verify that this Box is referenced only by related locks.
2110 assert(alock->obj_node()->eqv_uncast(obj), "");
2111 // Mark all related locks and unlocks.
2112 #ifdef ASSERT
2113 alock->log_lock_optimization(C, "eliminate_lock_set_nested");
2114 #endif
2115 alock->set_nested();
2116 }
2117 }
2118 }
2119 } else {
2120 #ifdef ASSERT
2121 alock->log_lock_optimization(C, "eliminate_lock_NOT_nested_lock_region");
2122 if (C->log() != NULL)
2123 alock->as_Lock()->is_nested_lock_region(C); // rerun for debugging output
2124 #endif
2125 }
2126 }
2127 return;
2128 }
2129 // Process locks for non escaping object
2130 assert(alock->is_non_esc_obj(), "");
2131 } // EliminateNestedLocks
2132
2133 if (alock->is_non_esc_obj()) { // Lock is used for non escaping object
2134 // Look for all locks of this object and mark them and
2135 // corresponding BoxLock nodes as eliminated.
2136 Node* obj = alock->obj_node();
2137 for (uint j = 0; j < obj->outcnt(); j++) {
2138 Node* o = obj->raw_out(j);
2139 if (o->is_AbstractLock() &&
2140 o->as_AbstractLock()->obj_node()->eqv_uncast(obj)) {
2141 alock = o->as_AbstractLock();
2142 Node* box = alock->box_node();
2143 // Replace old box node with new eliminated box for all users
2144 // of the same object and mark related locks as eliminated.
2145 mark_eliminated_box(box, obj);
2146 }
2147 }
2148 }
2149 }
2150
2151 // we have determined that this lock/unlock can be eliminated, we simply
2152 // eliminate the node without expanding it.
2153 //
2154 // Note: The membar's associated with the lock/unlock are currently not
2155 // eliminated. This should be investigated as a future enhancement.
2156 //
eliminate_locking_node(AbstractLockNode * alock)2157 bool PhaseMacroExpand::eliminate_locking_node(AbstractLockNode *alock) {
2158
2159 if (!alock->is_eliminated()) {
2160 return false;
2161 }
2162 #ifdef ASSERT
2163 if (!alock->is_coarsened()) {
2164 // Check that new "eliminated" BoxLock node is created.
2165 BoxLockNode* oldbox = alock->box_node()->as_BoxLock();
2166 assert(oldbox->is_eliminated(), "should be done already");
2167 }
2168 #endif
2169
2170 alock->log_lock_optimization(C, "eliminate_lock");
2171
2172 #ifndef PRODUCT
2173 if (PrintEliminateLocks) {
2174 if (alock->is_Lock()) {
2175 tty->print_cr("++++ Eliminated: %d Lock", alock->_idx);
2176 } else {
2177 tty->print_cr("++++ Eliminated: %d Unlock", alock->_idx);
2178 }
2179 }
2180 #endif
2181
2182 Node* mem = alock->in(TypeFunc::Memory);
2183 Node* ctrl = alock->in(TypeFunc::Control);
2184 guarantee(ctrl != NULL, "missing control projection, cannot replace_node() with NULL");
2185
2186 extract_call_projections(alock);
2187 // There are 2 projections from the lock. The lock node will
2188 // be deleted when its last use is subsumed below.
2189 assert(alock->outcnt() == 2 &&
2190 _fallthroughproj != NULL &&
2191 _memproj_fallthrough != NULL,
2192 "Unexpected projections from Lock/Unlock");
2193
2194 Node* fallthroughproj = _fallthroughproj;
2195 Node* memproj_fallthrough = _memproj_fallthrough;
2196
2197 // The memory projection from a lock/unlock is RawMem
2198 // The input to a Lock is merged memory, so extract its RawMem input
2199 // (unless the MergeMem has been optimized away.)
2200 if (alock->is_Lock()) {
2201 // Seach for MemBarAcquireLock node and delete it also.
2202 MemBarNode* membar = fallthroughproj->unique_ctrl_out()->as_MemBar();
2203 assert(membar != NULL && membar->Opcode() == Op_MemBarAcquireLock, "");
2204 Node* ctrlproj = membar->proj_out(TypeFunc::Control);
2205 Node* memproj = membar->proj_out(TypeFunc::Memory);
2206 _igvn.replace_node(ctrlproj, fallthroughproj);
2207 _igvn.replace_node(memproj, memproj_fallthrough);
2208
2209 // Delete FastLock node also if this Lock node is unique user
2210 // (a loop peeling may clone a Lock node).
2211 Node* flock = alock->as_Lock()->fastlock_node();
2212 if (flock->outcnt() == 1) {
2213 assert(flock->unique_out() == alock, "sanity");
2214 _igvn.replace_node(flock, top());
2215 }
2216 }
2217
2218 // Seach for MemBarReleaseLock node and delete it also.
2219 if (alock->is_Unlock() && ctrl->is_Proj() && ctrl->in(0)->is_MemBar()) {
2220 MemBarNode* membar = ctrl->in(0)->as_MemBar();
2221 assert(membar->Opcode() == Op_MemBarReleaseLock &&
2222 mem->is_Proj() && membar == mem->in(0), "");
2223 _igvn.replace_node(fallthroughproj, ctrl);
2224 _igvn.replace_node(memproj_fallthrough, mem);
2225 fallthroughproj = ctrl;
2226 memproj_fallthrough = mem;
2227 ctrl = membar->in(TypeFunc::Control);
2228 mem = membar->in(TypeFunc::Memory);
2229 }
2230
2231 _igvn.replace_node(fallthroughproj, ctrl);
2232 _igvn.replace_node(memproj_fallthrough, mem);
2233 return true;
2234 }
2235
2236
2237 //------------------------------expand_lock_node----------------------
expand_lock_node(LockNode * lock)2238 void PhaseMacroExpand::expand_lock_node(LockNode *lock) {
2239
2240 Node* ctrl = lock->in(TypeFunc::Control);
2241 Node* mem = lock->in(TypeFunc::Memory);
2242 Node* obj = lock->obj_node();
2243 Node* box = lock->box_node();
2244 Node* flock = lock->fastlock_node();
2245
2246 assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2247
2248 // Make the merge point
2249 Node *region;
2250 Node *mem_phi;
2251 Node *slow_path;
2252
2253 if (UseOptoBiasInlining) {
2254 /*
2255 * See the full description in MacroAssembler::biased_locking_enter().
2256 *
2257 * if( (mark_word & biased_lock_mask) == biased_lock_pattern ) {
2258 * // The object is biased.
2259 * proto_node = klass->prototype_header;
2260 * o_node = thread | proto_node;
2261 * x_node = o_node ^ mark_word;
2262 * if( (x_node & ~age_mask) == 0 ) { // Biased to the current thread ?
2263 * // Done.
2264 * } else {
2265 * if( (x_node & biased_lock_mask) != 0 ) {
2266 * // The klass's prototype header is no longer biased.
2267 * cas(&mark_word, mark_word, proto_node)
2268 * goto cas_lock;
2269 * } else {
2270 * // The klass's prototype header is still biased.
2271 * if( (x_node & epoch_mask) != 0 ) { // Expired epoch?
2272 * old = mark_word;
2273 * new = o_node;
2274 * } else {
2275 * // Different thread or anonymous biased.
2276 * old = mark_word & (epoch_mask | age_mask | biased_lock_mask);
2277 * new = thread | old;
2278 * }
2279 * // Try to rebias.
2280 * if( cas(&mark_word, old, new) == 0 ) {
2281 * // Done.
2282 * } else {
2283 * goto slow_path; // Failed.
2284 * }
2285 * }
2286 * }
2287 * } else {
2288 * // The object is not biased.
2289 * cas_lock:
2290 * if( FastLock(obj) == 0 ) {
2291 * // Done.
2292 * } else {
2293 * slow_path:
2294 * OptoRuntime::complete_monitor_locking_Java(obj);
2295 * }
2296 * }
2297 */
2298
2299 region = new RegionNode(5);
2300 // create a Phi for the memory state
2301 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2302
2303 Node* fast_lock_region = new RegionNode(3);
2304 Node* fast_lock_mem_phi = new PhiNode( fast_lock_region, Type::MEMORY, TypeRawPtr::BOTTOM);
2305
2306 // First, check mark word for the biased lock pattern.
2307 Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2308
2309 // Get fast path - mark word has the biased lock pattern.
2310 ctrl = opt_bits_test(ctrl, fast_lock_region, 1, mark_node,
2311 markWord::biased_lock_mask_in_place,
2312 markWord::biased_lock_pattern, true);
2313 // fast_lock_region->in(1) is set to slow path.
2314 fast_lock_mem_phi->init_req(1, mem);
2315
2316 // Now check that the lock is biased to the current thread and has
2317 // the same epoch and bias as Klass::_prototype_header.
2318
2319 // Special-case a fresh allocation to avoid building nodes:
2320 Node* klass_node = AllocateNode::Ideal_klass(obj, &_igvn);
2321 if (klass_node == NULL) {
2322 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
2323 klass_node = transform_later(LoadKlassNode::make(_igvn, NULL, mem, k_adr, _igvn.type(k_adr)->is_ptr()));
2324 #ifdef _LP64
2325 if (UseCompressedClassPointers && klass_node->is_DecodeNKlass()) {
2326 assert(klass_node->in(1)->Opcode() == Op_LoadNKlass, "sanity");
2327 klass_node->in(1)->init_req(0, ctrl);
2328 } else
2329 #endif
2330 klass_node->init_req(0, ctrl);
2331 }
2332 Node *proto_node = make_load(ctrl, mem, klass_node, in_bytes(Klass::prototype_header_offset()), TypeX_X, TypeX_X->basic_type());
2333
2334 Node* thread = transform_later(new ThreadLocalNode());
2335 Node* cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2336 Node* o_node = transform_later(new OrXNode(cast_thread, proto_node));
2337 Node* x_node = transform_later(new XorXNode(o_node, mark_node));
2338
2339 // Get slow path - mark word does NOT match the value.
2340 STATIC_ASSERT(markWord::age_mask_in_place <= INT_MAX);
2341 Node* not_biased_ctrl = opt_bits_test(ctrl, region, 3, x_node,
2342 (~(int)markWord::age_mask_in_place), 0);
2343 // region->in(3) is set to fast path - the object is biased to the current thread.
2344 mem_phi->init_req(3, mem);
2345
2346
2347 // Mark word does NOT match the value (thread | Klass::_prototype_header).
2348
2349
2350 // First, check biased pattern.
2351 // Get fast path - _prototype_header has the same biased lock pattern.
2352 ctrl = opt_bits_test(not_biased_ctrl, fast_lock_region, 2, x_node,
2353 markWord::biased_lock_mask_in_place, 0, true);
2354
2355 not_biased_ctrl = fast_lock_region->in(2); // Slow path
2356 // fast_lock_region->in(2) - the prototype header is no longer biased
2357 // and we have to revoke the bias on this object.
2358 // We are going to try to reset the mark of this object to the prototype
2359 // value and fall through to the CAS-based locking scheme.
2360 Node* adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
2361 Node* cas = new StoreXConditionalNode(not_biased_ctrl, mem, adr,
2362 proto_node, mark_node);
2363 transform_later(cas);
2364 Node* proj = transform_later(new SCMemProjNode(cas));
2365 fast_lock_mem_phi->init_req(2, proj);
2366
2367
2368 // Second, check epoch bits.
2369 Node* rebiased_region = new RegionNode(3);
2370 Node* old_phi = new PhiNode( rebiased_region, TypeX_X);
2371 Node* new_phi = new PhiNode( rebiased_region, TypeX_X);
2372
2373 // Get slow path - mark word does NOT match epoch bits.
2374 Node* epoch_ctrl = opt_bits_test(ctrl, rebiased_region, 1, x_node,
2375 markWord::epoch_mask_in_place, 0);
2376 // The epoch of the current bias is not valid, attempt to rebias the object
2377 // toward the current thread.
2378 rebiased_region->init_req(2, epoch_ctrl);
2379 old_phi->init_req(2, mark_node);
2380 new_phi->init_req(2, o_node);
2381
2382 // rebiased_region->in(1) is set to fast path.
2383 // The epoch of the current bias is still valid but we know
2384 // nothing about the owner; it might be set or it might be clear.
2385 Node* cmask = MakeConX(markWord::biased_lock_mask_in_place |
2386 markWord::age_mask_in_place |
2387 markWord::epoch_mask_in_place);
2388 Node* old = transform_later(new AndXNode(mark_node, cmask));
2389 cast_thread = transform_later(new CastP2XNode(ctrl, thread));
2390 Node* new_mark = transform_later(new OrXNode(cast_thread, old));
2391 old_phi->init_req(1, old);
2392 new_phi->init_req(1, new_mark);
2393
2394 transform_later(rebiased_region);
2395 transform_later(old_phi);
2396 transform_later(new_phi);
2397
2398 // Try to acquire the bias of the object using an atomic operation.
2399 // If this fails we will go in to the runtime to revoke the object's bias.
2400 cas = new StoreXConditionalNode(rebiased_region, mem, adr, new_phi, old_phi);
2401 transform_later(cas);
2402 proj = transform_later(new SCMemProjNode(cas));
2403
2404 // Get slow path - Failed to CAS.
2405 not_biased_ctrl = opt_bits_test(rebiased_region, region, 4, cas, 0, 0);
2406 mem_phi->init_req(4, proj);
2407 // region->in(4) is set to fast path - the object is rebiased to the current thread.
2408
2409 // Failed to CAS.
2410 slow_path = new RegionNode(3);
2411 Node *slow_mem = new PhiNode( slow_path, Type::MEMORY, TypeRawPtr::BOTTOM);
2412
2413 slow_path->init_req(1, not_biased_ctrl); // Capture slow-control
2414 slow_mem->init_req(1, proj);
2415
2416 // Call CAS-based locking scheme (FastLock node).
2417
2418 transform_later(fast_lock_region);
2419 transform_later(fast_lock_mem_phi);
2420
2421 // Get slow path - FastLock failed to lock the object.
2422 ctrl = opt_bits_test(fast_lock_region, region, 2, flock, 0, 0);
2423 mem_phi->init_req(2, fast_lock_mem_phi);
2424 // region->in(2) is set to fast path - the object is locked to the current thread.
2425
2426 slow_path->init_req(2, ctrl); // Capture slow-control
2427 slow_mem->init_req(2, fast_lock_mem_phi);
2428
2429 transform_later(slow_path);
2430 transform_later(slow_mem);
2431 // Reset lock's memory edge.
2432 lock->set_req(TypeFunc::Memory, slow_mem);
2433
2434 } else {
2435 region = new RegionNode(3);
2436 // create a Phi for the memory state
2437 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2438
2439 // Optimize test; set region slot 2
2440 slow_path = opt_bits_test(ctrl, region, 2, flock, 0, 0);
2441 mem_phi->init_req(2, mem);
2442 }
2443
2444 // Make slow path call
2445 CallNode *call = make_slow_call((CallNode *) lock, OptoRuntime::complete_monitor_enter_Type(),
2446 OptoRuntime::complete_monitor_locking_Java(), NULL, slow_path,
2447 obj, box, NULL);
2448
2449 extract_call_projections(call);
2450
2451 // Slow path can only throw asynchronous exceptions, which are always
2452 // de-opted. So the compiler thinks the slow-call can never throw an
2453 // exception. If it DOES throw an exception we would need the debug
2454 // info removed first (since if it throws there is no monitor).
2455 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2456 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2457
2458 // Capture slow path
2459 // disconnect fall-through projection from call and create a new one
2460 // hook up users of fall-through projection to region
2461 Node *slow_ctrl = _fallthroughproj->clone();
2462 transform_later(slow_ctrl);
2463 _igvn.hash_delete(_fallthroughproj);
2464 _fallthroughproj->disconnect_inputs(NULL, C);
2465 region->init_req(1, slow_ctrl);
2466 // region inputs are now complete
2467 transform_later(region);
2468 _igvn.replace_node(_fallthroughproj, region);
2469
2470 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory));
2471 mem_phi->init_req(1, memproj );
2472 transform_later(mem_phi);
2473 _igvn.replace_node(_memproj_fallthrough, mem_phi);
2474 }
2475
2476 //------------------------------expand_unlock_node----------------------
expand_unlock_node(UnlockNode * unlock)2477 void PhaseMacroExpand::expand_unlock_node(UnlockNode *unlock) {
2478
2479 Node* ctrl = unlock->in(TypeFunc::Control);
2480 Node* mem = unlock->in(TypeFunc::Memory);
2481 Node* obj = unlock->obj_node();
2482 Node* box = unlock->box_node();
2483
2484 assert(!box->as_BoxLock()->is_eliminated(), "sanity");
2485
2486 // No need for a null check on unlock
2487
2488 // Make the merge point
2489 Node *region;
2490 Node *mem_phi;
2491
2492 if (UseOptoBiasInlining) {
2493 // Check for biased locking unlock case, which is a no-op.
2494 // See the full description in MacroAssembler::biased_locking_exit().
2495 region = new RegionNode(4);
2496 // create a Phi for the memory state
2497 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2498 mem_phi->init_req(3, mem);
2499
2500 Node* mark_node = make_load(ctrl, mem, obj, oopDesc::mark_offset_in_bytes(), TypeX_X, TypeX_X->basic_type());
2501 ctrl = opt_bits_test(ctrl, region, 3, mark_node,
2502 markWord::biased_lock_mask_in_place,
2503 markWord::biased_lock_pattern);
2504 } else {
2505 region = new RegionNode(3);
2506 // create a Phi for the memory state
2507 mem_phi = new PhiNode( region, Type::MEMORY, TypeRawPtr::BOTTOM);
2508 }
2509
2510 FastUnlockNode *funlock = new FastUnlockNode( ctrl, obj, box );
2511 funlock = transform_later( funlock )->as_FastUnlock();
2512 // Optimize test; set region slot 2
2513 Node *slow_path = opt_bits_test(ctrl, region, 2, funlock, 0, 0);
2514 Node *thread = transform_later(new ThreadLocalNode());
2515
2516 CallNode *call = make_slow_call((CallNode *) unlock, OptoRuntime::complete_monitor_exit_Type(),
2517 CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C),
2518 "complete_monitor_unlocking_C", slow_path, obj, box, thread);
2519
2520 extract_call_projections(call);
2521
2522 assert ( _ioproj_fallthrough == NULL && _ioproj_catchall == NULL &&
2523 _memproj_catchall == NULL && _catchallcatchproj == NULL, "Unexpected projection from Lock");
2524
2525 // No exceptions for unlocking
2526 // Capture slow path
2527 // disconnect fall-through projection from call and create a new one
2528 // hook up users of fall-through projection to region
2529 Node *slow_ctrl = _fallthroughproj->clone();
2530 transform_later(slow_ctrl);
2531 _igvn.hash_delete(_fallthroughproj);
2532 _fallthroughproj->disconnect_inputs(NULL, C);
2533 region->init_req(1, slow_ctrl);
2534 // region inputs are now complete
2535 transform_later(region);
2536 _igvn.replace_node(_fallthroughproj, region);
2537
2538 Node *memproj = transform_later(new ProjNode(call, TypeFunc::Memory) );
2539 mem_phi->init_req(1, memproj );
2540 mem_phi->init_req(2, mem);
2541 transform_later(mem_phi);
2542 _igvn.replace_node(_memproj_fallthrough, mem_phi);
2543 }
2544
expand_subtypecheck_node(SubTypeCheckNode * check)2545 void PhaseMacroExpand::expand_subtypecheck_node(SubTypeCheckNode *check) {
2546 assert(check->in(SubTypeCheckNode::Control) == NULL, "should be pinned");
2547 Node* bol = check->unique_out();
2548 Node* obj_or_subklass = check->in(SubTypeCheckNode::ObjOrSubKlass);
2549 Node* superklass = check->in(SubTypeCheckNode::SuperKlass);
2550 assert(bol->is_Bool() && bol->as_Bool()->_test._test == BoolTest::ne, "unexpected bool node");
2551
2552 for (DUIterator_Last imin, i = bol->last_outs(imin); i >= imin; --i) {
2553 Node* iff = bol->last_out(i);
2554 assert(iff->is_If(), "where's the if?");
2555
2556 if (iff->in(0)->is_top()) {
2557 _igvn.replace_input_of(iff, 1, C->top());
2558 continue;
2559 }
2560
2561 Node* iftrue = iff->as_If()->proj_out(1);
2562 Node* iffalse = iff->as_If()->proj_out(0);
2563 Node* ctrl = iff->in(0);
2564
2565 Node* subklass = NULL;
2566 if (_igvn.type(obj_or_subklass)->isa_klassptr()) {
2567 subklass = obj_or_subklass;
2568 } else {
2569 Node* k_adr = basic_plus_adr(obj_or_subklass, oopDesc::klass_offset_in_bytes());
2570 subklass = _igvn.transform(LoadKlassNode::make(_igvn, NULL, C->immutable_memory(), k_adr, TypeInstPtr::KLASS));
2571 }
2572
2573 Node* not_subtype_ctrl = Phase::gen_subtype_check(subklass, superklass, &ctrl, NULL, _igvn);
2574
2575 _igvn.replace_input_of(iff, 0, C->top());
2576 _igvn.replace_node(iftrue, not_subtype_ctrl);
2577 _igvn.replace_node(iffalse, ctrl);
2578 }
2579 _igvn.replace_node(check, C->top());
2580 }
2581
2582 //---------------------------eliminate_macro_nodes----------------------
2583 // Eliminate scalar replaced allocations and associated locks.
eliminate_macro_nodes()2584 void PhaseMacroExpand::eliminate_macro_nodes() {
2585 if (C->macro_count() == 0)
2586 return;
2587
2588 // First, attempt to eliminate locks
2589 int cnt = C->macro_count();
2590 for (int i=0; i < cnt; i++) {
2591 Node *n = C->macro_node(i);
2592 if (n->is_AbstractLock()) { // Lock and Unlock nodes
2593 // Before elimination mark all associated (same box and obj)
2594 // lock and unlock nodes.
2595 mark_eliminated_locking_nodes(n->as_AbstractLock());
2596 }
2597 }
2598 bool progress = true;
2599 while (progress) {
2600 progress = false;
2601 for (int i = C->macro_count(); i > 0; i--) {
2602 Node * n = C->macro_node(i-1);
2603 bool success = false;
2604 debug_only(int old_macro_count = C->macro_count(););
2605 if (n->is_AbstractLock()) {
2606 success = eliminate_locking_node(n->as_AbstractLock());
2607 }
2608 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2609 progress = progress || success;
2610 }
2611 }
2612 // Next, attempt to eliminate allocations
2613 _has_locks = false;
2614 progress = true;
2615 while (progress) {
2616 progress = false;
2617 for (int i = C->macro_count(); i > 0; i--) {
2618 Node * n = C->macro_node(i-1);
2619 bool success = false;
2620 debug_only(int old_macro_count = C->macro_count(););
2621 switch (n->class_id()) {
2622 case Node::Class_Allocate:
2623 case Node::Class_AllocateArray:
2624 success = eliminate_allocate_node(n->as_Allocate());
2625 break;
2626 case Node::Class_CallStaticJava:
2627 success = eliminate_boxing_node(n->as_CallStaticJava());
2628 break;
2629 case Node::Class_Lock:
2630 case Node::Class_Unlock:
2631 assert(!n->as_AbstractLock()->is_eliminated(), "sanity");
2632 _has_locks = true;
2633 break;
2634 case Node::Class_ArrayCopy:
2635 break;
2636 case Node::Class_OuterStripMinedLoop:
2637 break;
2638 case Node::Class_SubTypeCheck:
2639 break;
2640 case Node::Class_Opaque1:
2641 break;
2642 default:
2643 assert(n->Opcode() == Op_LoopLimit ||
2644 n->Opcode() == Op_Opaque2 ||
2645 n->Opcode() == Op_Opaque3 ||
2646 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(n),
2647 "unknown node type in macro list");
2648 }
2649 assert(success == (C->macro_count() < old_macro_count), "elimination reduces macro count");
2650 progress = progress || success;
2651 }
2652 }
2653 }
2654
2655 //------------------------------expand_macro_nodes----------------------
2656 // Returns true if a failure occurred.
expand_macro_nodes()2657 bool PhaseMacroExpand::expand_macro_nodes() {
2658 // Last attempt to eliminate macro nodes.
2659 eliminate_macro_nodes();
2660
2661 // Eliminate Opaque and LoopLimit nodes. Do it after all loop optimizations.
2662 bool progress = true;
2663 while (progress) {
2664 progress = false;
2665 for (int i = C->macro_count(); i > 0; i--) {
2666 Node* n = C->macro_node(i-1);
2667 bool success = false;
2668 debug_only(int old_macro_count = C->macro_count(););
2669 if (n->Opcode() == Op_LoopLimit) {
2670 // Remove it from macro list and put on IGVN worklist to optimize.
2671 C->remove_macro_node(n);
2672 _igvn._worklist.push(n);
2673 success = true;
2674 } else if (n->Opcode() == Op_CallStaticJava) {
2675 // Remove it from macro list and put on IGVN worklist to optimize.
2676 C->remove_macro_node(n);
2677 _igvn._worklist.push(n);
2678 success = true;
2679 } else if (n->is_Opaque1() || n->Opcode() == Op_Opaque2) {
2680 _igvn.replace_node(n, n->in(1));
2681 success = true;
2682 #if INCLUDE_RTM_OPT
2683 } else if ((n->Opcode() == Op_Opaque3) && ((Opaque3Node*)n)->rtm_opt()) {
2684 assert(C->profile_rtm(), "should be used only in rtm deoptimization code");
2685 assert((n->outcnt() == 1) && n->unique_out()->is_Cmp(), "");
2686 Node* cmp = n->unique_out();
2687 #ifdef ASSERT
2688 // Validate graph.
2689 assert((cmp->outcnt() == 1) && cmp->unique_out()->is_Bool(), "");
2690 BoolNode* bol = cmp->unique_out()->as_Bool();
2691 assert((bol->outcnt() == 1) && bol->unique_out()->is_If() &&
2692 (bol->_test._test == BoolTest::ne), "");
2693 IfNode* ifn = bol->unique_out()->as_If();
2694 assert((ifn->outcnt() == 2) &&
2695 ifn->proj_out(1)->is_uncommon_trap_proj(Deoptimization::Reason_rtm_state_change) != NULL, "");
2696 #endif
2697 Node* repl = n->in(1);
2698 if (!_has_locks) {
2699 // Remove RTM state check if there are no locks in the code.
2700 // Replace input to compare the same value.
2701 repl = (cmp->in(1) == n) ? cmp->in(2) : cmp->in(1);
2702 }
2703 _igvn.replace_node(n, repl);
2704 success = true;
2705 #endif
2706 } else if (n->Opcode() == Op_OuterStripMinedLoop) {
2707 n->as_OuterStripMinedLoop()->adjust_strip_mined_loop(&_igvn);
2708 C->remove_macro_node(n);
2709 success = true;
2710 }
2711 assert(!success || (C->macro_count() == (old_macro_count - 1)), "elimination must have deleted one node from macro list");
2712 progress = progress || success;
2713 }
2714 }
2715
2716 // Clean up the graph so we're less likely to hit the maximum node
2717 // limit
2718 _igvn.set_delay_transform(false);
2719 _igvn.optimize();
2720 if (C->failing()) return true;
2721 _igvn.set_delay_transform(true);
2722
2723
2724 // Because we run IGVN after each expansion, some macro nodes may go
2725 // dead and be removed from the list as we iterate over it. Move
2726 // Allocate nodes (processed in a second pass) at the beginning of
2727 // the list and then iterate from the last element of the list until
2728 // an Allocate node is seen. This is robust to random deletion in
2729 // the list due to nodes going dead.
2730 C->sort_macro_nodes();
2731
2732 // expand arraycopy "macro" nodes first
2733 // For ReduceBulkZeroing, we must first process all arraycopy nodes
2734 // before the allocate nodes are expanded.
2735 while (C->macro_count() > 0) {
2736 int macro_count = C->macro_count();
2737 Node * n = C->macro_node(macro_count-1);
2738 assert(n->is_macro(), "only macro nodes expected here");
2739 if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2740 // node is unreachable, so don't try to expand it
2741 C->remove_macro_node(n);
2742 continue;
2743 }
2744 if (n->is_Allocate()) {
2745 break;
2746 }
2747 // Make sure expansion will not cause node limit to be exceeded.
2748 // Worst case is a macro node gets expanded into about 200 nodes.
2749 // Allow 50% more for optimization.
2750 if (C->check_node_count(300, "out of nodes before macro expansion")) {
2751 return true;
2752 }
2753
2754 debug_only(int old_macro_count = C->macro_count(););
2755 switch (n->class_id()) {
2756 case Node::Class_Lock:
2757 expand_lock_node(n->as_Lock());
2758 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2759 break;
2760 case Node::Class_Unlock:
2761 expand_unlock_node(n->as_Unlock());
2762 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2763 break;
2764 case Node::Class_ArrayCopy:
2765 expand_arraycopy_node(n->as_ArrayCopy());
2766 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2767 break;
2768 case Node::Class_SubTypeCheck:
2769 expand_subtypecheck_node(n->as_SubTypeCheck());
2770 assert(C->macro_count() == (old_macro_count - 1), "expansion must have deleted one node from macro list");
2771 break;
2772 default:
2773 assert(false, "unknown node type in macro list");
2774 }
2775 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2776 if (C->failing()) return true;
2777
2778 // Clean up the graph so we're less likely to hit the maximum node
2779 // limit
2780 _igvn.set_delay_transform(false);
2781 _igvn.optimize();
2782 if (C->failing()) return true;
2783 _igvn.set_delay_transform(true);
2784 }
2785
2786 // All nodes except Allocate nodes are expanded now. There could be
2787 // new optimization opportunities (such as folding newly created
2788 // load from a just allocated object). Run IGVN.
2789
2790 // expand "macro" nodes
2791 // nodes are removed from the macro list as they are processed
2792 while (C->macro_count() > 0) {
2793 int macro_count = C->macro_count();
2794 Node * n = C->macro_node(macro_count-1);
2795 assert(n->is_macro(), "only macro nodes expected here");
2796 if (_igvn.type(n) == Type::TOP || (n->in(0) != NULL && n->in(0)->is_top())) {
2797 // node is unreachable, so don't try to expand it
2798 C->remove_macro_node(n);
2799 continue;
2800 }
2801 // Make sure expansion will not cause node limit to be exceeded.
2802 // Worst case is a macro node gets expanded into about 200 nodes.
2803 // Allow 50% more for optimization.
2804 if (C->check_node_count(300, "out of nodes before macro expansion")) {
2805 return true;
2806 }
2807 switch (n->class_id()) {
2808 case Node::Class_Allocate:
2809 expand_allocate(n->as_Allocate());
2810 break;
2811 case Node::Class_AllocateArray:
2812 expand_allocate_array(n->as_AllocateArray());
2813 break;
2814 default:
2815 assert(false, "unknown node type in macro list");
2816 }
2817 assert(C->macro_count() < macro_count, "must have deleted a node from macro list");
2818 if (C->failing()) return true;
2819
2820 // Clean up the graph so we're less likely to hit the maximum node
2821 // limit
2822 _igvn.set_delay_transform(false);
2823 _igvn.optimize();
2824 if (C->failing()) return true;
2825 _igvn.set_delay_transform(true);
2826 }
2827
2828 _igvn.set_delay_transform(false);
2829 return false;
2830 }
2831