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