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