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