1 /*
2 * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "gc/shared/barrierSet.hpp"
26 #include "gc/shared/c2/barrierSetC2.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "memory/resourceArea.hpp"
29 #include "oops/compressedOops.hpp"
30 #include "opto/ad.hpp"
31 #include "opto/addnode.hpp"
32 #include "opto/callnode.hpp"
33 #include "opto/idealGraphPrinter.hpp"
34 #include "opto/matcher.hpp"
35 #include "opto/memnode.hpp"
36 #include "opto/movenode.hpp"
37 #include "opto/opcodes.hpp"
38 #include "opto/regmask.hpp"
39 #include "opto/rootnode.hpp"
40 #include "opto/runtime.hpp"
41 #include "opto/type.hpp"
42 #include "opto/vectornode.hpp"
43 #include "runtime/os.inline.hpp"
44 #include "runtime/sharedRuntime.hpp"
45 #include "utilities/align.hpp"
46
47 OptoReg::Name OptoReg::c_frame_pointer;
48
49 const RegMask *Matcher::idealreg2regmask[_last_machine_leaf];
50 RegMask Matcher::mreg2regmask[_last_Mach_Reg];
51 RegMask Matcher::caller_save_regmask;
52 RegMask Matcher::caller_save_regmask_exclude_soe;
53 RegMask Matcher::STACK_ONLY_mask;
54 RegMask Matcher::c_frame_ptr_mask;
55 const uint Matcher::_begin_rematerialize = _BEGIN_REMATERIALIZE;
56 const uint Matcher::_end_rematerialize = _END_REMATERIALIZE;
57
58 //---------------------------Matcher-------------------------------------------
59 Matcher::Matcher()
60 : PhaseTransform( Phase::Ins_Select ),
61 _states_arena(Chunk::medium_size, mtCompiler, Arena::Tag::tag_states),
62 _new_nodes(C->comp_arena()),
63 _visited(&_states_arena),
64 _shared(&_states_arena),
65 _dontcare(&_states_arena),
66 _reduceOp(reduceOp), _leftOp(leftOp), _rightOp(rightOp),
67 _swallowed(swallowed),
68 _begin_inst_chain_rule(_BEGIN_INST_CHAIN_RULE),
69 _end_inst_chain_rule(_END_INST_CHAIN_RULE),
70 _must_clone(must_clone),
71 _shared_nodes(C->comp_arena()),
72 #ifndef PRODUCT
73 _old2new_map(C->comp_arena()),
74 _new2old_map(C->comp_arena()),
75 _reused(C->comp_arena()),
76 #endif // !PRODUCT
77 _allocation_started(false),
78 _ruleName(ruleName),
79 _register_save_policy(register_save_policy),
80 _c_reg_save_policy(c_reg_save_policy),
81 _register_save_type(register_save_type),
82 _return_addr_mask(C->comp_arena()) {
83 C->set_matcher(this);
84
85 idealreg2spillmask [Op_RegI] = nullptr;
86 idealreg2spillmask [Op_RegN] = nullptr;
87 idealreg2spillmask [Op_RegL] = nullptr;
88 idealreg2spillmask [Op_RegF] = nullptr;
89 idealreg2spillmask [Op_RegD] = nullptr;
90 idealreg2spillmask [Op_RegP] = nullptr;
91 idealreg2spillmask [Op_VecA] = nullptr;
92 idealreg2spillmask [Op_VecS] = nullptr;
93 idealreg2spillmask [Op_VecD] = nullptr;
94 idealreg2spillmask [Op_VecX] = nullptr;
95 idealreg2spillmask [Op_VecY] = nullptr;
96 idealreg2spillmask [Op_VecZ] = nullptr;
97 idealreg2spillmask [Op_RegFlags] = nullptr;
98 idealreg2spillmask [Op_RegVectMask] = nullptr;
99
100 idealreg2debugmask [Op_RegI] = nullptr;
101 idealreg2debugmask [Op_RegN] = nullptr;
102 idealreg2debugmask [Op_RegL] = nullptr;
103 idealreg2debugmask [Op_RegF] = nullptr;
104 idealreg2debugmask [Op_RegD] = nullptr;
105 idealreg2debugmask [Op_RegP] = nullptr;
106 idealreg2debugmask [Op_VecA] = nullptr;
107 idealreg2debugmask [Op_VecS] = nullptr;
108 idealreg2debugmask [Op_VecD] = nullptr;
109 idealreg2debugmask [Op_VecX] = nullptr;
110 idealreg2debugmask [Op_VecY] = nullptr;
111 idealreg2debugmask [Op_VecZ] = nullptr;
112 idealreg2debugmask [Op_RegFlags] = nullptr;
113 idealreg2debugmask [Op_RegVectMask] = nullptr;
114
115 DEBUG_ONLY(_mem_node = nullptr;) // Ideal memory node consumed by mach node
116 }
117
118 //------------------------------warp_incoming_stk_arg------------------------
119 // This warps a VMReg into an OptoReg::Name
120 OptoReg::Name Matcher::warp_incoming_stk_arg( VMReg reg ) {
121 OptoReg::Name warped;
122 if( reg->is_stack() ) { // Stack slot argument?
123 warped = OptoReg::add(_old_SP, reg->reg2stack() );
124 warped = OptoReg::add(warped, C->out_preserve_stack_slots());
125 if( warped >= _in_arg_limit )
126 _in_arg_limit = OptoReg::add(warped, 1); // Bump max stack slot seen
127 return warped;
128 }
129 return OptoReg::as_OptoReg(reg);
130 }
131
132 //---------------------------compute_old_SP------------------------------------
133 OptoReg::Name Compile::compute_old_SP() {
134 int fixed = fixed_slots();
135 int preserve = in_preserve_stack_slots();
136 return OptoReg::stack2reg(align_up(fixed + preserve, (int)Matcher::stack_alignment_in_slots()));
137 }
138
139
140
141 #ifdef ASSERT
142 void Matcher::verify_new_nodes_only(Node* xroot) {
143 // Make sure that the new graph only references new nodes
144 ResourceMark rm;
145 Unique_Node_List worklist;
146 VectorSet visited;
147 worklist.push(xroot);
148 while (worklist.size() > 0) {
149 Node* n = worklist.pop();
150 if (visited.test_set(n->_idx)) {
151 continue;
152 }
153 assert(C->node_arena()->contains(n), "dead node");
154 assert(!n->is_Initialize() || n->as_Initialize()->number_of_projs(TypeFunc::Memory) == 1,
155 "after matching, Initialize should have a single memory projection");
156 for (uint j = 0; j < n->req(); j++) {
157 Node* in = n->in(j);
158 if (in != nullptr) {
159 worklist.push(in);
160 }
161 }
162 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
163 worklist.push(n->fast_out(j));
164 }
165 }
166 }
167 #endif
168
169
170 //---------------------------match---------------------------------------------
171 void Matcher::match( ) {
172 if( MaxLabelRootDepth < 100 ) { // Too small?
173 assert(false, "invalid MaxLabelRootDepth, increase it to 100 minimum");
174 MaxLabelRootDepth = 100;
175 }
176 // One-time initialization of some register masks.
177 init_spill_mask( C->root()->in(1) );
178 if (C->failing()) {
179 return;
180 }
181 assert(_return_addr_mask.is_empty(),
182 "return address mask must be empty initially");
183 _return_addr_mask.insert(return_addr());
184 #ifdef _LP64
185 // Pointers take 2 slots in 64-bit land
186 _return_addr_mask.insert(OptoReg::add(return_addr(), 1));
187 #endif
188
189 // Map a Java-signature return type into return register-value
190 // machine registers for 0, 1 and 2 returned values.
191 const TypeTuple *range = C->tf()->range();
192 if( range->cnt() > TypeFunc::Parms ) { // If not a void function
193 // Get ideal-register return type
194 uint ireg = range->field_at(TypeFunc::Parms)->ideal_reg();
195 // Get machine return register
196 uint sop = C->start()->Opcode();
197 OptoRegPair regs = return_value(ireg);
198
199 // And mask for same
200 _return_value_mask.assignFrom(RegMask(regs.first()));
201 if( OptoReg::is_valid(regs.second()) )
202 _return_value_mask.insert(regs.second());
203 }
204
205 // ---------------
206 // Frame Layout
207
208 // Need the method signature to determine the incoming argument types,
209 // because the types determine which registers the incoming arguments are
210 // in, and this affects the matched code.
211 const TypeTuple *domain = C->tf()->domain();
212 uint argcnt = domain->cnt() - TypeFunc::Parms;
213 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
214 VMRegPair *vm_parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
215 _parm_regs = NEW_RESOURCE_ARRAY( OptoRegPair, argcnt );
216 _calling_convention_mask = NEW_RESOURCE_ARRAY( RegMask, argcnt );
217 uint i;
218 for( i = 0; i<argcnt; i++ ) {
219 sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
220 new (_calling_convention_mask + i) RegMask(C->comp_arena());
221 }
222
223 // Pass array of ideal registers and length to USER code (from the AD file)
224 // that will convert this to an array of register numbers.
225 const StartNode *start = C->start();
226 start->calling_convention( sig_bt, vm_parm_regs, argcnt );
227 #ifdef ASSERT
228 // Sanity check users' calling convention. Real handy while trying to
229 // get the initial port correct.
230 { for (uint i = 0; i<argcnt; i++) {
231 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
232 assert(domain->field_at(i+TypeFunc::Parms)==Type::HALF, "only allowed on halve" );
233 _parm_regs[i].set_bad();
234 continue;
235 }
236 VMReg parm_reg = vm_parm_regs[i].first();
237 assert(parm_reg->is_valid(), "invalid arg?");
238 if (parm_reg->is_reg()) {
239 OptoReg::Name opto_parm_reg = OptoReg::as_OptoReg(parm_reg);
240 assert(can_be_java_arg(opto_parm_reg) ||
241 C->stub_function() == CAST_FROM_FN_PTR(address, OptoRuntime::rethrow_C) ||
242 opto_parm_reg == inline_cache_reg(),
243 "parameters in register must be preserved by runtime stubs");
244 }
245 for (uint j = 0; j < i; j++) {
246 assert(parm_reg != vm_parm_regs[j].first(),
247 "calling conv. must produce distinct regs");
248 }
249 }
250 }
251 #endif
252
253 // Do some initial frame layout.
254
255 // Compute the old incoming SP (may be called FP) as
256 // OptoReg::stack0() + locks + in_preserve_stack_slots + pad2.
257 _old_SP = C->compute_old_SP();
258 assert( is_even(_old_SP), "must be even" );
259
260 // Compute highest incoming stack argument as
261 // _old_SP + out_preserve_stack_slots + incoming argument size.
262 _in_arg_limit = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
263 assert( is_even(_in_arg_limit), "out_preserve must be even" );
264 for( i = 0; i < argcnt; i++ ) {
265 // Permit args to have no register
266 _calling_convention_mask[i].clear();
267 if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
268 _parm_regs[i].set_bad();
269 continue;
270 }
271 // calling_convention returns stack arguments as a count of
272 // slots beyond OptoReg::stack0()/VMRegImpl::stack0. We need to convert this to
273 // the allocators point of view, taking into account all the
274 // preserve area, locks & pad2.
275
276 OptoReg::Name reg1 = warp_incoming_stk_arg(vm_parm_regs[i].first());
277 if( OptoReg::is_valid(reg1))
278 _calling_convention_mask[i].insert(reg1);
279
280 OptoReg::Name reg2 = warp_incoming_stk_arg(vm_parm_regs[i].second());
281 if( OptoReg::is_valid(reg2))
282 _calling_convention_mask[i].insert(reg2);
283
284 // Saved biased stack-slot register number
285 _parm_regs[i].set_pair(reg2, reg1);
286 }
287
288 // Allocated register sets are aligned to their size. Offsets to the stack
289 // pointer have to be aligned to the size of the access. For this _new_SP is
290 // aligned to the size of the largest register set with the stack alignment as
291 // limit and a minimum of SlotsPerLong (2).
292 int vector_aligment = MIN2(C->max_vector_size(), stack_alignment_in_bytes()) / VMRegImpl::stack_slot_size;
293 _new_SP = OptoReg::Name(align_up(_in_arg_limit, MAX2((int)RegMask::SlotsPerLong, vector_aligment)));
294
295 // Compute highest outgoing stack argument as
296 // _new_SP + out_preserve_stack_slots + max(outgoing argument size).
297 _out_arg_limit = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
298 assert( is_even(_out_arg_limit), "out_preserve must be even" );
299
300 // ---------------
301 // Collect roots of matcher trees. Every node for which
302 // _shared[_idx] is cleared is guaranteed to not be shared, and thus
303 // can be a valid interior of some tree.
304 find_shared( C->root() );
305 find_shared( C->top() );
306
307 C->print_method(PHASE_BEFORE_MATCHING, 1);
308
309 // Create new ideal node ConP #null even if it does exist in old space
310 // to avoid false sharing if the corresponding mach node is not used.
311 // The corresponding mach node is only used in rare cases for derived
312 // pointers.
313 Node* new_ideal_null = ConNode::make(TypePtr::NULL_PTR);
314
315 // Swap out to old-space; emptying new-space
316 Arena* old = C->swap_old_and_new();
317
318 // Save debug and profile information for nodes in old space:
319 _old_node_note_array = C->node_note_array();
320 if (_old_node_note_array != nullptr) {
321 C->set_node_note_array(new(C->comp_arena()) GrowableArray<Node_Notes*>
322 (C->comp_arena(), _old_node_note_array->length(),
323 0, nullptr));
324 }
325
326 // Pre-size the new_node table to avoid the need for range checks.
327 grow_new_node_array(C->unique());
328
329 // Reset node counter so MachNodes start with _idx at 0
330 int live_nodes = C->live_nodes();
331 C->set_unique(0);
332 C->reset_dead_node_list();
333
334 // Recursively match trees from old space into new space.
335 // Correct leaves of new-space Nodes; they point to old-space.
336 _visited.clear();
337 Node* const n = xform(C->top(), live_nodes);
338 if (C->failing()) return;
339 C->set_cached_top_node(n);
340 if (!C->failing()) {
341 Node* xroot = xform( C->root(), 1 );
342 if (C->failing()) return;
343 if (xroot == nullptr) {
344 Matcher::soft_match_failure(); // recursive matching process failed
345 assert(false, "instruction match failed");
346 C->record_method_not_compilable("instruction match failed");
347 } else {
348 // During matching shared constants were attached to C->root()
349 // because xroot wasn't available yet, so transfer the uses to
350 // the xroot.
351 for( DUIterator_Fast jmax, j = C->root()->fast_outs(jmax); j < jmax; j++ ) {
352 Node* n = C->root()->fast_out(j);
353 if (C->node_arena()->contains(n)) {
354 assert(n->in(0) == C->root(), "should be control user");
355 n->set_req(0, xroot);
356 --j;
357 --jmax;
358 }
359 }
360
361 // Generate new mach node for ConP #null
362 assert(new_ideal_null != nullptr, "sanity");
363 _mach_null = match_tree(new_ideal_null);
364 // Don't set control, it will confuse GCM since there are no uses.
365 // The control will be set when this node is used first time
366 // in find_base_for_derived().
367 assert(_mach_null != nullptr || C->failure_is_artificial(), ""); // bailouts are handled below.
368
369 C->set_root(xroot->is_Root() ? xroot->as_Root() : nullptr);
370
371 #ifdef ASSERT
372 verify_new_nodes_only(xroot);
373 #endif
374 }
375 }
376 if (C->top() == nullptr || C->root() == nullptr) {
377 // New graph lost. This is due to a compilation failure we encountered earlier.
378 stringStream ss;
379 if (C->failure_reason() != nullptr) {
380 ss.print("graph lost: %s", C->failure_reason());
381 } else {
382 assert(C->failure_reason() != nullptr, "graph lost: reason unknown");
383 ss.print("graph lost: reason unknown");
384 }
385 C->record_method_not_compilable(ss.as_string() DEBUG_ONLY(COMMA true));
386 }
387 if (C->failing()) {
388 // delete old;
389 old->destruct_contents();
390 return;
391 }
392 assert( C->top(), "" );
393 assert( C->root(), "" );
394 validate_null_checks();
395
396 // Now smoke old-space
397 NOT_DEBUG( old->destruct_contents() );
398
399 // ------------------------
400 // Set up save-on-entry registers.
401 Fixup_Save_On_Entry( );
402
403 { // Cleanup mach IR after selection phase is over.
404 Compile::TracePhase tp(_t_postselect_cleanup);
405 do_postselect_cleanup();
406 if (C->failing()) return;
407 assert(verify_after_postselect_cleanup(), "");
408 }
409 }
410
411 //------------------------------Fixup_Save_On_Entry----------------------------
412 // The stated purpose of this routine is to take care of save-on-entry
413 // registers. However, the overall goal of the Match phase is to convert into
414 // machine-specific instructions which have RegMasks to guide allocation.
415 // So what this procedure really does is put a valid RegMask on each input
416 // to the machine-specific variations of all Return, TailCall and Halt
417 // instructions. It also adds edgs to define the save-on-entry values (and of
418 // course gives them a mask).
419
420 static RegMask *init_input_masks( uint size, RegMask &ret_adr, RegMask &fp ) {
421 RegMask *rms = NEW_RESOURCE_ARRAY( RegMask, size );
422 for (unsigned int i = 0; i < size; ++i) {
423 new (rms + i) RegMask(Compile::current()->comp_arena());
424 }
425 // Do all the pre-defined register masks
426 rms[TypeFunc::Control ].assignFrom(RegMask::EMPTY);
427 rms[TypeFunc::I_O ].assignFrom(RegMask::EMPTY);
428 rms[TypeFunc::Memory ].assignFrom(RegMask::EMPTY);
429 rms[TypeFunc::ReturnAdr].assignFrom(ret_adr);
430 rms[TypeFunc::FramePtr ].assignFrom(fp);
431 return rms;
432 }
433
434 int Matcher::scalable_predicate_reg_slots() {
435 assert(Matcher::has_predicated_vectors() && Matcher::supports_scalable_vector(),
436 "scalable predicate vector should be supported");
437 int vector_reg_bit_size = Matcher::scalable_vector_reg_size(T_BYTE) << LogBitsPerByte;
438 // We assume each predicate register is one-eighth of the size of
439 // scalable vector register, one mask bit per vector byte.
440 int predicate_reg_bit_size = vector_reg_bit_size >> 3;
441 // Compute number of slots which is required when scalable predicate
442 // register is spilled. E.g. if scalable vector register is 640 bits,
443 // predicate register is 80 bits, which is 2.5 * slots.
444 // We will round up the slot number to power of 2, which is required
445 // by find_first_set().
446 int slots = predicate_reg_bit_size & (BitsPerInt - 1)
447 ? (predicate_reg_bit_size >> LogBitsPerInt) + 1
448 : predicate_reg_bit_size >> LogBitsPerInt;
449 return round_up_power_of_2(slots);
450 }
451
452 #define NOF_STACK_MASKS (2*13)
453
454 // Create the initial stack mask used by values spilling to the stack.
455 // Disallow any debug info in outgoing argument areas by setting the
456 // initial mask accordingly.
457 void Matcher::init_first_stack_mask() {
458
459 // Allocate storage for spill masks as masks for the appropriate load type.
460 RegMask *rms = (RegMask*)C->comp_arena()->AmallocWords(sizeof(RegMask) * NOF_STACK_MASKS);
461
462 // Initialize empty placeholder masks into the newly allocated arena
463 for (int i = 0; i < NOF_STACK_MASKS; i++) {
464 new (rms + i) RegMask(C->comp_arena());
465 }
466
467 int index = 0;
468 for (int i = Op_RegN; i <= Op_RegVectMask; ++i) {
469 idealreg2spillmask[i] = &rms[index++];
470 idealreg2debugmask[i] = &rms[index++];
471 }
472 assert(index == NOF_STACK_MASKS, "wrong size");
473
474 // At first, start with the empty mask
475 C->FIRST_STACK_mask().clear();
476
477 // Add in the incoming argument area
478 OptoReg::Name init_in = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
479 for (OptoReg::Name i = init_in; i < _in_arg_limit; i = OptoReg::add(i, 1)) {
480 C->FIRST_STACK_mask().insert(i);
481 }
482 // Add in all bits past the outgoing argument area
483 C->FIRST_STACK_mask().set_all_from(_out_arg_limit);
484
485 // Make spill masks. Registers for their class, plus FIRST_STACK_mask.
486 RegMask aligned_stack_mask(C->FIRST_STACK_mask(), C->comp_arena());
487 // Keep spill masks aligned.
488 aligned_stack_mask.clear_to_pairs();
489 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
490 RegMask scalable_stack_mask(aligned_stack_mask, C->comp_arena());
491
492 idealreg2spillmask[Op_RegP]->assignFrom(*idealreg2regmask[Op_RegP]);
493 #ifdef _LP64
494 idealreg2spillmask[Op_RegN]->assignFrom(*idealreg2regmask[Op_RegN]);
495 idealreg2spillmask[Op_RegN]->or_with(C->FIRST_STACK_mask());
496 idealreg2spillmask[Op_RegP]->or_with(aligned_stack_mask);
497 #else
498 idealreg2spillmask[Op_RegP]->or_with(C->FIRST_STACK_mask());
499 #endif
500 idealreg2spillmask[Op_RegI]->assignFrom(*idealreg2regmask[Op_RegI]);
501 idealreg2spillmask[Op_RegI]->or_with(C->FIRST_STACK_mask());
502 idealreg2spillmask[Op_RegL]->assignFrom(*idealreg2regmask[Op_RegL]);
503 idealreg2spillmask[Op_RegL]->or_with(aligned_stack_mask);
504 idealreg2spillmask[Op_RegF]->assignFrom(*idealreg2regmask[Op_RegF]);
505 idealreg2spillmask[Op_RegF]->or_with(C->FIRST_STACK_mask());
506 idealreg2spillmask[Op_RegD]->assignFrom(*idealreg2regmask[Op_RegD]);
507 idealreg2spillmask[Op_RegD]->or_with(aligned_stack_mask);
508
509 if (Matcher::has_predicated_vectors()) {
510 idealreg2spillmask[Op_RegVectMask]->assignFrom(*idealreg2regmask[Op_RegVectMask]);
511 idealreg2spillmask[Op_RegVectMask]->or_with(aligned_stack_mask);
512 } else {
513 idealreg2spillmask[Op_RegVectMask]->assignFrom(RegMask::EMPTY);
514 }
515
516 if (Matcher::vector_size_supported(T_BYTE,4)) {
517 idealreg2spillmask[Op_VecS]->assignFrom(*idealreg2regmask[Op_VecS]);
518 idealreg2spillmask[Op_VecS]->or_with(C->FIRST_STACK_mask());
519 } else {
520 idealreg2spillmask[Op_VecS]->assignFrom(RegMask::EMPTY);
521 }
522
523 if (Matcher::vector_size_supported(T_FLOAT,2)) {
524 // For VecD we need dual alignment and 8 bytes (2 slots) for spills.
525 // RA guarantees such alignment since it is needed for Double and Long values.
526 idealreg2spillmask[Op_VecD]->assignFrom(*idealreg2regmask[Op_VecD]);
527 idealreg2spillmask[Op_VecD]->or_with(aligned_stack_mask);
528 } else {
529 idealreg2spillmask[Op_VecD]->assignFrom(RegMask::EMPTY);
530 }
531
532 if (Matcher::vector_size_supported(T_FLOAT,4)) {
533 // For VecX we need quadro alignment and 16 bytes (4 slots) for spills.
534 //
535 // RA can use input arguments stack slots for spills but until RA
536 // we don't know frame size and offset of input arg stack slots.
537 //
538 // Exclude last input arg stack slots to avoid spilling vectors there
539 // otherwise vector spills could stomp over stack slots in caller frame.
540 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
541 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecX); k++) {
542 aligned_stack_mask.remove(in);
543 in = OptoReg::add(in, -1);
544 }
545 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecX);
546 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
547 idealreg2spillmask[Op_VecX]->assignFrom(*idealreg2regmask[Op_VecX]);
548 idealreg2spillmask[Op_VecX]->or_with(aligned_stack_mask);
549 } else {
550 idealreg2spillmask[Op_VecX]->assignFrom(RegMask::EMPTY);
551 }
552
553 if (Matcher::vector_size_supported(T_FLOAT,8)) {
554 // For VecY we need octo alignment and 32 bytes (8 slots) for spills.
555 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
556 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecY); k++) {
557 aligned_stack_mask.remove(in);
558 in = OptoReg::add(in, -1);
559 }
560 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecY);
561 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
562 idealreg2spillmask[Op_VecY]->assignFrom(*idealreg2regmask[Op_VecY]);
563 idealreg2spillmask[Op_VecY]->or_with(aligned_stack_mask);
564 } else {
565 idealreg2spillmask[Op_VecY]->assignFrom(RegMask::EMPTY);
566 }
567
568 if (Matcher::vector_size_supported(T_FLOAT,16)) {
569 // For VecZ we need enough alignment and 64 bytes (16 slots) for spills.
570 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
571 for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecZ); k++) {
572 aligned_stack_mask.remove(in);
573 in = OptoReg::add(in, -1);
574 }
575 aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecZ);
576 assert(aligned_stack_mask.is_infinite_stack(), "should be infinite stack");
577 idealreg2spillmask[Op_VecZ]->assignFrom(*idealreg2regmask[Op_VecZ]);
578 idealreg2spillmask[Op_VecZ]->or_with(aligned_stack_mask);
579 } else {
580 idealreg2spillmask[Op_VecZ]->assignFrom(RegMask::EMPTY);
581 }
582
583 if (Matcher::supports_scalable_vector()) {
584 int k = 1;
585 OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
586 if (Matcher::has_predicated_vectors()) {
587 // Exclude last input arg stack slots to avoid spilling vector register there,
588 // otherwise RegVectMask spills could stomp over stack slots in caller frame.
589 for (; (in >= init_in) && (k < scalable_predicate_reg_slots()); k++) {
590 scalable_stack_mask.remove(in);
591 in = OptoReg::add(in, -1);
592 }
593
594 // For RegVectMask
595 scalable_stack_mask.clear_to_sets(scalable_predicate_reg_slots());
596 assert(scalable_stack_mask.is_infinite_stack(), "should be infinite stack");
597 idealreg2spillmask[Op_RegVectMask]->assignFrom(*idealreg2regmask[Op_RegVectMask]);
598 idealreg2spillmask[Op_RegVectMask]->or_with(scalable_stack_mask);
599 }
600
601 // Exclude last input arg stack slots to avoid spilling vector register there,
602 // otherwise vector spills could stomp over stack slots in caller frame.
603 for (; (in >= init_in) && (k < scalable_vector_reg_size(T_FLOAT)); k++) {
604 scalable_stack_mask.remove(in);
605 in = OptoReg::add(in, -1);
606 }
607
608 // For VecA
609 scalable_stack_mask.clear_to_sets(RegMask::SlotsPerVecA);
610 assert(scalable_stack_mask.is_infinite_stack(), "should be infinite stack");
611 idealreg2spillmask[Op_VecA]->assignFrom(*idealreg2regmask[Op_VecA]);
612 idealreg2spillmask[Op_VecA]->or_with(scalable_stack_mask);
613 } else {
614 idealreg2spillmask[Op_VecA]->assignFrom(RegMask::EMPTY);
615 }
616
617 if (UseFPUForSpilling) {
618 // This mask logic assumes that the spill operations are
619 // symmetric and that the registers involved are the same size.
620 // On sparc for instance we may have to use 64 bit moves will
621 // kill 2 registers when used with F0-F31.
622 idealreg2spillmask[Op_RegI]->or_with(*idealreg2regmask[Op_RegF]);
623 idealreg2spillmask[Op_RegF]->or_with(*idealreg2regmask[Op_RegI]);
624 #ifdef _LP64
625 idealreg2spillmask[Op_RegN]->or_with(*idealreg2regmask[Op_RegF]);
626 idealreg2spillmask[Op_RegL]->or_with(*idealreg2regmask[Op_RegD]);
627 idealreg2spillmask[Op_RegD]->or_with(*idealreg2regmask[Op_RegL]);
628 idealreg2spillmask[Op_RegP]->or_with(*idealreg2regmask[Op_RegD]);
629 #else
630 idealreg2spillmask[Op_RegP]->or_with(*idealreg2regmask[Op_RegF]);
631 #ifdef ARM
632 // ARM has support for moving 64bit values between a pair of
633 // integer registers and a double register
634 idealreg2spillmask[Op_RegL]->or_with(*idealreg2regmask[Op_RegD]);
635 idealreg2spillmask[Op_RegD]->or_with(*idealreg2regmask[Op_RegL]);
636 #endif
637 #endif
638 }
639
640 // Make up debug masks. Any spill slot plus callee-save (SOE) registers.
641 // Caller-save (SOC, AS) registers are assumed to be trashable by the various
642 // inline-cache fixup routines.
643 idealreg2debugmask[Op_RegN]->assignFrom(*idealreg2spillmask[Op_RegN]);
644 idealreg2debugmask[Op_RegI]->assignFrom(*idealreg2spillmask[Op_RegI]);
645 idealreg2debugmask[Op_RegL]->assignFrom(*idealreg2spillmask[Op_RegL]);
646 idealreg2debugmask[Op_RegF]->assignFrom(*idealreg2spillmask[Op_RegF]);
647 idealreg2debugmask[Op_RegD]->assignFrom(*idealreg2spillmask[Op_RegD]);
648 idealreg2debugmask[Op_RegP]->assignFrom(*idealreg2spillmask[Op_RegP]);
649 idealreg2debugmask[Op_RegVectMask]->assignFrom(*idealreg2spillmask[Op_RegVectMask]);
650
651 idealreg2debugmask[Op_VecA]->assignFrom(*idealreg2spillmask[Op_VecA]);
652 idealreg2debugmask[Op_VecS]->assignFrom(*idealreg2spillmask[Op_VecS]);
653 idealreg2debugmask[Op_VecD]->assignFrom(*idealreg2spillmask[Op_VecD]);
654 idealreg2debugmask[Op_VecX]->assignFrom(*idealreg2spillmask[Op_VecX]);
655 idealreg2debugmask[Op_VecY]->assignFrom(*idealreg2spillmask[Op_VecY]);
656 idealreg2debugmask[Op_VecZ]->assignFrom(*idealreg2spillmask[Op_VecZ]);
657
658 // Prevent stub compilations from attempting to reference
659 // callee-saved (SOE) registers from debug info
660 bool exclude_soe = !Compile::current()->is_method_compilation();
661 RegMask* caller_save_mask = exclude_soe ? &caller_save_regmask_exclude_soe : &caller_save_regmask;
662
663 idealreg2debugmask[Op_RegN]->subtract(*caller_save_mask);
664 idealreg2debugmask[Op_RegI]->subtract(*caller_save_mask);
665 idealreg2debugmask[Op_RegL]->subtract(*caller_save_mask);
666 idealreg2debugmask[Op_RegF]->subtract(*caller_save_mask);
667 idealreg2debugmask[Op_RegD]->subtract(*caller_save_mask);
668 idealreg2debugmask[Op_RegP]->subtract(*caller_save_mask);
669 idealreg2debugmask[Op_RegVectMask]->subtract(*caller_save_mask);
670
671 idealreg2debugmask[Op_VecA]->subtract(*caller_save_mask);
672 idealreg2debugmask[Op_VecS]->subtract(*caller_save_mask);
673 idealreg2debugmask[Op_VecD]->subtract(*caller_save_mask);
674 idealreg2debugmask[Op_VecX]->subtract(*caller_save_mask);
675 idealreg2debugmask[Op_VecY]->subtract(*caller_save_mask);
676 idealreg2debugmask[Op_VecZ]->subtract(*caller_save_mask);
677 }
678
679 //---------------------------is_save_on_entry----------------------------------
680 bool Matcher::is_save_on_entry(int reg) {
681 return
682 _register_save_policy[reg] == 'E' ||
683 _register_save_policy[reg] == 'A'; // Save-on-entry register?
684 }
685
686 //---------------------------Fixup_Save_On_Entry-------------------------------
687 void Matcher::Fixup_Save_On_Entry( ) {
688 init_first_stack_mask();
689
690 Node *root = C->root(); // Short name for root
691 // Count number of save-on-entry registers.
692 uint soe_cnt = number_of_saved_registers();
693 uint i;
694
695 // Find the procedure Start Node
696 StartNode *start = C->start();
697 assert( start, "Expect a start node" );
698
699 // Input RegMask array shared by all Returns.
700 // The type for doubles and longs has a count of 2, but
701 // there is only 1 returned value
702 uint ret_edge_cnt = TypeFunc::Parms + ((C->tf()->range()->cnt() == TypeFunc::Parms) ? 0 : 1);
703 RegMask *ret_rms = init_input_masks( ret_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
704 // Returns have 0 or 1 returned values depending on call signature.
705 // Return register is specified by return_value in the AD file.
706 if (ret_edge_cnt > TypeFunc::Parms) {
707 ret_rms[TypeFunc::Parms + 0].assignFrom(_return_value_mask);
708 }
709
710 // Input RegMask array shared by all ForwardExceptions
711 uint forw_exc_edge_cnt = TypeFunc::Parms;
712 RegMask* forw_exc_rms = init_input_masks( forw_exc_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
713
714 // Input RegMask array shared by all Rethrows.
715 uint reth_edge_cnt = TypeFunc::Parms+1;
716 RegMask *reth_rms = init_input_masks( reth_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
717 // Rethrow takes exception oop only, but in the argument 0 slot.
718 OptoReg::Name reg = find_receiver();
719 if (reg >= 0) {
720 reth_rms[TypeFunc::Parms].assignFrom(mreg2regmask[reg]);
721 #ifdef _LP64
722 // Need two slots for ptrs in 64-bit land
723 reth_rms[TypeFunc::Parms].insert(OptoReg::add(OptoReg::Name(reg), 1));
724 #endif
725 }
726
727 // Input RegMask array shared by all TailCalls
728 uint tail_call_edge_cnt = TypeFunc::Parms+2;
729 RegMask *tail_call_rms = init_input_masks( tail_call_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
730
731 // Input RegMask array shared by all TailJumps
732 uint tail_jump_edge_cnt = TypeFunc::Parms+2;
733 RegMask *tail_jump_rms = init_input_masks( tail_jump_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
734
735 // TailCalls have 2 returned values (target & moop), whose masks come
736 // from the usual MachNode/MachOper mechanism. Find a sample
737 // TailCall to extract these masks and put the correct masks into
738 // the tail_call_rms array.
739 for( i=1; i < root->req(); i++ ) {
740 MachReturnNode *m = root->in(i)->as_MachReturn();
741 if( m->ideal_Opcode() == Op_TailCall ) {
742 tail_call_rms[TypeFunc::Parms + 0].assignFrom(m->MachNode::in_RegMask(TypeFunc::Parms + 0));
743 tail_call_rms[TypeFunc::Parms + 1].assignFrom(m->MachNode::in_RegMask(TypeFunc::Parms + 1));
744 break;
745 }
746 }
747
748 // TailJumps have 2 returned values (target & ex_oop), whose masks come
749 // from the usual MachNode/MachOper mechanism. Find a sample
750 // TailJump to extract these masks and put the correct masks into
751 // the tail_jump_rms array.
752 for( i=1; i < root->req(); i++ ) {
753 MachReturnNode *m = root->in(i)->as_MachReturn();
754 if( m->ideal_Opcode() == Op_TailJump ) {
755 tail_jump_rms[TypeFunc::Parms + 0].assignFrom(m->MachNode::in_RegMask(TypeFunc::Parms + 0));
756 tail_jump_rms[TypeFunc::Parms + 1].assignFrom(m->MachNode::in_RegMask(TypeFunc::Parms + 1));
757 break;
758 }
759 }
760
761 // Input RegMask array shared by all Halts
762 uint halt_edge_cnt = TypeFunc::Parms;
763 RegMask *halt_rms = init_input_masks( halt_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
764
765 // Capture the return input masks into each exit flavor
766 for( i=1; i < root->req(); i++ ) {
767 MachReturnNode *exit = root->in(i)->as_MachReturn();
768 switch( exit->ideal_Opcode() ) {
769 case Op_Return : exit->_in_rms = ret_rms; break;
770 case Op_Rethrow : exit->_in_rms = reth_rms; break;
771 case Op_TailCall : exit->_in_rms = tail_call_rms; break;
772 case Op_TailJump : exit->_in_rms = tail_jump_rms; break;
773 case Op_ForwardException: exit->_in_rms = forw_exc_rms; break;
774 case Op_Halt : exit->_in_rms = halt_rms; break;
775 default : ShouldNotReachHere();
776 }
777 }
778
779 // Next unused projection number from Start.
780 int proj_cnt = C->tf()->domain()->cnt();
781
782 // Do all the save-on-entry registers. Make projections from Start for
783 // them, and give them a use at the exit points. To the allocator, they
784 // look like incoming register arguments.
785 for( i = 0; i < _last_Mach_Reg; i++ ) {
786 if( is_save_on_entry(i) ) {
787
788 // Add the save-on-entry to the mask array
789 ret_rms [ ret_edge_cnt].assignFrom(mreg2regmask[i]);
790 reth_rms [ reth_edge_cnt].assignFrom(mreg2regmask[i]);
791 tail_call_rms[tail_call_edge_cnt].assignFrom(mreg2regmask[i]);
792 tail_jump_rms[tail_jump_edge_cnt].assignFrom(mreg2regmask[i]);
793 forw_exc_rms [ forw_exc_edge_cnt].assignFrom(mreg2regmask[i]);
794 // Halts need the SOE registers, but only in the stack as debug info.
795 // A just-prior uncommon-trap or deoptimization will use the SOE regs.
796 halt_rms [ halt_edge_cnt].assignFrom(*idealreg2spillmask[_register_save_type[i]]);
797
798 Node *mproj;
799
800 // Is this a RegF low half of a RegD? Double up 2 adjacent RegF's
801 // into a single RegD.
802 if( (i&1) == 0 &&
803 _register_save_type[i ] == Op_RegF &&
804 _register_save_type[i+1] == Op_RegF &&
805 is_save_on_entry(i+1) ) {
806 // Add other bit for double
807 ret_rms [ ret_edge_cnt].insert(OptoReg::Name(i+1));
808 reth_rms [ reth_edge_cnt].insert(OptoReg::Name(i+1));
809 tail_call_rms[tail_call_edge_cnt].insert(OptoReg::Name(i+1));
810 tail_jump_rms[tail_jump_edge_cnt].insert(OptoReg::Name(i+1));
811 forw_exc_rms [ forw_exc_edge_cnt].insert(OptoReg::Name(i+1));
812 halt_rms [ halt_edge_cnt].insert(OptoReg::Name(i+1));
813 mproj = new MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegD );
814 proj_cnt += 2; // Skip 2 for doubles
815 }
816 else if( (i&1) == 1 && // Else check for high half of double
817 _register_save_type[i-1] == Op_RegF &&
818 _register_save_type[i ] == Op_RegF &&
819 is_save_on_entry(i-1) ) {
820 ret_rms [ ret_edge_cnt].assignFrom(RegMask::EMPTY);
821 reth_rms [ reth_edge_cnt].assignFrom(RegMask::EMPTY);
822 tail_call_rms[tail_call_edge_cnt].assignFrom(RegMask::EMPTY);
823 tail_jump_rms[tail_jump_edge_cnt].assignFrom(RegMask::EMPTY);
824 forw_exc_rms [ forw_exc_edge_cnt].assignFrom(RegMask::EMPTY);
825 halt_rms [ halt_edge_cnt].assignFrom(RegMask::EMPTY);
826 mproj = C->top();
827 }
828 // Is this a RegI low half of a RegL? Double up 2 adjacent RegI's
829 // into a single RegL.
830 else if( (i&1) == 0 &&
831 _register_save_type[i ] == Op_RegI &&
832 _register_save_type[i+1] == Op_RegI &&
833 is_save_on_entry(i+1) ) {
834 // Add other bit for long
835 ret_rms [ ret_edge_cnt].insert(OptoReg::Name(i+1));
836 reth_rms [ reth_edge_cnt].insert(OptoReg::Name(i+1));
837 tail_call_rms[tail_call_edge_cnt].insert(OptoReg::Name(i+1));
838 tail_jump_rms[tail_jump_edge_cnt].insert(OptoReg::Name(i+1));
839 forw_exc_rms [ forw_exc_edge_cnt].insert(OptoReg::Name(i+1));
840 halt_rms [ halt_edge_cnt].insert(OptoReg::Name(i+1));
841 mproj = new MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegL );
842 proj_cnt += 2; // Skip 2 for longs
843 }
844 else if( (i&1) == 1 && // Else check for high half of long
845 _register_save_type[i-1] == Op_RegI &&
846 _register_save_type[i ] == Op_RegI &&
847 is_save_on_entry(i-1) ) {
848 ret_rms [ ret_edge_cnt].assignFrom(RegMask::EMPTY);
849 reth_rms [ reth_edge_cnt].assignFrom(RegMask::EMPTY);
850 tail_call_rms[tail_call_edge_cnt].assignFrom(RegMask::EMPTY);
851 tail_jump_rms[tail_jump_edge_cnt].assignFrom(RegMask::EMPTY);
852 forw_exc_rms [ forw_exc_edge_cnt].assignFrom(RegMask::EMPTY);
853 halt_rms [ halt_edge_cnt].assignFrom(RegMask::EMPTY);
854 mproj = C->top();
855 } else {
856 // Make a projection for it off the Start
857 mproj = new MachProjNode( start, proj_cnt++, ret_rms[ret_edge_cnt], _register_save_type[i] );
858 }
859
860 ret_edge_cnt ++;
861 reth_edge_cnt ++;
862 tail_call_edge_cnt ++;
863 tail_jump_edge_cnt ++;
864 forw_exc_edge_cnt++;
865 halt_edge_cnt ++;
866
867 // Add a use of the SOE register to all exit paths
868 for (uint j=1; j < root->req(); j++) {
869 root->in(j)->add_req(mproj);
870 }
871 } // End of if a save-on-entry register
872 } // End of for all machine registers
873 }
874
875 //------------------------------init_spill_mask--------------------------------
876 void Matcher::init_spill_mask( Node *ret ) {
877 if( idealreg2regmask[Op_RegI] ) return; // One time only init
878
879 OptoReg::c_frame_pointer = c_frame_pointer();
880 c_frame_ptr_mask.assignFrom(RegMask(c_frame_pointer()));
881 #ifdef _LP64
882 // pointers are twice as big
883 c_frame_ptr_mask.insert(OptoReg::add(c_frame_pointer(), 1));
884 #endif
885
886 // Start at OptoReg::stack0()
887 STACK_ONLY_mask.clear();
888 // STACK_ONLY_mask is all stack bits
889 STACK_ONLY_mask.set_all_from(OptoReg::stack2reg(0));
890
891 for (OptoReg::Name i = OptoReg::Name(0); i < OptoReg::Name(_last_Mach_Reg);
892 i = OptoReg::add(i, 1)) {
893 // Copy the register names over into the shared world.
894 // SharedInfo::regName[i] = regName[i];
895 // Handy RegMasks per machine register
896 mreg2regmask[i].insert(i);
897
898 // Set up regmasks used to exclude save-on-call (and always-save) registers from debug masks.
899 if (_register_save_policy[i] == 'C' ||
900 _register_save_policy[i] == 'A') {
901 caller_save_regmask.insert(i);
902 }
903 // Exclude save-on-entry registers from debug masks for stub compilations.
904 if (_register_save_policy[i] == 'C' ||
905 _register_save_policy[i] == 'A' ||
906 _register_save_policy[i] == 'E') {
907 caller_save_regmask_exclude_soe.insert(i);
908 }
909 }
910
911 // Grab the Frame Pointer
912 Node *fp = ret->in(TypeFunc::FramePtr);
913 // Share frame pointer while making spill ops
914 set_shared(fp);
915
916 // Get the ADLC notion of the right regmask, for each basic type.
917 #ifdef _LP64
918 idealreg2regmask[Op_RegN] = regmask_for_ideal_register(Op_RegN, ret);
919 #endif
920 idealreg2regmask[Op_RegI] = regmask_for_ideal_register(Op_RegI, ret);
921 idealreg2regmask[Op_RegP] = regmask_for_ideal_register(Op_RegP, ret);
922 idealreg2regmask[Op_RegF] = regmask_for_ideal_register(Op_RegF, ret);
923 idealreg2regmask[Op_RegD] = regmask_for_ideal_register(Op_RegD, ret);
924 idealreg2regmask[Op_RegL] = regmask_for_ideal_register(Op_RegL, ret);
925 idealreg2regmask[Op_VecA] = regmask_for_ideal_register(Op_VecA, ret);
926 idealreg2regmask[Op_VecS] = regmask_for_ideal_register(Op_VecS, ret);
927 idealreg2regmask[Op_VecD] = regmask_for_ideal_register(Op_VecD, ret);
928 idealreg2regmask[Op_VecX] = regmask_for_ideal_register(Op_VecX, ret);
929 idealreg2regmask[Op_VecY] = regmask_for_ideal_register(Op_VecY, ret);
930 idealreg2regmask[Op_VecZ] = regmask_for_ideal_register(Op_VecZ, ret);
931 idealreg2regmask[Op_RegVectMask] = regmask_for_ideal_register(Op_RegVectMask, ret);
932 }
933
934 #ifdef ASSERT
935 static void match_alias_type(Compile* C, Node* n, Node* m) {
936 if (!VerifyAliases) return; // do not go looking for trouble by default
937 const TypePtr* nat = n->adr_type();
938 const TypePtr* mat = m->adr_type();
939 int nidx = C->get_alias_index(nat);
940 int midx = C->get_alias_index(mat);
941 // Detune the assert for cases like (AndI 0xFF (LoadB p)).
942 if (nidx == Compile::AliasIdxTop && midx >= Compile::AliasIdxRaw) {
943 for (uint i = 1; i < n->req(); i++) {
944 Node* n1 = n->in(i);
945 const TypePtr* n1at = n1->adr_type();
946 if (n1at != nullptr) {
947 nat = n1at;
948 nidx = C->get_alias_index(n1at);
949 }
950 }
951 }
952 // %%% Kludgery. Instead, fix ideal adr_type methods for all these cases:
953 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxRaw) {
954 switch (n->Opcode()) {
955 case Op_PrefetchAllocation:
956 nidx = Compile::AliasIdxRaw;
957 nat = TypeRawPtr::BOTTOM;
958 break;
959 }
960 }
961 if (nidx == Compile::AliasIdxRaw && midx == Compile::AliasIdxTop) {
962 switch (n->Opcode()) {
963 case Op_ClearArray:
964 midx = Compile::AliasIdxRaw;
965 mat = TypeRawPtr::BOTTOM;
966 break;
967 }
968 }
969 if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxBot) {
970 switch (n->Opcode()) {
971 case Op_Return:
972 case Op_Rethrow:
973 case Op_Halt:
974 case Op_TailCall:
975 case Op_TailJump:
976 case Op_ForwardException:
977 nidx = Compile::AliasIdxBot;
978 nat = TypePtr::BOTTOM;
979 break;
980 }
981 }
982 if (nidx == Compile::AliasIdxBot && midx == Compile::AliasIdxTop) {
983 switch (n->Opcode()) {
984 case Op_StrComp:
985 case Op_StrEquals:
986 case Op_StrIndexOf:
987 case Op_StrIndexOfChar:
988 case Op_AryEq:
989 case Op_VectorizedHashCode:
990 case Op_CountPositives:
991 case Op_MemBarVolatile:
992 case Op_MemBarCPUOrder: // %%% these ideals should have narrower adr_type?
993 case Op_StrInflatedCopy:
994 case Op_StrCompressedCopy:
995 case Op_OnSpinWait:
996 case Op_EncodeISOArray:
997 nidx = Compile::AliasIdxTop;
998 nat = nullptr;
999 break;
1000 }
1001 }
1002 if (nidx != midx) {
1003 if (PrintOpto || (PrintMiscellaneous && (WizardMode || Verbose))) {
1004 tty->print_cr("==== Matcher alias shift %d => %d", nidx, midx);
1005 n->dump();
1006 m->dump();
1007 }
1008 assert(C->subsume_loads() && C->must_alias(nat, midx),
1009 "must not lose alias info when matching");
1010 }
1011 }
1012 #endif
1013
1014 //------------------------------xform------------------------------------------
1015 // Given a Node in old-space, Match him (Label/Reduce) to produce a machine
1016 // Node in new-space. Given a new-space Node, recursively walk his children.
1017 Node *Matcher::transform( Node *n ) { ShouldNotCallThis(); return n; }
1018 Node *Matcher::xform( Node *n, int max_stack ) {
1019 // Use one stack to keep both: child's node/state and parent's node/index
1020 MStack mstack(max_stack * 2 * 2); // usually: C->live_nodes() * 2 * 2
1021 mstack.push(n, Visit, nullptr, -1); // set null as parent to indicate root
1022 while (mstack.is_nonempty()) {
1023 C->check_node_count(NodeLimitFudgeFactor, "too many nodes matching instructions");
1024 if (C->failing()) return nullptr;
1025 n = mstack.node(); // Leave node on stack
1026 Node_State nstate = mstack.state();
1027 if (nstate == Visit) {
1028 mstack.set_state(Post_Visit);
1029 Node *oldn = n;
1030 // Old-space or new-space check
1031 if (!C->node_arena()->contains(n)) {
1032 // Old space!
1033 Node* m = nullptr;
1034 if (has_new_node(n)) { // Not yet Label/Reduced
1035 m = new_node(n);
1036 } else {
1037 if (!is_dontcare(n)) { // Matcher can match this guy
1038 // Calls match special. They match alone with no children.
1039 // Their children, the incoming arguments, match normally.
1040 m = n->is_SafePoint() ? match_sfpt(n->as_SafePoint()):match_tree(n);
1041 if (C->failing()) return nullptr;
1042 if (m == nullptr) { Matcher::soft_match_failure(); return nullptr; }
1043 if (n->is_MemBar()) {
1044 m->as_MachMemBar()->set_adr_type(n->adr_type());
1045 }
1046 } else { // Nothing the matcher cares about
1047 if (n->is_Proj() && n->in(0) != nullptr && n->in(0)->is_Multi()) { // Projections?
1048 if (n->in(0)->is_Initialize() && n->as_Proj()->_con == TypeFunc::Memory) {
1049 // Initialize may have multiple NarrowMem projections. They would all match to identical raw mem MachProjs.
1050 // We don't need multiple MachProjs. Create one if none already exist, otherwise use existing one.
1051 m = n->in(0)->as_Initialize()->mem_mach_proj();
1052 if (m == nullptr && has_new_node(n->in(0))) {
1053 InitializeNode* new_init = new_node(n->in(0))->as_Initialize();
1054 m = new_init->mem_mach_proj();
1055 }
1056 assert(m == nullptr || m->is_MachProj(), "no mem projection yet or a MachProj created during matching");
1057 }
1058 if (m == nullptr) {
1059 // Convert to machine-dependent projection
1060 m = n->in(0)->as_Multi()->match( n->as_Proj(), this );
1061 NOT_PRODUCT(record_new2old(m, n);)
1062 }
1063 if (m->in(0) != nullptr) // m might be top
1064 collect_null_checks(m, n);
1065 } else { // Else just a regular 'ol guy
1066 m = n->clone(); // So just clone into new-space
1067 NOT_PRODUCT(record_new2old(m, n);)
1068 // Def-Use edges will be added incrementally as Uses
1069 // of this node are matched.
1070 assert(m->outcnt() == 0, "no Uses of this clone yet");
1071 }
1072 }
1073
1074 set_new_node(n, m); // Map old to new
1075 if (_old_node_note_array != nullptr) {
1076 Node_Notes* nn = C->locate_node_notes(_old_node_note_array,
1077 n->_idx);
1078 C->set_node_notes_at(m->_idx, nn);
1079 }
1080 DEBUG_ONLY(match_alias_type(C, n, m));
1081 }
1082 n = m; // n is now a new-space node
1083 mstack.set_node(n);
1084 }
1085
1086 // New space!
1087 if (_visited.test_set(n->_idx)) continue; // while(mstack.is_nonempty())
1088
1089 int i;
1090 // Put precedence edges on stack first (match them last).
1091 for (i = oldn->req(); (uint)i < oldn->len(); i++) {
1092 Node *m = oldn->in(i);
1093 if (m == nullptr) break;
1094 // set -1 to call add_prec() instead of set_req() during Step1
1095 mstack.push(m, Visit, n, -1);
1096 }
1097
1098 // Handle precedence edges for interior nodes
1099 for (i = n->len()-1; (uint)i >= n->req(); i--) {
1100 Node *m = n->in(i);
1101 if (m == nullptr || C->node_arena()->contains(m)) continue;
1102 n->rm_prec(i);
1103 // set -1 to call add_prec() instead of set_req() during Step1
1104 mstack.push(m, Visit, n, -1);
1105 }
1106
1107 // For constant debug info, I'd rather have unmatched constants.
1108 int cnt = n->req();
1109 JVMState* jvms = n->jvms();
1110 int debug_cnt = jvms ? jvms->debug_start() : cnt;
1111
1112 // Now do only debug info. Clone constants rather than matching.
1113 // Constants are represented directly in the debug info without
1114 // the need for executable machine instructions.
1115 // Monitor boxes are also represented directly.
1116 for (i = cnt - 1; i >= debug_cnt; --i) { // For all debug inputs do
1117 Node *m = n->in(i); // Get input
1118 int op = m->Opcode();
1119 assert((op == Op_BoxLock) == jvms->is_monitor_use(i), "boxes only at monitor sites");
1120 if( op == Op_ConI || op == Op_ConP || op == Op_ConN || op == Op_ConNKlass ||
1121 op == Op_ConF || op == Op_ConD || op == Op_ConL
1122 // || op == Op_BoxLock // %%%% enable this and remove (+++) in chaitin.cpp
1123 ) {
1124 m = m->clone();
1125 NOT_PRODUCT(record_new2old(m, n));
1126 mstack.push(m, Post_Visit, n, i); // Don't need to visit
1127 mstack.push(m->in(0), Visit, m, 0);
1128 } else {
1129 mstack.push(m, Visit, n, i);
1130 }
1131 }
1132
1133 // And now walk his children, and convert his inputs to new-space.
1134 for( ; i >= 0; --i ) { // For all normal inputs do
1135 Node *m = n->in(i); // Get input
1136 if(m != nullptr)
1137 mstack.push(m, Visit, n, i);
1138 }
1139
1140 }
1141 else if (nstate == Post_Visit) {
1142 // Set xformed input
1143 Node *p = mstack.parent();
1144 if (p != nullptr) { // root doesn't have parent
1145 int i = (int)mstack.index();
1146 if (i >= 0)
1147 p->set_req(i, n); // required input
1148 else if (i == -1)
1149 p->add_prec(n); // precedence input
1150 else
1151 ShouldNotReachHere();
1152 }
1153 mstack.pop(); // remove processed node from stack
1154 }
1155 else {
1156 ShouldNotReachHere();
1157 }
1158 } // while (mstack.is_nonempty())
1159 return n; // Return new-space Node
1160 }
1161
1162 //------------------------------warp_outgoing_stk_arg------------------------
1163 OptoReg::Name Matcher::warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call ) {
1164 // Convert outgoing argument location to a pre-biased stack offset
1165 if (reg->is_stack()) {
1166 OptoReg::Name warped = reg->reg2stack();
1167 // Adjust the stack slot offset to be the register number used
1168 // by the allocator.
1169 warped = OptoReg::add(begin_out_arg_area, warped);
1170 // Keep track of the largest numbered stack slot used for an arg.
1171 // Largest used slot per call-site indicates the amount of stack
1172 // that is killed by the call.
1173 if (warped >= out_arg_limit_per_call) {
1174 out_arg_limit_per_call = OptoReg::add(warped, 1);
1175 }
1176 return warped;
1177 }
1178 return OptoReg::as_OptoReg(reg);
1179 }
1180
1181
1182 //------------------------------match_sfpt-------------------------------------
1183 // Helper function to match call instructions. Calls match special.
1184 // They match alone with no children. Their children, the incoming
1185 // arguments, match normally.
1186 MachNode *Matcher::match_sfpt( SafePointNode *sfpt ) {
1187 MachSafePointNode *msfpt = nullptr;
1188 MachCallNode *mcall = nullptr;
1189 uint cnt;
1190 // Split out case for SafePoint vs Call
1191 CallNode *call;
1192 const TypeTuple *domain;
1193 ciMethod* method = nullptr;
1194 if( sfpt->is_Call() ) {
1195 call = sfpt->as_Call();
1196 domain = call->tf()->domain();
1197 cnt = domain->cnt();
1198
1199 // Match just the call, nothing else
1200 MachNode *m = match_tree(call);
1201 if (C->failing()) return nullptr;
1202 if( m == nullptr ) { Matcher::soft_match_failure(); return nullptr; }
1203
1204 // Copy data from the Ideal SafePoint to the machine version
1205 mcall = m->as_MachCall();
1206
1207 mcall->set_tf( call->tf());
1208 mcall->set_entry_point( call->entry_point());
1209 mcall->set_cnt( call->cnt());
1210 mcall->set_guaranteed_safepoint(call->guaranteed_safepoint());
1211
1212 if( mcall->is_MachCallJava() ) {
1213 MachCallJavaNode *mcall_java = mcall->as_MachCallJava();
1214 const CallJavaNode *call_java = call->as_CallJava();
1215 assert(call_java->validate_symbolic_info(), "inconsistent info");
1216 method = call_java->method();
1217 mcall_java->_method = method;
1218 mcall_java->_optimized_virtual = call_java->is_optimized_virtual();
1219 mcall_java->_override_symbolic_info = call_java->override_symbolic_info();
1220 mcall_java->_arg_escape = call_java->arg_escape();
1221 if( mcall_java->is_MachCallStaticJava() )
1222 mcall_java->as_MachCallStaticJava()->_name =
1223 call_java->as_CallStaticJava()->_name;
1224 if( mcall_java->is_MachCallDynamicJava() )
1225 mcall_java->as_MachCallDynamicJava()->_vtable_index =
1226 call_java->as_CallDynamicJava()->_vtable_index;
1227 }
1228 else if( mcall->is_MachCallRuntime() ) {
1229 MachCallRuntimeNode* mach_call_rt = mcall->as_MachCallRuntime();
1230 mach_call_rt->_name = call->as_CallRuntime()->_name;
1231 mach_call_rt->_leaf_no_fp = call->is_CallLeafNoFP();
1232 }
1233 msfpt = mcall;
1234 }
1235 // This is a non-call safepoint
1236 else {
1237 call = nullptr;
1238 domain = nullptr;
1239 MachNode *mn = match_tree(sfpt);
1240 if (C->failing()) return nullptr;
1241 msfpt = mn->as_MachSafePoint();
1242 cnt = TypeFunc::Parms;
1243 }
1244 msfpt->_has_ea_local_in_scope = sfpt->has_ea_local_in_scope();
1245
1246 // Advertise the correct memory effects (for anti-dependence computation).
1247 msfpt->set_adr_type(sfpt->adr_type());
1248
1249 // Allocate a private array of RegMasks. These RegMasks are not shared.
1250 msfpt->_in_rms = NEW_RESOURCE_ARRAY( RegMask, cnt );
1251 // Empty them all.
1252 for (uint i = 0; i < cnt; i++) {
1253 ::new (msfpt->_in_rms + i) RegMask(C->comp_arena());
1254 }
1255
1256 // Do all the pre-defined non-Empty register masks
1257 msfpt->_in_rms[TypeFunc::ReturnAdr].assignFrom(_return_addr_mask);
1258 msfpt->_in_rms[TypeFunc::FramePtr ].assignFrom(c_frame_ptr_mask);
1259
1260 // Place first outgoing argument can possibly be put.
1261 OptoReg::Name begin_out_arg_area = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
1262 assert( is_even(begin_out_arg_area), "" );
1263 // Compute max outgoing register number per call site.
1264 OptoReg::Name out_arg_limit_per_call = begin_out_arg_area;
1265 // Calls to C may hammer extra stack slots above and beyond any arguments.
1266 // These are usually backing store for register arguments for varargs.
1267 if( call != nullptr && call->is_CallRuntime() )
1268 out_arg_limit_per_call = OptoReg::add(out_arg_limit_per_call,C->varargs_C_out_slots_killed());
1269
1270
1271 // Do the normal argument list (parameters) register masks
1272 int argcnt = cnt - TypeFunc::Parms;
1273 if( argcnt > 0 ) { // Skip it all if we have no args
1274 BasicType *sig_bt = NEW_RESOURCE_ARRAY( BasicType, argcnt );
1275 VMRegPair *parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
1276 int i;
1277 for( i = 0; i < argcnt; i++ ) {
1278 sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
1279 }
1280 // V-call to pick proper calling convention
1281 call->calling_convention( sig_bt, parm_regs, argcnt );
1282
1283 #ifdef ASSERT
1284 // Sanity check users' calling convention. Really handy during
1285 // the initial porting effort. Fairly expensive otherwise.
1286 { for (int i = 0; i<argcnt; i++) {
1287 if( !parm_regs[i].first()->is_valid() &&
1288 !parm_regs[i].second()->is_valid() ) continue;
1289 VMReg reg1 = parm_regs[i].first();
1290 VMReg reg2 = parm_regs[i].second();
1291 for (int j = 0; j < i; j++) {
1292 if( !parm_regs[j].first()->is_valid() &&
1293 !parm_regs[j].second()->is_valid() ) continue;
1294 VMReg reg3 = parm_regs[j].first();
1295 VMReg reg4 = parm_regs[j].second();
1296 if( !reg1->is_valid() ) {
1297 assert( !reg2->is_valid(), "valid halvsies" );
1298 } else if( !reg3->is_valid() ) {
1299 assert( !reg4->is_valid(), "valid halvsies" );
1300 } else {
1301 assert( reg1 != reg2, "calling conv. must produce distinct regs");
1302 assert( reg1 != reg3, "calling conv. must produce distinct regs");
1303 assert( reg1 != reg4, "calling conv. must produce distinct regs");
1304 assert( reg2 != reg3, "calling conv. must produce distinct regs");
1305 assert( reg2 != reg4 || !reg2->is_valid(), "calling conv. must produce distinct regs");
1306 assert( reg3 != reg4, "calling conv. must produce distinct regs");
1307 }
1308 }
1309 }
1310 }
1311 #endif
1312
1313 // Visit each argument. Compute its outgoing register mask.
1314 // Return results now can have 2 bits returned.
1315 // Compute max over all outgoing arguments both per call-site
1316 // and over the entire method.
1317 for( i = 0; i < argcnt; i++ ) {
1318 // Address of incoming argument mask to fill in
1319 RegMask *rm = &mcall->_in_rms[i+TypeFunc::Parms];
1320 VMReg first = parm_regs[i].first();
1321 VMReg second = parm_regs[i].second();
1322 if(!first->is_valid() &&
1323 !second->is_valid()) {
1324 continue; // Avoid Halves
1325 }
1326 // Handle case where arguments are in vector registers.
1327 if(call->in(TypeFunc::Parms + i)->bottom_type()->isa_vect()) {
1328 OptoReg::Name reg_fst = OptoReg::as_OptoReg(first);
1329 OptoReg::Name reg_snd = OptoReg::as_OptoReg(second);
1330 assert (reg_fst <= reg_snd, "fst=%d snd=%d", reg_fst, reg_snd);
1331 for (OptoReg::Name r = reg_fst; r <= reg_snd; r++) {
1332 rm->insert(r);
1333 }
1334 }
1335 // Grab first register, adjust stack slots and insert in mask.
1336 OptoReg::Name reg1 = warp_outgoing_stk_arg(first, begin_out_arg_area, out_arg_limit_per_call );
1337 if (OptoReg::is_valid(reg1))
1338 rm->insert(reg1);
1339 // Grab second register (if any), adjust stack slots and insert in mask.
1340 OptoReg::Name reg2 = warp_outgoing_stk_arg(second, begin_out_arg_area, out_arg_limit_per_call );
1341 if (OptoReg::is_valid(reg2))
1342 rm->insert(reg2);
1343 } // End of for all arguments
1344 }
1345
1346 // Compute the max stack slot killed by any call. These will not be
1347 // available for debug info, and will be used to adjust FIRST_STACK_mask
1348 // after all call sites have been visited.
1349 if( _out_arg_limit < out_arg_limit_per_call)
1350 _out_arg_limit = out_arg_limit_per_call;
1351
1352 if (mcall) {
1353 // Kill the outgoing argument area, including any non-argument holes and
1354 // any legacy C-killed slots. Use Fat-Projections to do the killing.
1355 // Since the max-per-method covers the max-per-call-site and debug info
1356 // is excluded on the max-per-method basis, debug info cannot land in
1357 // this killed area.
1358 uint r_cnt = mcall->tf()->range()->cnt();
1359 MachProjNode* proj = new MachProjNode(mcall, r_cnt + 10000, RegMask::EMPTY, MachProjNode::fat_proj);
1360 for (int i = begin_out_arg_area; i < out_arg_limit_per_call; i++) {
1361 proj->_rout.insert(OptoReg::Name(i));
1362 }
1363 if (!proj->_rout.is_empty()) {
1364 push_projection(proj);
1365 }
1366 }
1367 // Transfer the safepoint information from the call to the mcall
1368 // Move the JVMState list
1369 msfpt->set_jvms(sfpt->jvms());
1370 for (JVMState* jvms = msfpt->jvms(); jvms; jvms = jvms->caller()) {
1371 jvms->set_map(sfpt);
1372 }
1373
1374 // Debug inputs begin just after the last incoming parameter
1375 assert((mcall == nullptr) || (mcall->jvms() == nullptr) ||
1376 (mcall->jvms()->debug_start() + mcall->_jvmadj == mcall->tf()->domain()->cnt()), "");
1377
1378 // Add additional edges.
1379 if (msfpt->mach_constant_base_node_input() != (uint)-1 && !msfpt->is_MachCallLeaf()) {
1380 // For these calls we can not add MachConstantBase in expand(), as the
1381 // ins are not complete then.
1382 msfpt->ins_req(msfpt->mach_constant_base_node_input(), C->mach_constant_base_node());
1383 if (msfpt->jvms() &&
1384 msfpt->mach_constant_base_node_input() <= msfpt->jvms()->debug_start() + msfpt->_jvmadj) {
1385 // We added an edge before jvms, so we must adapt the position of the ins.
1386 msfpt->jvms()->adapt_position(+1);
1387 }
1388 }
1389
1390 // Registers killed by the call are set in the local scheduling pass
1391 // of Global Code Motion.
1392 return msfpt;
1393 }
1394
1395 //---------------------------match_tree----------------------------------------
1396 // Match a Ideal Node DAG - turn it into a tree; Label & Reduce. Used as part
1397 // of the whole-sale conversion from Ideal to Mach Nodes. Also used for
1398 // making GotoNodes while building the CFG and in init_spill_mask() to identify
1399 // a Load's result RegMask for memoization in idealreg2regmask[]
1400 MachNode *Matcher::match_tree( const Node *n ) {
1401 assert( n->Opcode() != Op_Phi, "cannot match" );
1402 assert( !n->is_block_start(), "cannot match" );
1403 // Set the mark for all locally allocated State objects.
1404 // When this call returns, the _states_arena arena will be reset
1405 // freeing all State objects.
1406 ResourceMark rm( &_states_arena );
1407
1408 LabelRootDepth = 0;
1409
1410 // StoreNodes require their Memory input to match any LoadNodes
1411 Node *mem = n->is_Store() ? n->in(MemNode::Memory) : (Node*)1 ;
1412 #ifdef ASSERT
1413 Node* save_mem_node = _mem_node;
1414 _mem_node = n->is_Store() ? (Node*)n : nullptr;
1415 #endif
1416 // State object for root node of match tree
1417 // Allocate it on _states_arena - stack allocation can cause stack overflow.
1418 State *s = new (&_states_arena) State;
1419 s->_kids[0] = nullptr;
1420 s->_kids[1] = nullptr;
1421 s->_leaf = (Node*)n;
1422 // Label the input tree, allocating labels from top-level arena
1423 Node* root_mem = mem;
1424 Label_Root(n, s, n->in(0), root_mem);
1425 if (C->failing()) return nullptr;
1426
1427 // The minimum cost match for the whole tree is found at the root State
1428 uint mincost = max_juint;
1429 uint cost = max_juint;
1430 uint i;
1431 for (i = 0; i < NUM_OPERANDS; i++) {
1432 if (s->valid(i) && // valid entry and
1433 s->cost(i) < cost && // low cost and
1434 s->rule(i) >= NUM_OPERANDS) {// not an operand
1435 mincost = i;
1436 cost = s->cost(i);
1437 }
1438 }
1439 if (mincost == max_juint) {
1440 #ifndef PRODUCT
1441 tty->print("No matching rule for:");
1442 s->dump();
1443 #endif
1444 Matcher::soft_match_failure();
1445 return nullptr;
1446 }
1447 // Reduce input tree based upon the state labels to machine Nodes
1448 MachNode *m = ReduceInst(s, s->rule(mincost), mem);
1449 // New-to-old mapping is done in ReduceInst, to cover complex instructions.
1450 NOT_PRODUCT(_old2new_map.map(n->_idx, m);)
1451
1452 // Add any Matcher-ignored edges
1453 uint cnt = n->req();
1454 uint start = 1;
1455 if( mem != (Node*)1 ) start = MemNode::Memory+1;
1456 if( n->is_AddP() ) {
1457 assert( mem == (Node*)1, "" );
1458 start = AddPNode::Base+1;
1459 }
1460 for( i = start; i < cnt; i++ ) {
1461 if( !n->match_edge(i) ) {
1462 if( i < m->req() )
1463 m->ins_req( i, n->in(i) );
1464 else
1465 m->add_req( n->in(i) );
1466 }
1467 }
1468
1469 DEBUG_ONLY( _mem_node = save_mem_node; )
1470 return m;
1471 }
1472
1473
1474 //------------------------------match_into_reg---------------------------------
1475 // Choose to either match this Node in a register or part of the current
1476 // match tree. Return true for requiring a register and false for matching
1477 // as part of the current match tree.
1478 static bool match_into_reg( const Node *n, Node *m, Node *control, int i, bool shared ) {
1479
1480 const Type *t = m->bottom_type();
1481
1482 if (t->singleton()) {
1483 // Never force constants into registers. Allow them to match as
1484 // constants or registers. Copies of the same value will share
1485 // the same register. See find_shared_node.
1486 return false;
1487 } else { // Not a constant
1488 if (!shared && Matcher::is_encode_and_store_pattern(n, m)) {
1489 // Make it possible to match "encode and store" patterns with non-shared
1490 // encode operations that are pinned to a control node (e.g. by CastPP
1491 // node removal in final graph reshaping). The matched instruction cannot
1492 // float above the encode's control node because it is pinned to the
1493 // store's control node.
1494 return false;
1495 }
1496 // Stop recursion if they have different Controls.
1497 Node* m_control = m->in(0);
1498 // Control of load's memory can post-dominates load's control.
1499 // So use it since load can't float above its memory.
1500 Node* mem_control = (m->is_Load()) ? m->in(MemNode::Memory)->in(0) : nullptr;
1501 if (control && m_control && control != m_control && control != mem_control) {
1502
1503 // Actually, we can live with the most conservative control we
1504 // find, if it post-dominates the others. This allows us to
1505 // pick up load/op/store trees where the load can float a little
1506 // above the store.
1507 Node *x = control;
1508 const uint max_scan = 6; // Arbitrary scan cutoff
1509 uint j;
1510 for (j=0; j<max_scan; j++) {
1511 if (x->is_Region()) // Bail out at merge points
1512 return true;
1513 x = x->in(0);
1514 if (x == m_control) // Does 'control' post-dominate
1515 break; // m->in(0)? If so, we can use it
1516 if (x == mem_control) // Does 'control' post-dominate
1517 break; // mem_control? If so, we can use it
1518 }
1519 if (j == max_scan) // No post-domination before scan end?
1520 return true; // Then break the match tree up
1521 }
1522 if ((m->is_DecodeN() && Matcher::narrow_oop_use_complex_address()) ||
1523 (m->is_DecodeNKlass() && Matcher::narrow_klass_use_complex_address())) {
1524 // These are commonly used in address expressions and can
1525 // efficiently fold into them on X64 in some cases.
1526 return false;
1527 }
1528 }
1529
1530 // Not forceable cloning. If shared, put it into a register.
1531 return shared;
1532 }
1533
1534
1535 //------------------------------Instruction Selection--------------------------
1536 // Label method walks a "tree" of nodes, using the ADLC generated DFA to match
1537 // ideal nodes to machine instructions. Trees are delimited by shared Nodes,
1538 // things the Matcher does not match (e.g., Memory), and things with different
1539 // Controls (hence forced into different blocks). We pass in the Control
1540 // selected for this entire State tree.
1541
1542 // The Matcher works on Trees, but an Intel add-to-memory requires a DAG: the
1543 // Store and the Load must have identical Memories (as well as identical
1544 // pointers). Since the Matcher does not have anything for Memory (and
1545 // does not handle DAGs), I have to match the Memory input myself. If the
1546 // Tree root is a Store or if there are multiple Loads in the tree, I require
1547 // all Loads to have the identical memory.
1548 Node* Matcher::Label_Root(const Node* n, State* svec, Node* control, Node*& mem) {
1549 // Since Label_Root is a recursive function, its possible that we might run
1550 // out of stack space. See bugs 6272980 & 6227033 for more info.
1551 LabelRootDepth++;
1552 if (LabelRootDepth > MaxLabelRootDepth) {
1553 // Bailout. Can for example be hit with a deep chain of operations.
1554 C->record_method_not_compilable("Out of stack space, increase MaxLabelRootDepth");
1555 return nullptr;
1556 }
1557 uint care = 0; // Edges matcher cares about
1558 uint cnt = n->req();
1559 uint i = 0;
1560
1561 // Examine children for memory state
1562 // Can only subsume a child into your match-tree if that child's memory state
1563 // is not modified along the path to another input.
1564 // It is unsafe even if the other inputs are separate roots.
1565 Node *input_mem = nullptr;
1566 for( i = 1; i < cnt; i++ ) {
1567 if( !n->match_edge(i) ) continue;
1568 Node *m = n->in(i); // Get ith input
1569 assert( m, "expect non-null children" );
1570 if( m->is_Load() ) {
1571 if( input_mem == nullptr ) {
1572 input_mem = m->in(MemNode::Memory);
1573 if (mem == (Node*)1) {
1574 // Save this memory to bail out if there's another memory access
1575 // to a different memory location in the same tree.
1576 mem = input_mem;
1577 }
1578 } else if( input_mem != m->in(MemNode::Memory) ) {
1579 input_mem = NodeSentinel;
1580 }
1581 }
1582 }
1583
1584 for( i = 1; i < cnt; i++ ){// For my children
1585 if( !n->match_edge(i) ) continue;
1586 Node *m = n->in(i); // Get ith input
1587 // Allocate states out of a private arena
1588 State *s = new (&_states_arena) State;
1589 svec->_kids[care++] = s;
1590 assert( care <= 2, "binary only for now" );
1591
1592 // Recursively label the State tree.
1593 s->_kids[0] = nullptr;
1594 s->_kids[1] = nullptr;
1595 s->_leaf = m;
1596
1597 // Check for leaves of the State Tree; things that cannot be a part of
1598 // the current tree. If it finds any, that value is matched as a
1599 // register operand. If not, then the normal matching is used.
1600 if( match_into_reg(n, m, control, i, is_shared(m)) ||
1601 // Stop recursion if this is a LoadNode and there is another memory access
1602 // to a different memory location in the same tree (for example, a StoreNode
1603 // at the root of this tree or another LoadNode in one of the children).
1604 ((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ||
1605 // Can NOT include the match of a subtree when its memory state
1606 // is used by any of the other subtrees
1607 (input_mem == NodeSentinel) ) {
1608 // Print when we exclude matching due to different memory states at input-loads
1609 if (PrintOpto && (Verbose && WizardMode) && (input_mem == NodeSentinel)
1610 && !((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem)) {
1611 tty->print_cr("invalid input_mem");
1612 }
1613 // Switch to a register-only opcode; this value must be in a register
1614 // and cannot be subsumed as part of a larger instruction.
1615 s->DFA( m->ideal_reg(), m );
1616
1617 } else {
1618 // If match tree has no control and we do, adopt it for entire tree
1619 if( control == nullptr && m->in(0) != nullptr && m->req() > 1 )
1620 control = m->in(0); // Pick up control
1621 // Else match as a normal part of the match tree.
1622 control = Label_Root(m, s, control, mem);
1623 if (C->failing()) return nullptr;
1624 }
1625 }
1626
1627 // Call DFA to match this node, and return
1628 svec->DFA( n->Opcode(), n );
1629
1630 uint x;
1631 for( x = 0; x < _LAST_MACH_OPER; x++ )
1632 if( svec->valid(x) )
1633 break;
1634
1635 if (x >= _LAST_MACH_OPER) {
1636 #ifdef ASSERT
1637 n->dump();
1638 svec->dump();
1639 #endif
1640 assert( false, "bad AD file" );
1641 C->record_failure("bad AD file");
1642 }
1643 return control;
1644 }
1645
1646
1647 // Con nodes reduced using the same rule can share their MachNode
1648 // which reduces the number of copies of a constant in the final
1649 // program. The register allocator is free to split uses later to
1650 // split live ranges.
1651 MachNode* Matcher::find_shared_node(Node* leaf, uint rule) {
1652 if (!leaf->is_Con() && !leaf->is_DecodeNarrowPtr()) return nullptr;
1653
1654 // See if this Con has already been reduced using this rule.
1655 if (_shared_nodes.max() <= leaf->_idx) return nullptr;
1656 MachNode* last = (MachNode*)_shared_nodes.at(leaf->_idx);
1657 if (last != nullptr && rule == last->rule()) {
1658 // Don't expect control change for DecodeN
1659 if (leaf->is_DecodeNarrowPtr())
1660 return last;
1661 // Get the new space root.
1662 Node* xroot = new_node(C->root());
1663 if (xroot == nullptr) {
1664 // This shouldn't happen give the order of matching.
1665 return nullptr;
1666 }
1667
1668 // Shared constants need to have their control be root so they
1669 // can be scheduled properly.
1670 Node* control = last->in(0);
1671 if (control != xroot) {
1672 if (control == nullptr || control == C->root()) {
1673 last->set_req(0, xroot);
1674 } else {
1675 assert(false, "unexpected control");
1676 return nullptr;
1677 }
1678 }
1679 return last;
1680 }
1681 return nullptr;
1682 }
1683
1684
1685 //------------------------------ReduceInst-------------------------------------
1686 // Reduce a State tree (with given Control) into a tree of MachNodes.
1687 // This routine (and it's cohort ReduceOper) convert Ideal Nodes into
1688 // complicated machine Nodes. Each MachNode covers some tree of Ideal Nodes.
1689 // Each MachNode has a number of complicated MachOper operands; each
1690 // MachOper also covers a further tree of Ideal Nodes.
1691
1692 // The root of the Ideal match tree is always an instruction, so we enter
1693 // the recursion here. After building the MachNode, we need to recurse
1694 // the tree checking for these cases:
1695 // (1) Child is an instruction -
1696 // Build the instruction (recursively), add it as an edge.
1697 // Build a simple operand (register) to hold the result of the instruction.
1698 // (2) Child is an interior part of an instruction -
1699 // Skip over it (do nothing)
1700 // (3) Child is the start of a operand -
1701 // Build the operand, place it inside the instruction
1702 // Call ReduceOper.
1703 MachNode *Matcher::ReduceInst( State *s, int rule, Node *&mem ) {
1704 assert( rule >= NUM_OPERANDS, "called with operand rule" );
1705
1706 MachNode* shared_node = find_shared_node(s->_leaf, rule);
1707 if (shared_node != nullptr) {
1708 return shared_node;
1709 }
1710
1711 // Build the object to represent this state & prepare for recursive calls
1712 MachNode *mach = s->MachNodeGenerator(rule);
1713 guarantee(mach != nullptr, "Missing MachNode");
1714 mach->_opnds[0] = s->MachOperGenerator(_reduceOp[rule]);
1715 assert( mach->_opnds[0] != nullptr, "Missing result operand" );
1716 Node *leaf = s->_leaf;
1717 NOT_PRODUCT(record_new2old(mach, leaf);)
1718 // Check for instruction or instruction chain rule
1719 if( rule >= _END_INST_CHAIN_RULE || rule < _BEGIN_INST_CHAIN_RULE ) {
1720 assert(C->node_arena()->contains(s->_leaf) || !has_new_node(s->_leaf),
1721 "duplicating node that's already been matched");
1722 // Instruction
1723 mach->add_req( leaf->in(0) ); // Set initial control
1724 // Reduce interior of complex instruction
1725 ReduceInst_Interior( s, rule, mem, mach, 1 );
1726 } else {
1727 // Instruction chain rules are data-dependent on their inputs
1728 mach->add_req(nullptr); // Set initial control to none
1729 ReduceInst_Chain_Rule( s, rule, mem, mach );
1730 }
1731
1732 // If a Memory was used, insert a Memory edge
1733 if( mem != (Node*)1 ) {
1734 mach->ins_req(MemNode::Memory,mem);
1735 #ifdef ASSERT
1736 // Verify adr type after matching memory operation
1737 const MachOper* oper = mach->memory_operand();
1738 if (oper != nullptr && oper != (MachOper*)-1) {
1739 // It has a unique memory operand. Find corresponding ideal mem node.
1740 Node* m = nullptr;
1741 if (leaf->is_Mem()) {
1742 m = leaf;
1743 } else {
1744 m = _mem_node;
1745 assert(m != nullptr && m->is_Mem(), "expecting memory node");
1746 }
1747 const Type* mach_at = mach->adr_type();
1748 // DecodeN node consumed by an address may have different type
1749 // than its input. Don't compare types for such case.
1750 if (m->adr_type() != mach_at &&
1751 (m->in(MemNode::Address)->is_DecodeNarrowPtr() ||
1752 (m->in(MemNode::Address)->is_AddP() &&
1753 m->in(MemNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr()) ||
1754 (m->in(MemNode::Address)->is_AddP() &&
1755 m->in(MemNode::Address)->in(AddPNode::Address)->is_AddP() &&
1756 m->in(MemNode::Address)->in(AddPNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr()))) {
1757 mach_at = m->adr_type();
1758 }
1759 if (m->adr_type() != mach_at) {
1760 m->dump();
1761 tty->print_cr("mach:");
1762 mach->dump(1);
1763 }
1764 assert(m->adr_type() == mach_at, "matcher should not change adr type");
1765 }
1766 #endif
1767 }
1768
1769 // If the _leaf is an AddP, insert the base edge
1770 if (leaf->is_AddP()) {
1771 mach->ins_req(AddPNode::Base,leaf->in(AddPNode::Base));
1772 }
1773
1774 uint number_of_projections_prior = number_of_projections();
1775
1776 // Perform any 1-to-many expansions required
1777 MachNode *ex = mach->Expand(s, _projection_list, mem);
1778 if (ex != mach) {
1779 assert(ex->ideal_reg() == mach->ideal_reg(), "ideal types should match");
1780 if( ex->in(1)->is_Con() )
1781 ex->in(1)->set_req(0, C->root());
1782 // Remove old node from the graph
1783 for( uint i=0; i<mach->req(); i++ ) {
1784 mach->set_req(i,nullptr);
1785 }
1786 NOT_PRODUCT(record_new2old(ex, s->_leaf);)
1787 }
1788
1789 // PhaseChaitin::fixup_spills will sometimes generate spill code
1790 // via the matcher. By the time, nodes have been wired into the CFG,
1791 // and any further nodes generated by expand rules will be left hanging
1792 // in space, and will not get emitted as output code. Catch this.
1793 // Also, catch any new register allocation constraints ("projections")
1794 // generated belatedly during spill code generation.
1795 if (_allocation_started) {
1796 guarantee(ex == mach, "no expand rules during spill generation");
1797 guarantee(number_of_projections_prior == number_of_projections(), "no allocation during spill generation");
1798 }
1799
1800 if (leaf->is_Con() || leaf->is_DecodeNarrowPtr()) {
1801 // Record the con for sharing
1802 _shared_nodes.map(leaf->_idx, ex);
1803 }
1804
1805 // Have mach nodes inherit GC barrier data
1806 mach->set_barrier_data(MemNode::barrier_data(leaf));
1807 mach->set_memory_order(MemNode::memory_order(leaf));
1808 mach->set_trailing_membar(leaf);
1809
1810 return ex;
1811 }
1812
1813 void Matcher::handle_precedence_edges(Node* n, MachNode *mach) {
1814 for (uint i = n->req(); i < n->len(); i++) {
1815 if (n->in(i) != nullptr) {
1816 mach->add_prec(n->in(i));
1817 }
1818 }
1819 }
1820
1821 void Matcher::ReduceInst_Chain_Rule(State* s, int rule, Node* &mem, MachNode* mach) {
1822 // 'op' is what I am expecting to receive
1823 int op = _leftOp[rule];
1824 // Operand type to catch childs result
1825 // This is what my child will give me.
1826 unsigned int opnd_class_instance = s->rule(op);
1827 // Choose between operand class or not.
1828 // This is what I will receive.
1829 int catch_op = (FIRST_OPERAND_CLASS <= op && op < NUM_OPERANDS) ? opnd_class_instance : op;
1830 // New rule for child. Chase operand classes to get the actual rule.
1831 unsigned int newrule = s->rule(catch_op);
1832
1833 if (newrule < NUM_OPERANDS) {
1834 // Chain from operand or operand class, may be output of shared node
1835 assert(opnd_class_instance < NUM_OPERANDS, "Bad AD file: Instruction chain rule must chain from operand");
1836 // Insert operand into array of operands for this instruction
1837 mach->_opnds[1] = s->MachOperGenerator(opnd_class_instance);
1838
1839 ReduceOper(s, newrule, mem, mach);
1840 } else {
1841 // Chain from the result of an instruction
1842 assert(newrule >= _LAST_MACH_OPER, "Do NOT chain from internal operand");
1843 mach->_opnds[1] = s->MachOperGenerator(_reduceOp[catch_op]);
1844 Node *mem1 = (Node*)1;
1845 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1846 mach->add_req( ReduceInst(s, newrule, mem1) );
1847 DEBUG_ONLY(_mem_node = save_mem_node;)
1848 }
1849 return;
1850 }
1851
1852
1853 uint Matcher::ReduceInst_Interior( State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds ) {
1854 handle_precedence_edges(s->_leaf, mach);
1855
1856 if( s->_leaf->is_Load() ) {
1857 Node *mem2 = s->_leaf->in(MemNode::Memory);
1858 assert( mem == (Node*)1 || mem == mem2, "multiple Memories being matched at once?" );
1859 DEBUG_ONLY( if( mem == (Node*)1 ) _mem_node = s->_leaf;)
1860 mem = mem2;
1861 }
1862 if( s->_leaf->in(0) != nullptr && s->_leaf->req() > 1) {
1863 if( mach->in(0) == nullptr )
1864 mach->set_req(0, s->_leaf->in(0));
1865 }
1866
1867 // Now recursively walk the state tree & add operand list.
1868 for( uint i=0; i<2; i++ ) { // binary tree
1869 State *newstate = s->_kids[i];
1870 if( newstate == nullptr ) break; // Might only have 1 child
1871 // 'op' is what I am expecting to receive
1872 int op;
1873 if( i == 0 ) {
1874 op = _leftOp[rule];
1875 } else {
1876 op = _rightOp[rule];
1877 }
1878 // Operand type to catch childs result
1879 // This is what my child will give me.
1880 int opnd_class_instance = newstate->rule(op);
1881 // Choose between operand class or not.
1882 // This is what I will receive.
1883 int catch_op = (op >= FIRST_OPERAND_CLASS && op < NUM_OPERANDS) ? opnd_class_instance : op;
1884 // New rule for child. Chase operand classes to get the actual rule.
1885 int newrule = newstate->rule(catch_op);
1886
1887 if (newrule < NUM_OPERANDS) { // Operand/operandClass or internalOp/instruction?
1888 // Operand/operandClass
1889 // Insert operand into array of operands for this instruction
1890 mach->_opnds[num_opnds++] = newstate->MachOperGenerator(opnd_class_instance);
1891 ReduceOper(newstate, newrule, mem, mach);
1892
1893 } else { // Child is internal operand or new instruction
1894 if (newrule < _LAST_MACH_OPER) { // internal operand or instruction?
1895 // internal operand --> call ReduceInst_Interior
1896 // Interior of complex instruction. Do nothing but recurse.
1897 num_opnds = ReduceInst_Interior(newstate, newrule, mem, mach, num_opnds);
1898 } else {
1899 // instruction --> call build operand( ) to catch result
1900 // --> ReduceInst( newrule )
1901 mach->_opnds[num_opnds++] = s->MachOperGenerator(_reduceOp[catch_op]);
1902 Node *mem1 = (Node*)1;
1903 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1904 mach->add_req( ReduceInst( newstate, newrule, mem1 ) );
1905 DEBUG_ONLY(_mem_node = save_mem_node;)
1906 }
1907 }
1908 assert( mach->_opnds[num_opnds-1], "" );
1909 }
1910 return num_opnds;
1911 }
1912
1913 // This routine walks the interior of possible complex operands.
1914 // At each point we check our children in the match tree:
1915 // (1) No children -
1916 // We are a leaf; add _leaf field as an input to the MachNode
1917 // (2) Child is an internal operand -
1918 // Skip over it ( do nothing )
1919 // (3) Child is an instruction -
1920 // Call ReduceInst recursively and
1921 // and instruction as an input to the MachNode
1922 void Matcher::ReduceOper( State *s, int rule, Node *&mem, MachNode *mach ) {
1923 assert( rule < _LAST_MACH_OPER, "called with operand rule" );
1924 State *kid = s->_kids[0];
1925 assert( kid == nullptr || s->_leaf->in(0) == nullptr, "internal operands have no control" );
1926
1927 // Leaf? And not subsumed?
1928 if( kid == nullptr && !_swallowed[rule] ) {
1929 mach->add_req( s->_leaf ); // Add leaf pointer
1930 return; // Bail out
1931 }
1932
1933 if( s->_leaf->is_Load() ) {
1934 assert( mem == (Node*)1, "multiple Memories being matched at once?" );
1935 mem = s->_leaf->in(MemNode::Memory);
1936 DEBUG_ONLY(_mem_node = s->_leaf;)
1937 }
1938
1939 handle_precedence_edges(s->_leaf, mach);
1940
1941 if( s->_leaf->in(0) && s->_leaf->req() > 1) {
1942 if( !mach->in(0) )
1943 mach->set_req(0,s->_leaf->in(0));
1944 else {
1945 assert( s->_leaf->in(0) == mach->in(0), "same instruction, differing controls?" );
1946 }
1947 }
1948
1949 for (uint i = 0; kid != nullptr && i < 2; kid = s->_kids[1], i++) { // binary tree
1950 int newrule;
1951 if( i == 0) {
1952 newrule = kid->rule(_leftOp[rule]);
1953 } else {
1954 newrule = kid->rule(_rightOp[rule]);
1955 }
1956
1957 if (newrule < _LAST_MACH_OPER) { // Operand or instruction?
1958 // Internal operand; recurse but do nothing else
1959 ReduceOper(kid, newrule, mem, mach);
1960
1961 } else { // Child is a new instruction
1962 // Reduce the instruction, and add a direct pointer from this
1963 // machine instruction to the newly reduced one.
1964 Node *mem1 = (Node*)1;
1965 DEBUG_ONLY(Node *save_mem_node = _mem_node;)
1966 mach->add_req( ReduceInst( kid, newrule, mem1 ) );
1967 DEBUG_ONLY(_mem_node = save_mem_node;)
1968 }
1969 }
1970 }
1971
1972
1973 // -------------------------------------------------------------------------
1974 // Java-Java calling convention
1975 // (what you use when Java calls Java)
1976
1977 //------------------------------find_receiver----------------------------------
1978 // For a given signature, return the OptoReg for parameter 0.
1979 OptoReg::Name Matcher::find_receiver() {
1980 VMRegPair regs;
1981 BasicType sig_bt = T_OBJECT;
1982 SharedRuntime::java_calling_convention(&sig_bt, ®s, 1);
1983 // Return argument 0 register. In the LP64 build pointers
1984 // take 2 registers, but the VM wants only the 'main' name.
1985 return OptoReg::as_OptoReg(regs.first());
1986 }
1987
1988 bool Matcher::is_vshift_con_pattern(Node* n, Node* m) {
1989 if (n != nullptr && m != nullptr) {
1990 return VectorNode::is_vector_shift(n) &&
1991 VectorNode::is_vector_shift_count(m) && m->in(1)->is_Con();
1992 }
1993 return false;
1994 }
1995
1996 bool Matcher::clone_node(Node* n, Node* m, Matcher::MStack& mstack) {
1997 // Must clone all producers of flags, or we will not match correctly.
1998 // Suppose a compare setting int-flags is shared (e.g., a switch-tree)
1999 // then it will match into an ideal Op_RegFlags. Alas, the fp-flags
2000 // are also there, so we may match a float-branch to int-flags and
2001 // expect the allocator to haul the flags from the int-side to the
2002 // fp-side. No can do.
2003 if (_must_clone[m->Opcode()]) {
2004 mstack.push(m, Visit);
2005 return true;
2006 }
2007 return pd_clone_node(n, m, mstack);
2008 }
2009
2010 bool Matcher::clone_base_plus_offset_address(AddPNode* m, Matcher::MStack& mstack, VectorSet& address_visited) {
2011 Node *off = m->in(AddPNode::Offset);
2012 if (off->is_Con()) {
2013 address_visited.test_set(m->_idx); // Flag as address_visited
2014 mstack.push(m->in(AddPNode::Address), Pre_Visit);
2015 // Clone X+offset as it also folds into most addressing expressions
2016 mstack.push(off, Visit);
2017 mstack.push(m->in(AddPNode::Base), Pre_Visit);
2018 return true;
2019 }
2020 return false;
2021 }
2022
2023 // A method-klass-holder may be passed in the inline_cache_reg
2024 // and then expanded into the inline_cache_reg and a method_ptr register
2025 // defined in ad_<arch>.cpp
2026
2027 //------------------------------find_shared------------------------------------
2028 // Set bits if Node is shared or otherwise a root
2029 void Matcher::find_shared(Node* n) {
2030 // Allocate stack of size C->live_nodes() * 2 to avoid frequent realloc
2031 MStack mstack(C->live_nodes() * 2);
2032 // Mark nodes as address_visited if they are inputs to an address expression
2033 VectorSet address_visited;
2034 mstack.push(n, Visit); // Don't need to pre-visit root node
2035 while (mstack.is_nonempty()) {
2036 n = mstack.node(); // Leave node on stack
2037 Node_State nstate = mstack.state();
2038 uint nop = n->Opcode();
2039 if (nstate == Pre_Visit) {
2040 if (address_visited.test(n->_idx)) { // Visited in address already?
2041 // Flag as visited and shared now.
2042 set_visited(n);
2043 }
2044 if (is_visited(n)) { // Visited already?
2045 // Node is shared and has no reason to clone. Flag it as shared.
2046 // This causes it to match into a register for the sharing.
2047 set_shared(n); // Flag as shared and
2048 if (n->is_DecodeNarrowPtr()) {
2049 // Oop field/array element loads must be shared but since
2050 // they are shared through a DecodeN they may appear to have
2051 // a single use so force sharing here.
2052 set_shared(n->in(1));
2053 }
2054 mstack.pop(); // remove node from stack
2055 continue;
2056 }
2057 nstate = Visit; // Not already visited; so visit now
2058 }
2059 if (nstate == Visit) {
2060 mstack.set_state(Post_Visit);
2061 set_visited(n); // Flag as visited now
2062 bool mem_op = false;
2063 int mem_addr_idx = MemNode::Address;
2064 if (find_shared_visit(mstack, n, nop, mem_op, mem_addr_idx)) {
2065 continue;
2066 }
2067 for (int i = n->req() - 1; i >= 0; --i) { // For my children
2068 Node* m = n->in(i); // Get ith input
2069 if (m == nullptr) {
2070 continue; // Ignore nulls
2071 }
2072 if (clone_node(n, m, mstack)) {
2073 continue;
2074 }
2075
2076 // Clone addressing expressions as they are "free" in memory access instructions
2077 if (mem_op && i == mem_addr_idx && m->is_AddP() &&
2078 // When there are other uses besides address expressions
2079 // put it on stack and mark as shared.
2080 !is_visited(m)) {
2081 // Some inputs for address expression are not put on stack
2082 // to avoid marking them as shared and forcing them into register
2083 // if they are used only in address expressions.
2084 // But they should be marked as shared if there are other uses
2085 // besides address expressions.
2086
2087 if (pd_clone_address_expressions(m->as_AddP(), mstack, address_visited)) {
2088 continue;
2089 }
2090 } // if( mem_op &&
2091 mstack.push(m, Pre_Visit);
2092 } // for(int i = ...)
2093 }
2094 else if (nstate == Alt_Post_Visit) {
2095 mstack.pop(); // Remove node from stack
2096 // We cannot remove the Cmp input from the Bool here, as the Bool may be
2097 // shared and all users of the Bool need to move the Cmp in parallel.
2098 // This leaves both the Bool and the If pointing at the Cmp. To
2099 // prevent the Matcher from trying to Match the Cmp along both paths
2100 // BoolNode::match_edge always returns a zero.
2101
2102 // We reorder the Op_If in a pre-order manner, so we can visit without
2103 // accidentally sharing the Cmp (the Bool and the If make 2 users).
2104 n->add_req( n->in(1)->in(1) ); // Add the Cmp next to the Bool
2105 }
2106 else if (nstate == Post_Visit) {
2107 mstack.pop(); // Remove node from stack
2108
2109 // Now hack a few special opcodes
2110 uint opcode = n->Opcode();
2111 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->matcher_find_shared_post_visit(this, n, opcode);
2112 if (!gc_handled) {
2113 find_shared_post_visit(n, opcode);
2114 }
2115 }
2116 else {
2117 ShouldNotReachHere();
2118 }
2119 } // end of while (mstack.is_nonempty())
2120 }
2121
2122 bool Matcher::find_shared_visit(MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx) {
2123 switch(opcode) { // Handle some opcodes special
2124 case Op_Phi: // Treat Phis as shared roots
2125 case Op_Parm:
2126 case Op_Proj: // All handled specially during matching
2127 case Op_SafePointScalarObject:
2128 set_shared(n);
2129 set_dontcare(n);
2130 break;
2131 case Op_If:
2132 case Op_CountedLoopEnd:
2133 mstack.set_state(Alt_Post_Visit); // Alternative way
2134 // Convert (If (Bool (CmpX A B))) into (If (Bool) (CmpX A B)). Helps
2135 // with matching cmp/branch in 1 instruction. The Matcher needs the
2136 // Bool and CmpX side-by-side, because it can only get at constants
2137 // that are at the leaves of Match trees, and the Bool's condition acts
2138 // as a constant here.
2139 mstack.push(n->in(1), Visit); // Clone the Bool
2140 mstack.push(n->in(0), Pre_Visit); // Visit control input
2141 return true; // while (mstack.is_nonempty())
2142 case Op_ConvI2D: // These forms efficiently match with a prior
2143 case Op_ConvI2F: // Load but not a following Store
2144 if( n->in(1)->is_Load() && // Prior load
2145 n->outcnt() == 1 && // Not already shared
2146 n->unique_out()->is_Store() ) // Following store
2147 set_shared(n); // Force it to be a root
2148 break;
2149 case Op_ReverseBytesI:
2150 case Op_ReverseBytesL:
2151 if( n->in(1)->is_Load() && // Prior load
2152 n->outcnt() == 1 ) // Not already shared
2153 set_shared(n); // Force it to be a root
2154 break;
2155 case Op_BoxLock: // Can't match until we get stack-regs in ADLC
2156 case Op_IfFalse:
2157 case Op_IfTrue:
2158 case Op_MachProj:
2159 case Op_MergeMem:
2160 case Op_Catch:
2161 case Op_CatchProj:
2162 case Op_CProj:
2163 case Op_JumpProj:
2164 case Op_JProj:
2165 case Op_NeverBranch:
2166 set_dontcare(n);
2167 break;
2168 case Op_Jump:
2169 mstack.push(n->in(1), Pre_Visit); // Switch Value (could be shared)
2170 mstack.push(n->in(0), Pre_Visit); // Visit Control input
2171 return true; // while (mstack.is_nonempty())
2172 case Op_StrComp:
2173 case Op_StrEquals:
2174 case Op_StrIndexOf:
2175 case Op_StrIndexOfChar:
2176 case Op_AryEq:
2177 case Op_VectorizedHashCode:
2178 case Op_CountPositives:
2179 case Op_StrInflatedCopy:
2180 case Op_StrCompressedCopy:
2181 case Op_EncodeISOArray:
2182 case Op_FmaD:
2183 case Op_FmaF:
2184 case Op_FmaHF:
2185 case Op_FmaVD:
2186 case Op_FmaVF:
2187 case Op_FmaVHF:
2188 case Op_MacroLogicV:
2189 case Op_VectorCmpMasked:
2190 case Op_CompressV:
2191 case Op_CompressM:
2192 case Op_ExpandV:
2193 case Op_VectorLoadMask:
2194 set_shared(n); // Force result into register (it will be anyways)
2195 break;
2196 case Op_ConP: { // Convert pointers above the centerline to NUL
2197 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2198 const TypePtr* tp = tn->type()->is_ptr();
2199 if (tp->_ptr == TypePtr::AnyNull) {
2200 tn->set_type(TypePtr::NULL_PTR);
2201 }
2202 break;
2203 }
2204 case Op_ConN: { // Convert narrow pointers above the centerline to NUL
2205 TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2206 const TypePtr* tp = tn->type()->make_ptr();
2207 if (tp && tp->_ptr == TypePtr::AnyNull) {
2208 tn->set_type(TypeNarrowOop::NULL_PTR);
2209 }
2210 break;
2211 }
2212 case Op_Binary: // These are introduced in the Post_Visit state.
2213 ShouldNotReachHere();
2214 break;
2215 case Op_ClearArray:
2216 case Op_SafePoint:
2217 mem_op = true;
2218 break;
2219 default:
2220 if( n->is_Store() ) {
2221 // Do match stores, despite no ideal reg
2222 mem_op = true;
2223 break;
2224 }
2225 if( n->is_Mem() ) { // Loads and LoadStores
2226 mem_op = true;
2227 // Loads must be root of match tree due to prior load conflict
2228 if( C->subsume_loads() == false )
2229 set_shared(n);
2230 }
2231 // Fall into default case
2232 if( !n->ideal_reg() )
2233 set_dontcare(n); // Unmatchable Nodes
2234 } // end_switch
2235 return false;
2236 }
2237
2238 void Matcher::find_shared_post_visit(Node* n, uint opcode) {
2239 if (n->is_predicated_vector()) {
2240 // Restructure into binary trees for Matching.
2241 if (n->req() == 4) {
2242 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2243 n->set_req(2, n->in(3));
2244 n->del_req(3);
2245 } else if (n->req() == 5) {
2246 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2247 n->set_req(2, new BinaryNode(n->in(3), n->in(4)));
2248 n->del_req(4);
2249 n->del_req(3);
2250 } else if (n->req() == 6) {
2251 Node* b3 = new BinaryNode(n->in(4), n->in(5));
2252 Node* b2 = new BinaryNode(n->in(3), b3);
2253 Node* b1 = new BinaryNode(n->in(2), b2);
2254 n->set_req(2, b1);
2255 n->del_req(5);
2256 n->del_req(4);
2257 n->del_req(3);
2258 }
2259 return;
2260 }
2261
2262 switch(opcode) { // Handle some opcodes special
2263 case Op_CompareAndExchangeB:
2264 case Op_CompareAndExchangeS:
2265 case Op_CompareAndExchangeI:
2266 case Op_CompareAndExchangeL:
2267 case Op_CompareAndExchangeP:
2268 case Op_CompareAndExchangeN:
2269 case Op_WeakCompareAndSwapB:
2270 case Op_WeakCompareAndSwapS:
2271 case Op_WeakCompareAndSwapI:
2272 case Op_WeakCompareAndSwapL:
2273 case Op_WeakCompareAndSwapP:
2274 case Op_WeakCompareAndSwapN:
2275 case Op_CompareAndSwapB:
2276 case Op_CompareAndSwapS:
2277 case Op_CompareAndSwapI:
2278 case Op_CompareAndSwapL:
2279 case Op_CompareAndSwapP:
2280 case Op_CompareAndSwapN: { // Convert trinary to binary-tree
2281 Node* newval = n->in(MemNode::ValueIn);
2282 Node* oldval = n->in(LoadStoreConditionalNode::ExpectedIn);
2283 Node* pair = new BinaryNode(oldval, newval);
2284 n->set_req(MemNode::ValueIn, pair);
2285 n->del_req(LoadStoreConditionalNode::ExpectedIn);
2286 break;
2287 }
2288 case Op_CMoveD: // Convert trinary to binary-tree
2289 case Op_CMoveF:
2290 case Op_CMoveI:
2291 case Op_CMoveL:
2292 case Op_CMoveN:
2293 case Op_CMoveP: {
2294 // Restructure into a binary tree for Matching. It's possible that
2295 // we could move this code up next to the graph reshaping for IfNodes
2296 // or vice-versa, but I do not want to debug this for Ladybird.
2297 // 10/2/2000 CNC.
2298 Node* pair1 = new BinaryNode(n->in(1), n->in(1)->in(1));
2299 n->set_req(1, pair1);
2300 Node* pair2 = new BinaryNode(n->in(2), n->in(3));
2301 n->set_req(2, pair2);
2302 n->del_req(3);
2303 break;
2304 }
2305 case Op_MacroLogicV: {
2306 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2307 Node* pair2 = new BinaryNode(n->in(3), n->in(4));
2308 n->set_req(1, pair1);
2309 n->set_req(2, pair2);
2310 n->del_req(4);
2311 n->del_req(3);
2312 break;
2313 }
2314 case Op_StoreVectorMasked: {
2315 Node* pair = new BinaryNode(n->in(3), n->in(4));
2316 n->set_req(3, pair);
2317 n->del_req(4);
2318 break;
2319 }
2320 case Op_SelectFromTwoVector:
2321 case Op_LoopLimit: {
2322 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2323 n->set_req(1, pair1);
2324 n->set_req(2, n->in(3));
2325 n->del_req(3);
2326 break;
2327 }
2328 case Op_StrEquals:
2329 case Op_StrIndexOfChar: {
2330 Node* pair1 = new BinaryNode(n->in(2), n->in(3));
2331 n->set_req(2, pair1);
2332 n->set_req(3, n->in(4));
2333 n->del_req(4);
2334 break;
2335 }
2336 case Op_StrComp:
2337 case Op_StrIndexOf:
2338 case Op_VectorizedHashCode: {
2339 Node* pair1 = new BinaryNode(n->in(2), n->in(3));
2340 n->set_req(2, pair1);
2341 Node* pair2 = new BinaryNode(n->in(4),n->in(5));
2342 n->set_req(3, pair2);
2343 n->del_req(5);
2344 n->del_req(4);
2345 break;
2346 }
2347 case Op_EncodeISOArray:
2348 case Op_StrCompressedCopy:
2349 case Op_StrInflatedCopy: {
2350 // Restructure into a binary tree for Matching.
2351 Node* pair = new BinaryNode(n->in(3), n->in(4));
2352 n->set_req(3, pair);
2353 n->del_req(4);
2354 break;
2355 }
2356 case Op_FmaD:
2357 case Op_FmaF:
2358 case Op_FmaHF:
2359 case Op_FmaVD:
2360 case Op_FmaVF:
2361 case Op_FmaVHF: {
2362 // Restructure into a binary tree for Matching.
2363 Node* pair = new BinaryNode(n->in(1), n->in(2));
2364 n->set_req(2, pair);
2365 n->set_req(1, n->in(3));
2366 n->del_req(3);
2367 break;
2368 }
2369 case Op_MulAddS2I: {
2370 Node* pair1 = new BinaryNode(n->in(1), n->in(2));
2371 Node* pair2 = new BinaryNode(n->in(3), n->in(4));
2372 n->set_req(1, pair1);
2373 n->set_req(2, pair2);
2374 n->del_req(4);
2375 n->del_req(3);
2376 break;
2377 }
2378 case Op_VectorCmpMasked:
2379 case Op_CopySignD:
2380 case Op_SignumVF:
2381 case Op_SignumVD:
2382 case Op_SignumF:
2383 case Op_SignumD: {
2384 Node* pair = new BinaryNode(n->in(2), n->in(3));
2385 n->set_req(2, pair);
2386 n->del_req(3);
2387 break;
2388 }
2389 case Op_VectorBlend:
2390 case Op_VectorInsert: {
2391 Node* pair = new BinaryNode(n->in(1), n->in(2));
2392 n->set_req(1, pair);
2393 n->set_req(2, n->in(3));
2394 n->del_req(3);
2395 break;
2396 }
2397 case Op_LoadVectorGatherMasked: // fall-through
2398 case Op_StoreVectorScatter: {
2399 Node* pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn+1));
2400 n->set_req(MemNode::ValueIn, pair);
2401 n->del_req(MemNode::ValueIn+1);
2402 break;
2403 }
2404 case Op_StoreVectorScatterMasked: {
2405 Node* pair = new BinaryNode(n->in(MemNode::ValueIn+1), n->in(MemNode::ValueIn+2));
2406 n->set_req(MemNode::ValueIn+1, pair);
2407 n->del_req(MemNode::ValueIn+2);
2408 pair = new BinaryNode(n->in(MemNode::ValueIn), n->in(MemNode::ValueIn+1));
2409 n->set_req(MemNode::ValueIn, pair);
2410 n->del_req(MemNode::ValueIn+1);
2411 break;
2412 }
2413 case Op_VectorMaskCmp: {
2414 n->set_req(1, new BinaryNode(n->in(1), n->in(2)));
2415 n->set_req(2, n->in(3));
2416 n->del_req(3);
2417 break;
2418 }
2419 case Op_PartialSubtypeCheck: {
2420 if (UseSecondarySupersTable && n->in(2)->is_Con()) {
2421 // PartialSubtypeCheck uses both constant and register operands for superclass input.
2422 n->set_req(2, new BinaryNode(n->in(2), n->in(2)));
2423 break;
2424 }
2425 break;
2426 }
2427 default:
2428 break;
2429 }
2430 }
2431
2432 #ifndef PRODUCT
2433 void Matcher::record_new2old(Node* newn, Node* old) {
2434 _new2old_map.map(newn->_idx, old);
2435 if (!_reused.test_set(old->_igv_idx)) {
2436 // Reuse the Ideal-level IGV identifier so that the node can be tracked
2437 // across matching. If there are multiple machine nodes expanded from the
2438 // same Ideal node, only one will reuse its IGV identifier.
2439 newn->_igv_idx = old->_igv_idx;
2440 }
2441 }
2442
2443 // machine-independent root to machine-dependent root
2444 void Matcher::dump_old2new_map() {
2445 _old2new_map.dump();
2446 }
2447 #endif // !PRODUCT
2448
2449 //---------------------------collect_null_checks-------------------------------
2450 // Find null checks in the ideal graph; write a machine-specific node for
2451 // it. Used by later implicit-null-check handling. Actually collects
2452 // either an IfTrue or IfFalse for the common NOT-null path, AND the ideal
2453 // value being tested.
2454 void Matcher::collect_null_checks( Node *proj, Node *orig_proj ) {
2455 Node *iff = proj->in(0);
2456 if( iff->Opcode() == Op_If ) {
2457 // During matching If's have Bool & Cmp side-by-side
2458 BoolNode *b = iff->in(1)->as_Bool();
2459 Node *cmp = iff->in(2);
2460 int opc = cmp->Opcode();
2461 if (opc != Op_CmpP && opc != Op_CmpN) return;
2462
2463 const Type* ct = cmp->in(2)->bottom_type();
2464 if (ct == TypePtr::NULL_PTR ||
2465 (opc == Op_CmpN && ct == TypeNarrowOop::NULL_PTR)) {
2466
2467 bool push_it = false;
2468 if( proj->Opcode() == Op_IfTrue ) {
2469 #ifndef PRODUCT
2470 extern uint all_null_checks_found;
2471 all_null_checks_found++;
2472 #endif
2473 if( b->_test._test == BoolTest::ne ) {
2474 push_it = true;
2475 }
2476 } else {
2477 assert( proj->Opcode() == Op_IfFalse, "" );
2478 if( b->_test._test == BoolTest::eq ) {
2479 push_it = true;
2480 }
2481 }
2482 if( push_it ) {
2483 _null_check_tests.push(proj);
2484 Node* val = cmp->in(1);
2485 #ifdef _LP64
2486 if (val->bottom_type()->isa_narrowoop() &&
2487 !Matcher::narrow_oop_use_complex_address()) {
2488 //
2489 // Look for DecodeN node which should be pinned to orig_proj.
2490 // On platforms (Sparc) which can not handle 2 adds
2491 // in addressing mode we have to keep a DecodeN node and
2492 // use it to do implicit null check in address.
2493 //
2494 // DecodeN node was pinned to non-null path (orig_proj) during
2495 // CastPP transformation in final_graph_reshaping_impl().
2496 //
2497 uint cnt = orig_proj->outcnt();
2498 for (uint i = 0; i < orig_proj->outcnt(); i++) {
2499 Node* d = orig_proj->raw_out(i);
2500 if (d->is_DecodeN() && d->in(1) == val) {
2501 val = d;
2502 val->set_req(0, nullptr); // Unpin now.
2503 // Mark this as special case to distinguish from
2504 // a regular case: CmpP(DecodeN, null).
2505 val = (Node*)(((intptr_t)val) | 1);
2506 break;
2507 }
2508 }
2509 }
2510 #endif
2511 _null_check_tests.push(val);
2512 }
2513 }
2514 }
2515 }
2516
2517 //---------------------------validate_null_checks------------------------------
2518 // Its possible that the value being null checked is not the root of a match
2519 // tree. If so, I cannot use the value in an implicit null check.
2520 void Matcher::validate_null_checks( ) {
2521 uint cnt = _null_check_tests.size();
2522 for( uint i=0; i < cnt; i+=2 ) {
2523 Node *test = _null_check_tests[i];
2524 Node *val = _null_check_tests[i+1];
2525 bool is_decoden = ((intptr_t)val) & 1;
2526 val = (Node*)(((intptr_t)val) & ~1);
2527 if (has_new_node(val)) {
2528 Node* new_val = new_node(val);
2529 if (is_decoden) {
2530 assert(val->is_DecodeNarrowPtr() && val->in(0) == nullptr, "sanity");
2531 // Note: new_val may have a control edge if
2532 // the original ideal node DecodeN was matched before
2533 // it was unpinned in Matcher::collect_null_checks().
2534 // Unpin the mach node and mark it.
2535 new_val->set_req(0, nullptr);
2536 new_val = (Node*)(((intptr_t)new_val) | 1);
2537 }
2538 // Is a match-tree root, so replace with the matched value
2539 _null_check_tests.map(i+1, new_val);
2540 } else {
2541 // Yank from candidate list
2542 _null_check_tests.map(i+1,_null_check_tests[--cnt]);
2543 _null_check_tests.map(i,_null_check_tests[--cnt]);
2544 _null_check_tests.pop();
2545 _null_check_tests.pop();
2546 i-=2;
2547 }
2548 }
2549 }
2550
2551 bool Matcher::gen_narrow_oop_implicit_null_checks() {
2552 // Advice matcher to perform null checks on the narrow oop side.
2553 // Implicit checks are not possible on the uncompressed oop side anyway
2554 // (at least not for read accesses).
2555 // Performs significantly better (especially on Power 6).
2556 if (!os::zero_page_read_protected()) {
2557 return true;
2558 }
2559 return CompressedOops::use_implicit_null_checks() &&
2560 (narrow_oop_use_complex_address() ||
2561 CompressedOops::base() != nullptr);
2562 }
2563
2564 // Compute RegMask for an ideal register.
2565 const RegMask* Matcher::regmask_for_ideal_register(uint ideal_reg, Node* ret) {
2566 assert(!C->failing_internal() || C->failure_is_artificial(), "already failing.");
2567 if (C->failing()) {
2568 return nullptr;
2569 }
2570 const Type* t = Type::mreg2type[ideal_reg];
2571 if (t == nullptr) {
2572 assert(ideal_reg >= Op_VecA && ideal_reg <= Op_VecZ, "not a vector: %d", ideal_reg);
2573 return nullptr; // not supported
2574 }
2575 Node* fp = ret->in(TypeFunc::FramePtr);
2576 Node* mem = ret->in(TypeFunc::Memory);
2577 const TypePtr* atp = TypePtr::BOTTOM;
2578 MemNode::MemOrd mo = MemNode::unordered;
2579
2580 Node* spill;
2581 switch (ideal_reg) {
2582 case Op_RegN: spill = new LoadNNode(nullptr, mem, fp, atp, t->is_narrowoop(), mo); break;
2583 case Op_RegI: spill = new LoadINode(nullptr, mem, fp, atp, t->is_int(), mo); break;
2584 case Op_RegP: spill = new LoadPNode(nullptr, mem, fp, atp, t->is_ptr(), mo); break;
2585 case Op_RegF: spill = new LoadFNode(nullptr, mem, fp, atp, t, mo); break;
2586 case Op_RegD: spill = new LoadDNode(nullptr, mem, fp, atp, t, mo); break;
2587 case Op_RegL: spill = new LoadLNode(nullptr, mem, fp, atp, t->is_long(), mo); break;
2588
2589 case Op_VecA: // fall-through
2590 case Op_VecS: // fall-through
2591 case Op_VecD: // fall-through
2592 case Op_VecX: // fall-through
2593 case Op_VecY: // fall-through
2594 case Op_VecZ: spill = new LoadVectorNode(nullptr, mem, fp, atp, t->is_vect()); break;
2595 case Op_RegVectMask: return Matcher::predicate_reg_mask();
2596
2597 default: ShouldNotReachHere();
2598 }
2599 MachNode* mspill = match_tree(spill);
2600 assert(mspill != nullptr || C->failure_is_artificial(), "matching failed: %d", ideal_reg);
2601 if (C->failing()) {
2602 return nullptr;
2603 }
2604 // Handle generic vector operand case
2605 if (Matcher::supports_generic_vector_operands && t->isa_vect()) {
2606 specialize_mach_node(mspill);
2607 }
2608 return &mspill->out_RegMask();
2609 }
2610
2611 // Process Mach IR right after selection phase is over.
2612 void Matcher::do_postselect_cleanup() {
2613 if (supports_generic_vector_operands) {
2614 specialize_generic_vector_operands();
2615 if (C->failing()) return;
2616 }
2617 }
2618
2619 //----------------------------------------------------------------------
2620 // Generic machine operands elision.
2621 //----------------------------------------------------------------------
2622
2623 // Compute concrete vector operand for a generic TEMP vector mach node based on its user info.
2624 void Matcher::specialize_temp_node(MachTempNode* tmp, MachNode* use, uint idx) {
2625 assert(use->in(idx) == tmp, "not a user");
2626 assert(!Matcher::is_generic_vector(use->_opnds[0]), "use not processed yet");
2627
2628 if ((uint)idx == use->two_adr()) { // DEF_TEMP case
2629 tmp->_opnds[0] = use->_opnds[0]->clone();
2630 } else {
2631 uint ideal_vreg = vector_ideal_reg(C->max_vector_size());
2632 tmp->_opnds[0] = Matcher::pd_specialize_generic_vector_operand(tmp->_opnds[0], ideal_vreg, true /*is_temp*/);
2633 }
2634 }
2635
2636 // Compute concrete vector operand for a generic DEF/USE vector operand (of mach node m at index idx).
2637 MachOper* Matcher::specialize_vector_operand(MachNode* m, uint opnd_idx) {
2638 assert(Matcher::is_generic_vector(m->_opnds[opnd_idx]), "repeated updates");
2639 Node* def = nullptr;
2640 if (opnd_idx == 0) { // DEF
2641 def = m; // use mach node itself to compute vector operand type
2642 } else {
2643 int base_idx = m->operand_index(opnd_idx);
2644 def = m->in(base_idx);
2645 if (def->is_Mach()) {
2646 if (def->is_MachTemp() && Matcher::is_generic_vector(def->as_Mach()->_opnds[0])) {
2647 specialize_temp_node(def->as_MachTemp(), m, base_idx); // MachTemp node use site
2648 } else if (is_reg2reg_move(def->as_Mach())) {
2649 def = def->in(1); // skip over generic reg-to-reg moves
2650 }
2651 }
2652 }
2653 assert(def->bottom_type()->isa_vect(), "not a vector");
2654 uint ideal_vreg = def->bottom_type()->ideal_reg();
2655 return Matcher::pd_specialize_generic_vector_operand(m->_opnds[opnd_idx], ideal_vreg, false /*is_temp*/);
2656 }
2657
2658 void Matcher::specialize_mach_node(MachNode* m) {
2659 assert(!m->is_MachTemp(), "processed along with its user");
2660 // For generic use operands pull specific register class operands from
2661 // its def instruction's output operand (def operand).
2662 for (uint i = 0; i < m->num_opnds(); i++) {
2663 if (Matcher::is_generic_vector(m->_opnds[i])) {
2664 m->_opnds[i] = specialize_vector_operand(m, i);
2665 }
2666 }
2667 }
2668
2669 // Replace generic vector operands with concrete vector operands and eliminate generic reg-to-reg moves from the graph.
2670 void Matcher::specialize_generic_vector_operands() {
2671 assert(supports_generic_vector_operands, "sanity");
2672 ResourceMark rm;
2673
2674 // Replace generic vector operands (vec/legVec) with concrete ones (vec[SDXYZ]/legVec[SDXYZ])
2675 // and remove reg-to-reg vector moves (MoveVec2Leg and MoveLeg2Vec).
2676 Unique_Node_List live_nodes;
2677 C->identify_useful_nodes(live_nodes);
2678
2679 while (live_nodes.size() > 0) {
2680 MachNode* m = live_nodes.pop()->isa_Mach();
2681 if (m != nullptr) {
2682 if (Matcher::is_reg2reg_move(m)) {
2683 // Register allocator properly handles vec <=> leg moves using register masks.
2684 int opnd_idx = m->operand_index(1);
2685 Node* def = m->in(opnd_idx);
2686 m->subsume_by(def, C);
2687 } else if (m->is_MachTemp()) {
2688 // process MachTemp nodes at use site (see Matcher::specialize_vector_operand)
2689 } else {
2690 specialize_mach_node(m);
2691 }
2692 }
2693 }
2694 }
2695
2696 uint Matcher::vector_length(const Node* n) {
2697 const TypeVect* vt = n->bottom_type()->is_vect();
2698 return vt->length();
2699 }
2700
2701 uint Matcher::vector_length(const MachNode* use, const MachOper* opnd) {
2702 int def_idx = use->operand_index(opnd);
2703 Node* def = use->in(def_idx);
2704 return def->bottom_type()->is_vect()->length();
2705 }
2706
2707 uint Matcher::vector_length_in_bytes(const Node* n) {
2708 const TypeVect* vt = n->bottom_type()->is_vect();
2709 return vt->length_in_bytes();
2710 }
2711
2712 uint Matcher::vector_length_in_bytes(const MachNode* use, const MachOper* opnd) {
2713 uint def_idx = use->operand_index(opnd);
2714 Node* def = use->in(def_idx);
2715 return def->bottom_type()->is_vect()->length_in_bytes();
2716 }
2717
2718 BasicType Matcher::vector_element_basic_type(const Node* n) {
2719 const TypeVect* vt = n->bottom_type()->is_vect();
2720 return vt->element_basic_type();
2721 }
2722
2723 BasicType Matcher::vector_element_basic_type(const MachNode* use, const MachOper* opnd) {
2724 int def_idx = use->operand_index(opnd);
2725 Node* def = use->in(def_idx);
2726 return def->bottom_type()->is_vect()->element_basic_type();
2727 }
2728
2729 bool Matcher::is_non_long_integral_vector(const Node* n) {
2730 BasicType bt = vector_element_basic_type(n);
2731 assert(bt != T_CHAR, "char is not allowed in vector");
2732 return is_subword_type(bt) || bt == T_INT;
2733 }
2734
2735 bool Matcher::is_encode_and_store_pattern(const Node* n, const Node* m) {
2736 if (n == nullptr ||
2737 m == nullptr ||
2738 n->Opcode() != Op_StoreN ||
2739 !m->is_EncodeP() ||
2740 n->as_Store()->barrier_data() == 0) {
2741 return false;
2742 }
2743 assert(m == n->in(MemNode::ValueIn), "m should be input to n");
2744 return true;
2745 }
2746
2747 #ifdef ASSERT
2748 bool Matcher::verify_after_postselect_cleanup() {
2749 assert(!C->failing_internal() || C->failure_is_artificial(), "sanity");
2750 if (supports_generic_vector_operands) {
2751 Unique_Node_List useful;
2752 C->identify_useful_nodes(useful);
2753 for (uint i = 0; i < useful.size(); i++) {
2754 MachNode* m = useful.at(i)->isa_Mach();
2755 if (m != nullptr) {
2756 assert(!Matcher::is_reg2reg_move(m), "no MoveVec nodes allowed");
2757 for (uint j = 0; j < m->num_opnds(); j++) {
2758 assert(!Matcher::is_generic_vector(m->_opnds[j]), "no generic vector operands allowed");
2759 }
2760 }
2761 }
2762 }
2763 return true;
2764 }
2765 #endif // ASSERT
2766
2767 // Used by the DFA in dfa_xxx.cpp. Check for a following barrier or
2768 // atomic instruction acting as a store_load barrier without any
2769 // intervening volatile load, and thus we don't need a barrier here.
2770 // We retain the Node to act as a compiler ordering barrier.
2771 bool Matcher::post_store_load_barrier(const Node* vmb) {
2772 Compile* C = Compile::current();
2773 assert(vmb->is_MemBar(), "");
2774 assert(vmb->Opcode() != Op_MemBarAcquire && vmb->Opcode() != Op_LoadFence, "");
2775 const MemBarNode* membar = vmb->as_MemBar();
2776
2777 // Get the Ideal Proj node, ctrl, that can be used to iterate forward
2778 Node* ctrl = nullptr;
2779 for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) {
2780 Node* p = membar->fast_out(i);
2781 assert(p->is_Proj(), "only projections here");
2782 if ((p->as_Proj()->_con == TypeFunc::Control) &&
2783 !C->node_arena()->contains(p)) { // Unmatched old-space only
2784 ctrl = p;
2785 break;
2786 }
2787 }
2788 assert((ctrl != nullptr), "missing control projection");
2789
2790 for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) {
2791 Node *x = ctrl->fast_out(j);
2792 int xop = x->Opcode();
2793
2794 // We don't need current barrier if we see another or a lock
2795 // before seeing volatile load.
2796 //
2797 // Op_Fastunlock previously appeared in the Op_* list below.
2798 // With the advent of 1-0 lock operations we're no longer guaranteed
2799 // that a monitor exit operation contains a serializing instruction.
2800
2801 if (xop == Op_MemBarVolatile ||
2802 xop == Op_CompareAndExchangeB ||
2803 xop == Op_CompareAndExchangeS ||
2804 xop == Op_CompareAndExchangeI ||
2805 xop == Op_CompareAndExchangeL ||
2806 xop == Op_CompareAndExchangeP ||
2807 xop == Op_CompareAndExchangeN ||
2808 xop == Op_WeakCompareAndSwapB ||
2809 xop == Op_WeakCompareAndSwapS ||
2810 xop == Op_WeakCompareAndSwapL ||
2811 xop == Op_WeakCompareAndSwapP ||
2812 xop == Op_WeakCompareAndSwapN ||
2813 xop == Op_WeakCompareAndSwapI ||
2814 xop == Op_CompareAndSwapB ||
2815 xop == Op_CompareAndSwapS ||
2816 xop == Op_CompareAndSwapL ||
2817 xop == Op_CompareAndSwapP ||
2818 xop == Op_CompareAndSwapN ||
2819 xop == Op_CompareAndSwapI ||
2820 BarrierSet::barrier_set()->barrier_set_c2()->matcher_is_store_load_barrier(x, xop)) {
2821 return true;
2822 }
2823
2824 // Op_FastLock previously appeared in the Op_* list above.
2825 if (xop == Op_FastLock) {
2826 return true;
2827 }
2828
2829 if (x->is_MemBar()) {
2830 // We must retain this membar if there is an upcoming volatile
2831 // load, which will be followed by acquire membar.
2832 if (xop == Op_MemBarAcquire || xop == Op_LoadFence) {
2833 return false;
2834 } else {
2835 // For other kinds of barriers, check by pretending we
2836 // are them, and seeing if we can be removed.
2837 return post_store_load_barrier(x->as_MemBar());
2838 }
2839 }
2840
2841 // probably not necessary to check for these
2842 if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) {
2843 return false;
2844 }
2845 }
2846 return false;
2847 }
2848
2849 // Check whether node n is a branch to an uncommon trap that we could
2850 // optimize as test with very high branch costs in case of going to
2851 // the uncommon trap. The code must be able to be recompiled to use
2852 // a cheaper test.
2853 bool Matcher::branches_to_uncommon_trap(const Node *n) {
2854 // Don't do it for natives, adapters, or runtime stubs
2855 Compile *C = Compile::current();
2856 if (!C->is_method_compilation()) return false;
2857
2858 assert(n->is_If(), "You should only call this on if nodes.");
2859 IfNode *ifn = n->as_If();
2860
2861 Node *ifFalse = nullptr;
2862 for (DUIterator_Fast imax, i = ifn->fast_outs(imax); i < imax; i++) {
2863 if (ifn->fast_out(i)->is_IfFalse()) {
2864 ifFalse = ifn->fast_out(i);
2865 break;
2866 }
2867 }
2868 assert(ifFalse, "An If should have an ifFalse. Graph is broken.");
2869
2870 Node *reg = ifFalse;
2871 int cnt = 4; // We must protect against cycles. Limit to 4 iterations.
2872 // Alternatively use visited set? Seems too expensive.
2873 while (reg != nullptr && cnt > 0) {
2874 CallNode *call = nullptr;
2875 RegionNode *nxt_reg = nullptr;
2876 for (DUIterator_Fast imax, i = reg->fast_outs(imax); i < imax; i++) {
2877 Node *o = reg->fast_out(i);
2878 if (o->is_Call()) {
2879 call = o->as_Call();
2880 }
2881 if (o->is_Region()) {
2882 nxt_reg = o->as_Region();
2883 }
2884 }
2885
2886 if (call &&
2887 call->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) {
2888 const Type* trtype = call->in(TypeFunc::Parms)->bottom_type();
2889 if (trtype->isa_int() && trtype->is_int()->is_con()) {
2890 jint tr_con = trtype->is_int()->get_con();
2891 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
2892 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
2893 assert((int)reason < (int)BitsPerInt, "recode bit map");
2894
2895 if (is_set_nth_bit(C->allowed_deopt_reasons(), (int)reason)
2896 && action != Deoptimization::Action_none) {
2897 // This uncommon trap is sure to recompile, eventually.
2898 // When that happens, C->too_many_traps will prevent
2899 // this transformation from happening again.
2900 return true;
2901 }
2902 }
2903 }
2904
2905 reg = nxt_reg;
2906 cnt--;
2907 }
2908
2909 return false;
2910 }
2911
2912 //=============================================================================
2913 //---------------------------State---------------------------------------------
2914 State::State(void) : _rule() {
2915 #ifdef ASSERT
2916 _id = 0;
2917 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2918 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2919 #endif
2920 }
2921
2922 #ifdef ASSERT
2923 State::~State() {
2924 _id = 99;
2925 _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2926 _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2927 memset(_cost, -3, sizeof(_cost));
2928 memset(_rule, -3, sizeof(_rule));
2929 }
2930 #endif
2931
2932 #ifndef PRODUCT
2933 //---------------------------dump----------------------------------------------
2934 void State::dump() {
2935 tty->print("\n");
2936 dump(0);
2937 }
2938
2939 void State::dump(int depth) {
2940 for (int j = 0; j < depth; j++) {
2941 tty->print(" ");
2942 }
2943 tty->print("--N: ");
2944 _leaf->dump();
2945 uint i;
2946 for (i = 0; i < _LAST_MACH_OPER; i++) {
2947 // Check for valid entry
2948 if (valid(i)) {
2949 for (int j = 0; j < depth; j++) {
2950 tty->print(" ");
2951 }
2952 assert(cost(i) != max_juint, "cost must be a valid value");
2953 assert(rule(i) < _last_Mach_Node, "rule[i] must be valid rule");
2954 tty->print_cr("%s %d %s",
2955 ruleName[i], cost(i), ruleName[rule(i)] );
2956 }
2957 }
2958 tty->cr();
2959
2960 for (i = 0; i < 2; i++) {
2961 if (_kids[i]) {
2962 _kids[i]->dump(depth + 1);
2963 }
2964 }
2965 }
2966 #endif