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