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