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