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