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