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