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