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