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