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