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