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