1 /*
   2  * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // FORMS.CPP - Definitions for ADL Parser Forms Classes
  26 #include "adlc.hpp"
  27 
  28 //==============================Instructions===================================
  29 //------------------------------InstructForm-----------------------------------
  30 InstructForm::InstructForm(const char *id, bool ideal_only)
  31   : _ident(id), _ideal_only(ideal_only),
  32     _localNames(cmpstr, hashstr, Form::arena),
  33     _effects(cmpstr, hashstr, Form::arena),
  34     _is_mach_constant(false)
  35 {
  36       _ftype = Form::INS;
  37 
  38       _matrule   = NULL;
  39       _insencode = NULL;
  40       _constant  = NULL;
  41       _opcode    = NULL;
  42       _size      = NULL;
  43       _attribs   = NULL;
  44       _predicate = NULL;
  45       _exprule   = NULL;
  46       _rewrule   = NULL;
  47       _format    = NULL;
  48       _peephole  = NULL;
  49       _ins_pipe  = NULL;
  50       _uniq_idx  = NULL;
  51       _num_uniq  = 0;
  52       _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
  53       _cisc_spill_alternate = NULL;            // possible cisc replacement
  54       _cisc_reg_mask_name = NULL;
  55       _is_cisc_alternate = false;
  56       _is_short_branch = false;
  57       _short_branch_form = NULL;
  58       _alignment = 1;
  59 }
  60 
  61 InstructForm::InstructForm(const char *id, InstructForm *instr, MatchRule *rule)
  62   : _ident(id), _ideal_only(false),
  63     _localNames(instr->_localNames),
  64     _effects(instr->_effects),
  65     _is_mach_constant(false)
  66 {
  67       _ftype = Form::INS;
  68 
  69       _matrule   = rule;
  70       _insencode = instr->_insencode;
  71       _constant  = instr->_constant;
  72       _opcode    = instr->_opcode;
  73       _size      = instr->_size;
  74       _attribs   = instr->_attribs;
  75       _predicate = instr->_predicate;
  76       _exprule   = instr->_exprule;
  77       _rewrule   = instr->_rewrule;
  78       _format    = instr->_format;
  79       _peephole  = instr->_peephole;
  80       _ins_pipe  = instr->_ins_pipe;
  81       _uniq_idx  = instr->_uniq_idx;
  82       _num_uniq  = instr->_num_uniq;
  83       _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
  84       _cisc_spill_alternate = NULL;            // possible cisc replacement
  85       _cisc_reg_mask_name = NULL;
  86       _is_cisc_alternate = false;
  87       _is_short_branch = false;
  88       _short_branch_form = NULL;
  89       _alignment = 1;
  90      // Copy parameters
  91      const char *name;
  92      instr->_parameters.reset();
  93      for (; (name = instr->_parameters.iter()) != NULL;)
  94        _parameters.addName(name);
  95 }
  96 
  97 InstructForm::~InstructForm() {
  98 }
  99 
 100 InstructForm *InstructForm::is_instruction() const {
 101   return (InstructForm*)this;
 102 }
 103 
 104 bool InstructForm::ideal_only() const {
 105   return _ideal_only;
 106 }
 107 
 108 bool InstructForm::sets_result() const {
 109   return (_matrule != NULL && _matrule->sets_result());
 110 }
 111 
 112 bool InstructForm::needs_projections() {
 113   _components.reset();
 114   for( Component *comp; (comp = _components.iter()) != NULL; ) {
 115     if (comp->isa(Component::KILL)) {
 116       return true;
 117     }
 118   }
 119   return false;
 120 }
 121 
 122 
 123 bool InstructForm::has_temps() {
 124   if (_matrule) {
 125     // Examine each component to see if it is a TEMP
 126     _components.reset();
 127     // Skip the first component, if already handled as (SET dst (...))
 128     Component *comp = NULL;
 129     if (sets_result())  comp = _components.iter();
 130     while ((comp = _components.iter()) != NULL) {
 131       if (comp->isa(Component::TEMP)) {
 132         return true;
 133       }
 134     }
 135   }
 136 
 137   return false;
 138 }
 139 
 140 uint InstructForm::num_defs_or_kills() {
 141   uint   defs_or_kills = 0;
 142 
 143   _components.reset();
 144   for( Component *comp; (comp = _components.iter()) != NULL; ) {
 145     if( comp->isa(Component::DEF) || comp->isa(Component::KILL) ) {
 146       ++defs_or_kills;
 147     }
 148   }
 149 
 150   return  defs_or_kills;
 151 }
 152 
 153 // This instruction has an expand rule?
 154 bool InstructForm::expands() const {
 155   return ( _exprule != NULL );
 156 }
 157 
 158 // This instruction has a peephole rule?
 159 Peephole *InstructForm::peepholes() const {
 160   return _peephole;
 161 }
 162 
 163 // This instruction has a peephole rule?
 164 void InstructForm::append_peephole(Peephole *peephole) {
 165   if( _peephole == NULL ) {
 166     _peephole = peephole;
 167   } else {
 168     _peephole->append_peephole(peephole);
 169   }
 170 }
 171 
 172 
 173 // ideal opcode enumeration
 174 const char *InstructForm::ideal_Opcode( FormDict &globalNames )  const {
 175   if( !_matrule ) return "Node"; // Something weird
 176   // Chain rules do not really have ideal Opcodes; use their source
 177   // operand ideal Opcode instead.
 178   if( is_simple_chain_rule(globalNames) ) {
 179     const char *src = _matrule->_rChild->_opType;
 180     OperandForm *src_op = globalNames[src]->is_operand();
 181     assert( src_op, "Not operand class of chain rule" );
 182     if( !src_op->_matrule ) return "Node";
 183     return src_op->_matrule->_opType;
 184   }
 185   // Operand chain rules do not really have ideal Opcodes
 186   if( _matrule->is_chain_rule(globalNames) )
 187     return "Node";
 188   return strcmp(_matrule->_opType,"Set")
 189     ? _matrule->_opType
 190     : _matrule->_rChild->_opType;
 191 }
 192 
 193 // Recursive check on all operands' match rules in my match rule
 194 bool InstructForm::is_pinned(FormDict &globals) {
 195   if ( ! _matrule)  return false;
 196 
 197   int  index   = 0;
 198   if (_matrule->find_type("Goto",          index)) return true;
 199   if (_matrule->find_type("If",            index)) return true;
 200   if (_matrule->find_type("CountedLoopEnd",index)) return true;
 201   if (_matrule->find_type("Return",        index)) return true;
 202   if (_matrule->find_type("Rethrow",       index)) return true;
 203   if (_matrule->find_type("TailCall",      index)) return true;
 204   if (_matrule->find_type("TailJump",      index)) return true;
 205   if (_matrule->find_type("Halt",          index)) return true;
 206   if (_matrule->find_type("Jump",          index)) return true;
 207 
 208   return is_parm(globals);
 209 }
 210 
 211 // Recursive check on all operands' match rules in my match rule
 212 bool InstructForm::is_projection(FormDict &globals) {
 213   if ( ! _matrule)  return false;
 214 
 215   int  index   = 0;
 216   if (_matrule->find_type("Goto",    index)) return true;
 217   if (_matrule->find_type("Return",  index)) return true;
 218   if (_matrule->find_type("Rethrow", index)) return true;
 219   if (_matrule->find_type("TailCall",index)) return true;
 220   if (_matrule->find_type("TailJump",index)) return true;
 221   if (_matrule->find_type("Halt",    index)) return true;
 222 
 223   return false;
 224 }
 225 
 226 // Recursive check on all operands' match rules in my match rule
 227 bool InstructForm::is_parm(FormDict &globals) {
 228   if ( ! _matrule)  return false;
 229 
 230   int  index   = 0;
 231   if (_matrule->find_type("Parm",index)) return true;
 232 
 233   return false;
 234 }
 235 
 236 
 237 // Return 'true' if this instruction matches an ideal 'Copy*' node
 238 int InstructForm::is_ideal_copy() const {
 239   return _matrule ? _matrule->is_ideal_copy() : 0;
 240 }
 241 
 242 // Return 'true' if this instruction is too complex to rematerialize.
 243 int InstructForm::is_expensive() const {
 244   // We can prove it is cheap if it has an empty encoding.
 245   // This helps with platform-specific nops like ThreadLocal and RoundFloat.
 246   if (is_empty_encoding())
 247     return 0;
 248 
 249   if (is_tls_instruction())
 250     return 1;
 251 
 252   if (_matrule == NULL)  return 0;
 253 
 254   return _matrule->is_expensive();
 255 }
 256 
 257 // Has an empty encoding if _size is a constant zero or there
 258 // are no ins_encode tokens.
 259 int InstructForm::is_empty_encoding() const {
 260   if (_insencode != NULL) {
 261     _insencode->reset();
 262     if (_insencode->encode_class_iter() == NULL) {
 263       return 1;
 264     }
 265   }
 266   if (_size != NULL && strcmp(_size, "0") == 0) {
 267     return 1;
 268   }
 269   return 0;
 270 }
 271 
 272 int InstructForm::is_tls_instruction() const {
 273   if (_ident != NULL &&
 274       ( ! strcmp( _ident,"tlsLoadP") ||
 275         ! strncmp(_ident,"tlsLoadP_",9)) ) {
 276     return 1;
 277   }
 278 
 279   if (_matrule != NULL && _insencode != NULL) {
 280     const char* opType = _matrule->_opType;
 281     if (strcmp(opType, "Set")==0)
 282       opType = _matrule->_rChild->_opType;
 283     if (strcmp(opType,"ThreadLocal")==0) {
 284       fprintf(stderr, "Warning: ThreadLocal instruction %s should be named 'tlsLoadP_*'\n",
 285               (_ident == NULL ? "NULL" : _ident));
 286       return 1;
 287     }
 288   }
 289 
 290   return 0;
 291 }
 292 
 293 
 294 // Return 'true' if this instruction matches an ideal 'If' node
 295 bool InstructForm::is_ideal_if() const {
 296   if( _matrule == NULL ) return false;
 297 
 298   return _matrule->is_ideal_if();
 299 }
 300 
 301 // Return 'true' if this instruction matches an ideal 'FastLock' node
 302 bool InstructForm::is_ideal_fastlock() const {
 303   if( _matrule == NULL ) return false;
 304 
 305   return _matrule->is_ideal_fastlock();
 306 }
 307 
 308 // Return 'true' if this instruction matches an ideal 'MemBarXXX' node
 309 bool InstructForm::is_ideal_membar() const {
 310   if( _matrule == NULL ) return false;
 311 
 312   return _matrule->is_ideal_membar();
 313 }
 314 
 315 // Return 'true' if this instruction matches an ideal 'LoadPC' node
 316 bool InstructForm::is_ideal_loadPC() const {
 317   if( _matrule == NULL ) return false;
 318 
 319   return _matrule->is_ideal_loadPC();
 320 }
 321 
 322 // Return 'true' if this instruction matches an ideal 'Box' node
 323 bool InstructForm::is_ideal_box() const {
 324   if( _matrule == NULL ) return false;
 325 
 326   return _matrule->is_ideal_box();
 327 }
 328 
 329 // Return 'true' if this instruction matches an ideal 'Goto' node
 330 bool InstructForm::is_ideal_goto() const {
 331   if( _matrule == NULL ) return false;
 332 
 333   return _matrule->is_ideal_goto();
 334 }
 335 
 336 // Return 'true' if this instruction matches an ideal 'Jump' node
 337 bool InstructForm::is_ideal_jump() const {
 338   if( _matrule == NULL ) return false;
 339 
 340   return _matrule->is_ideal_jump();
 341 }
 342 
 343 // Return 'true' if instruction matches ideal 'If' | 'Goto' |
 344 //                    'CountedLoopEnd' | 'Jump'
 345 bool InstructForm::is_ideal_branch() const {
 346   if( _matrule == NULL ) return false;
 347 
 348   return _matrule->is_ideal_if() || _matrule->is_ideal_goto() || _matrule->is_ideal_jump();
 349 }
 350 
 351 
 352 // Return 'true' if this instruction matches an ideal 'Return' node
 353 bool InstructForm::is_ideal_return() const {
 354   if( _matrule == NULL ) return false;
 355 
 356   // Check MatchRule to see if the first entry is the ideal "Return" node
 357   int  index   = 0;
 358   if (_matrule->find_type("Return",index)) return true;
 359   if (_matrule->find_type("Rethrow",index)) return true;
 360   if (_matrule->find_type("TailCall",index)) return true;
 361   if (_matrule->find_type("TailJump",index)) return true;
 362 
 363   return false;
 364 }
 365 
 366 // Return 'true' if this instruction matches an ideal 'Halt' node
 367 bool InstructForm::is_ideal_halt() const {
 368   int  index   = 0;
 369   return _matrule && _matrule->find_type("Halt",index);
 370 }
 371 
 372 // Return 'true' if this instruction matches an ideal 'SafePoint' node
 373 bool InstructForm::is_ideal_safepoint() const {
 374   int  index   = 0;
 375   return _matrule && _matrule->find_type("SafePoint",index);
 376 }
 377 
 378 // Return 'true' if this instruction matches an ideal 'Nop' node
 379 bool InstructForm::is_ideal_nop() const {
 380   return _ident && _ident[0] == 'N' && _ident[1] == 'o' && _ident[2] == 'p' && _ident[3] == '_';
 381 }
 382 
 383 bool InstructForm::is_ideal_control() const {
 384   if ( ! _matrule)  return false;
 385 
 386   return is_ideal_return() || is_ideal_branch() || is_ideal_halt();
 387 }
 388 
 389 // Return 'true' if this instruction matches an ideal 'Call' node
 390 Form::CallType InstructForm::is_ideal_call() const {
 391   if( _matrule == NULL ) return Form::invalid_type;
 392 
 393   // Check MatchRule to see if the first entry is the ideal "Call" node
 394   int  idx   = 0;
 395   if(_matrule->find_type("CallStaticJava",idx))   return Form::JAVA_STATIC;
 396   idx = 0;
 397   if(_matrule->find_type("Lock",idx))             return Form::JAVA_STATIC;
 398   idx = 0;
 399   if(_matrule->find_type("Unlock",idx))           return Form::JAVA_STATIC;
 400   idx = 0;
 401   if(_matrule->find_type("CallDynamicJava",idx))  return Form::JAVA_DYNAMIC;
 402   idx = 0;
 403   if(_matrule->find_type("CallRuntime",idx))      return Form::JAVA_RUNTIME;
 404   idx = 0;
 405   if(_matrule->find_type("CallLeaf",idx))         return Form::JAVA_LEAF;
 406   idx = 0;
 407   if(_matrule->find_type("CallLeafNoFP",idx))     return Form::JAVA_LEAF;
 408   idx = 0;
 409 
 410   return Form::invalid_type;
 411 }
 412 
 413 // Return 'true' if this instruction matches an ideal 'Load?' node
 414 Form::DataType InstructForm::is_ideal_load() const {
 415   if( _matrule == NULL ) return Form::none;
 416 
 417   return  _matrule->is_ideal_load();
 418 }
 419 
 420 // Return 'true' if this instruction matches an ideal 'LoadKlass' node
 421 bool InstructForm::skip_antidep_check() const {
 422   if( _matrule == NULL ) return false;
 423 
 424   return  _matrule->skip_antidep_check();
 425 }
 426 
 427 // Return 'true' if this instruction matches an ideal 'Load?' node
 428 Form::DataType InstructForm::is_ideal_store() const {
 429   if( _matrule == NULL ) return Form::none;
 430 
 431   return  _matrule->is_ideal_store();
 432 }
 433 
 434 // Return the input register that must match the output register
 435 // If this is not required, return 0
 436 uint InstructForm::two_address(FormDict &globals) {
 437   uint  matching_input = 0;
 438   if(_components.count() == 0) return 0;
 439 
 440   _components.reset();
 441   Component *comp = _components.iter();
 442   // Check if there is a DEF
 443   if( comp->isa(Component::DEF) ) {
 444     // Check that this is a register
 445     const char  *def_type = comp->_type;
 446     const Form  *form     = globals[def_type];
 447     OperandForm *op       = form->is_operand();
 448     if( op ) {
 449       if( op->constrained_reg_class() != NULL &&
 450           op->interface_type(globals) == Form::register_interface ) {
 451         // Remember the local name for equality test later
 452         const char *def_name = comp->_name;
 453         // Check if a component has the same name and is a USE
 454         do {
 455           if( comp->isa(Component::USE) && strcmp(comp->_name,def_name)==0 ) {
 456             return operand_position_format(def_name);
 457           }
 458         } while( (comp = _components.iter()) != NULL);
 459       }
 460     }
 461   }
 462 
 463   return 0;
 464 }
 465 
 466 
 467 // when chaining a constant to an instruction, returns 'true' and sets opType
 468 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals) {
 469   const char *dummy  = NULL;
 470   const char *dummy2 = NULL;
 471   return is_chain_of_constant(globals, dummy, dummy2);
 472 }
 473 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
 474                 const char * &opTypeParam) {
 475   const char *result = NULL;
 476 
 477   return is_chain_of_constant(globals, opTypeParam, result);
 478 }
 479 
 480 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
 481                 const char * &opTypeParam, const char * &resultParam) {
 482   Form::DataType  data_type = Form::none;
 483   if ( ! _matrule)  return data_type;
 484 
 485   // !!!!!
 486   // The source of the chain rule is 'position = 1'
 487   uint         position = 1;
 488   const char  *result   = NULL;
 489   const char  *name     = NULL;
 490   const char  *opType   = NULL;
 491   // Here base_operand is looking for an ideal type to be returned (opType).
 492   if ( _matrule->is_chain_rule(globals)
 493        && _matrule->base_operand(position, globals, result, name, opType) ) {
 494     data_type = ideal_to_const_type(opType);
 495 
 496     // if it isn't an ideal constant type, just return
 497     if ( data_type == Form::none ) return data_type;
 498 
 499     // Ideal constant types also adjust the opType parameter.
 500     resultParam = result;
 501     opTypeParam = opType;
 502     return data_type;
 503   }
 504 
 505   return data_type;
 506 }
 507 
 508 // Check if a simple chain rule
 509 bool InstructForm::is_simple_chain_rule(FormDict &globals) const {
 510   if( _matrule && _matrule->sets_result()
 511       && _matrule->_rChild->_lChild == NULL
 512       && globals[_matrule->_rChild->_opType]
 513       && globals[_matrule->_rChild->_opType]->is_opclass() ) {
 514     return true;
 515   }
 516   return false;
 517 }
 518 
 519 // check for structural rematerialization
 520 bool InstructForm::rematerialize(FormDict &globals, RegisterForm *registers ) {
 521   bool   rematerialize = false;
 522 
 523   Form::DataType data_type = is_chain_of_constant(globals);
 524   if( data_type != Form::none )
 525     rematerialize = true;
 526 
 527   // Constants
 528   if( _components.count() == 1 && _components[0]->is(Component::USE_DEF) )
 529     rematerialize = true;
 530 
 531   // Pseudo-constants (values easily available to the runtime)
 532   if (is_empty_encoding() && is_tls_instruction())
 533     rematerialize = true;
 534 
 535   // 1-input, 1-output, such as copies or increments.
 536   if( _components.count() == 2 &&
 537       _components[0]->is(Component::DEF) &&
 538       _components[1]->isa(Component::USE) )
 539     rematerialize = true;
 540 
 541   // Check for an ideal 'Load?' and eliminate rematerialize option
 542   if ( is_ideal_load() != Form::none || // Ideal load?  Do not rematerialize
 543        is_ideal_copy() != Form::none || // Ideal copy?  Do not rematerialize
 544        is_expensive()  != Form::none) { // Expensive?   Do not rematerialize
 545     rematerialize = false;
 546   }
 547 
 548   // Always rematerialize the flags.  They are more expensive to save &
 549   // restore than to recompute (and possibly spill the compare's inputs).
 550   if( _components.count() >= 1 ) {
 551     Component *c = _components[0];
 552     const Form *form = globals[c->_type];
 553     OperandForm *opform = form->is_operand();
 554     if( opform ) {
 555       // Avoid the special stack_slots register classes
 556       const char *rc_name = opform->constrained_reg_class();
 557       if( rc_name ) {
 558         if( strcmp(rc_name,"stack_slots") ) {
 559           // Check for ideal_type of RegFlags
 560           const char *type = opform->ideal_type( globals, registers );
 561           if( !strcmp(type,"RegFlags") )
 562             rematerialize = true;
 563         } else
 564           rematerialize = false; // Do not rematerialize things target stk
 565       }
 566     }
 567   }
 568 
 569   return rematerialize;
 570 }
 571 
 572 // loads from memory, so must check for anti-dependence
 573 bool InstructForm::needs_anti_dependence_check(FormDict &globals) const {
 574   if ( skip_antidep_check() ) return false;
 575 
 576   // Machine independent loads must be checked for anti-dependences
 577   if( is_ideal_load() != Form::none )  return true;
 578 
 579   // !!!!! !!!!! !!!!!
 580   // TEMPORARY
 581   // if( is_simple_chain_rule(globals) )  return false;
 582 
 583   // String.(compareTo/equals/indexOf) and Arrays.equals use many memorys edges,
 584   // but writes none
 585   if( _matrule && _matrule->_rChild &&
 586       ( strcmp(_matrule->_rChild->_opType,"StrComp"    )==0 ||
 587         strcmp(_matrule->_rChild->_opType,"StrEquals"  )==0 ||
 588         strcmp(_matrule->_rChild->_opType,"StrIndexOf" )==0 ||
 589         strcmp(_matrule->_rChild->_opType,"AryEq"      )==0 ))
 590     return true;
 591 
 592   // Check if instruction has a USE of a memory operand class, but no defs
 593   bool USE_of_memory  = false;
 594   bool DEF_of_memory  = false;
 595   Component     *comp = NULL;
 596   ComponentList &components = (ComponentList &)_components;
 597 
 598   components.reset();
 599   while( (comp = components.iter()) != NULL ) {
 600     const Form  *form = globals[comp->_type];
 601     if( !form ) continue;
 602     OpClassForm *op   = form->is_opclass();
 603     if( !op ) continue;
 604     if( form->interface_type(globals) == Form::memory_interface ) {
 605       if( comp->isa(Component::USE) ) USE_of_memory = true;
 606       if( comp->isa(Component::DEF) ) {
 607         OperandForm *oper = form->is_operand();
 608         if( oper && oper->is_user_name_for_sReg() ) {
 609           // Stack slots are unaliased memory handled by allocator
 610           oper = oper;  // debug stopping point !!!!!
 611         } else {
 612           DEF_of_memory = true;
 613         }
 614       }
 615     }
 616   }
 617   return (USE_of_memory && !DEF_of_memory);
 618 }
 619 
 620 
 621 bool InstructForm::is_wide_memory_kill(FormDict &globals) const {
 622   if( _matrule == NULL ) return false;
 623   if( !_matrule->_opType ) return false;
 624 
 625   if( strcmp(_matrule->_opType,"MemBarRelease") == 0 ) return true;
 626   if( strcmp(_matrule->_opType,"MemBarAcquire") == 0 ) return true;
 627 
 628   return false;
 629 }
 630 
 631 int InstructForm::memory_operand(FormDict &globals) const {
 632   // Machine independent loads must be checked for anti-dependences
 633   // Check if instruction has a USE of a memory operand class, or a def.
 634   int USE_of_memory  = 0;
 635   int DEF_of_memory  = 0;
 636   const char*    last_memory_DEF = NULL; // to test DEF/USE pairing in asserts
 637   Component     *unique          = NULL;
 638   Component     *comp            = NULL;
 639   ComponentList &components      = (ComponentList &)_components;
 640 
 641   components.reset();
 642   while( (comp = components.iter()) != NULL ) {
 643     const Form  *form = globals[comp->_type];
 644     if( !form ) continue;
 645     OpClassForm *op   = form->is_opclass();
 646     if( !op ) continue;
 647     if( op->stack_slots_only(globals) )  continue;
 648     if( form->interface_type(globals) == Form::memory_interface ) {
 649       if( comp->isa(Component::DEF) ) {
 650         last_memory_DEF = comp->_name;
 651         DEF_of_memory++;
 652         unique = comp;
 653       } else if( comp->isa(Component::USE) ) {
 654         if( last_memory_DEF != NULL ) {
 655           assert(0 == strcmp(last_memory_DEF, comp->_name), "every memory DEF is followed by a USE of the same name");
 656           last_memory_DEF = NULL;
 657         }
 658         USE_of_memory++;
 659         if (DEF_of_memory == 0)  // defs take precedence
 660           unique = comp;
 661       } else {
 662         assert(last_memory_DEF == NULL, "unpaired memory DEF");
 663       }
 664     }
 665   }
 666   assert(last_memory_DEF == NULL, "unpaired memory DEF");
 667   assert(USE_of_memory >= DEF_of_memory, "unpaired memory DEF");
 668   USE_of_memory -= DEF_of_memory;   // treat paired DEF/USE as one occurrence
 669   if( (USE_of_memory + DEF_of_memory) > 0 ) {
 670     if( is_simple_chain_rule(globals) ) {
 671       //fprintf(stderr, "Warning: chain rule is not really a memory user.\n");
 672       //((InstructForm*)this)->dump();
 673       // Preceding code prints nothing on sparc and these insns on intel:
 674       // leaP8 leaP32 leaPIdxOff leaPIdxScale leaPIdxScaleOff leaP8 leaP32
 675       // leaPIdxOff leaPIdxScale leaPIdxScaleOff
 676       return NO_MEMORY_OPERAND;
 677     }
 678 
 679     if( DEF_of_memory == 1 ) {
 680       assert(unique != NULL, "");
 681       if( USE_of_memory == 0 ) {
 682         // unique def, no uses
 683       } else {
 684         // // unique def, some uses
 685         // // must return bottom unless all uses match def
 686         // unique = NULL;
 687       }
 688     } else if( DEF_of_memory > 0 ) {
 689       // multiple defs, don't care about uses
 690       unique = NULL;
 691     } else if( USE_of_memory == 1) {
 692       // unique use, no defs
 693       assert(unique != NULL, "");
 694     } else if( USE_of_memory > 0 ) {
 695       // multiple uses, no defs
 696       unique = NULL;
 697     } else {
 698       assert(false, "bad case analysis");
 699     }
 700     // process the unique DEF or USE, if there is one
 701     if( unique == NULL ) {
 702       return MANY_MEMORY_OPERANDS;
 703     } else {
 704       int pos = components.operand_position(unique->_name);
 705       if( unique->isa(Component::DEF) ) {
 706         pos += 1;                // get corresponding USE from DEF
 707       }
 708       assert(pos >= 1, "I was just looking at it!");
 709       return pos;
 710     }
 711   }
 712 
 713   // missed the memory op??
 714   if( true ) {  // %%% should not be necessary
 715     if( is_ideal_store() != Form::none ) {
 716       fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
 717       ((InstructForm*)this)->dump();
 718       // pretend it has multiple defs and uses
 719       return MANY_MEMORY_OPERANDS;
 720     }
 721     if( is_ideal_load()  != Form::none ) {
 722       fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
 723       ((InstructForm*)this)->dump();
 724       // pretend it has multiple uses and no defs
 725       return MANY_MEMORY_OPERANDS;
 726     }
 727   }
 728 
 729   return NO_MEMORY_OPERAND;
 730 }
 731 
 732 
 733 // This instruction captures the machine-independent bottom_type
 734 // Expected use is for pointer vs oop determination for LoadP
 735 bool InstructForm::captures_bottom_type(FormDict &globals) const {
 736   if( _matrule && _matrule->_rChild &&
 737        (!strcmp(_matrule->_rChild->_opType,"CastPP")     ||  // new result type
 738         !strcmp(_matrule->_rChild->_opType,"CastX2P")    ||  // new result type
 739         !strcmp(_matrule->_rChild->_opType,"DecodeN")    ||
 740         !strcmp(_matrule->_rChild->_opType,"EncodeP")    ||
 741         !strcmp(_matrule->_rChild->_opType,"LoadN")      ||
 742         !strcmp(_matrule->_rChild->_opType,"LoadNKlass") ||
 743         !strcmp(_matrule->_rChild->_opType,"CreateEx")   ||  // type of exception
 744         !strcmp(_matrule->_rChild->_opType,"CheckCastPP")) ) return true;
 745   else if ( is_ideal_load() == Form::idealP )                return true;
 746   else if ( is_ideal_store() != Form::none  )                return true;
 747 
 748   if (needs_base_oop_edge(globals)) return true;
 749 
 750   return  false;
 751 }
 752 
 753 
 754 // Access instr_cost attribute or return NULL.
 755 const char* InstructForm::cost() {
 756   for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
 757     if( strcmp(cur->_ident,AttributeForm::_ins_cost) == 0 ) {
 758       return cur->_val;
 759     }
 760   }
 761   return NULL;
 762 }
 763 
 764 // Return count of top-level operands.
 765 uint InstructForm::num_opnds() {
 766   int  num_opnds = _components.num_operands();
 767 
 768   // Need special handling for matching some ideal nodes
 769   // i.e. Matching a return node
 770   /*
 771   if( _matrule ) {
 772     if( strcmp(_matrule->_opType,"Return"   )==0 ||
 773         strcmp(_matrule->_opType,"Halt"     )==0 )
 774       return 3;
 775   }
 776     */
 777   return num_opnds;
 778 }
 779 
 780 // Return count of unmatched operands.
 781 uint InstructForm::num_post_match_opnds() {
 782   uint  num_post_match_opnds = _components.count();
 783   uint  num_match_opnds = _components.match_count();
 784   num_post_match_opnds = num_post_match_opnds - num_match_opnds;
 785 
 786   return num_post_match_opnds;
 787 }
 788 
 789 // Return the number of leaves below this complex operand
 790 uint InstructForm::num_consts(FormDict &globals) const {
 791   if ( ! _matrule) return 0;
 792 
 793   // This is a recursive invocation on all operands in the matchrule
 794   return _matrule->num_consts(globals);
 795 }
 796 
 797 // Constants in match rule with specified type
 798 uint InstructForm::num_consts(FormDict &globals, Form::DataType type) const {
 799   if ( ! _matrule) return 0;
 800 
 801   // This is a recursive invocation on all operands in the matchrule
 802   return _matrule->num_consts(globals, type);
 803 }
 804 
 805 
 806 // Return the register class associated with 'leaf'.
 807 const char *InstructForm::out_reg_class(FormDict &globals) {
 808   assert( false, "InstructForm::out_reg_class(FormDict &globals); Not Implemented");
 809 
 810   return NULL;
 811 }
 812 
 813 
 814 
 815 // Lookup the starting position of inputs we are interested in wrt. ideal nodes
 816 uint InstructForm::oper_input_base(FormDict &globals) {
 817   if( !_matrule ) return 1;     // Skip control for most nodes
 818 
 819   // Need special handling for matching some ideal nodes
 820   // i.e. Matching a return node
 821   if( strcmp(_matrule->_opType,"Return"    )==0 ||
 822       strcmp(_matrule->_opType,"Rethrow"   )==0 ||
 823       strcmp(_matrule->_opType,"TailCall"  )==0 ||
 824       strcmp(_matrule->_opType,"TailJump"  )==0 ||
 825       strcmp(_matrule->_opType,"SafePoint" )==0 ||
 826       strcmp(_matrule->_opType,"Halt"      )==0 )
 827     return AdlcVMDeps::Parms;   // Skip the machine-state edges
 828 
 829   if( _matrule->_rChild &&
 830       ( strcmp(_matrule->_rChild->_opType,"AryEq"     )==0 ||
 831         strcmp(_matrule->_rChild->_opType,"StrComp"   )==0 ||
 832         strcmp(_matrule->_rChild->_opType,"StrEquals" )==0 ||
 833         strcmp(_matrule->_rChild->_opType,"StrIndexOf")==0 )) {
 834         // String.(compareTo/equals/indexOf) and Arrays.equals
 835         // take 1 control and 1 memory edges.
 836     return 2;
 837   }
 838 
 839   // Check for handling of 'Memory' input/edge in the ideal world.
 840   // The AD file writer is shielded from knowledge of these edges.
 841   int base = 1;                 // Skip control
 842   base += _matrule->needs_ideal_memory_edge(globals);
 843 
 844   // Also skip the base-oop value for uses of derived oops.
 845   // The AD file writer is shielded from knowledge of these edges.
 846   base += needs_base_oop_edge(globals);
 847 
 848   return base;
 849 }
 850 
 851 // Implementation does not modify state of internal structures
 852 void InstructForm::build_components() {
 853   // Add top-level operands to the components
 854   if (_matrule)  _matrule->append_components(_localNames, _components);
 855 
 856   // Add parameters that "do not appear in match rule".
 857   bool has_temp = false;
 858   const char *name;
 859   const char *kill_name = NULL;
 860   for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
 861     OperandForm *opForm = (OperandForm*)_localNames[name];
 862 
 863     Effect* e = NULL;
 864     {
 865       const Form* form = _effects[name];
 866       e = form ? form->is_effect() : NULL;
 867     }
 868 
 869     if (e != NULL) {
 870       has_temp |= e->is(Component::TEMP);
 871 
 872       // KILLs must be declared after any TEMPs because TEMPs are real
 873       // uses so their operand numbering must directly follow the real
 874       // inputs from the match rule.  Fixing the numbering seems
 875       // complex so simply enforce the restriction during parse.
 876       if (kill_name != NULL &&
 877           e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
 878         OperandForm* kill = (OperandForm*)_localNames[kill_name];
 879         globalAD->syntax_err(_linenum, "%s: %s %s must be at the end of the argument list\n",
 880                              _ident, kill->_ident, kill_name);
 881       } else if (e->isa(Component::KILL) && !e->isa(Component::USE)) {
 882         kill_name = name;
 883       }
 884     }
 885 
 886     const Component *component  = _components.search(name);
 887     if ( component  == NULL ) {
 888       if (e) {
 889         _components.insert(name, opForm->_ident, e->_use_def, false);
 890         component = _components.search(name);
 891         if (component->isa(Component::USE) && !component->isa(Component::TEMP) && _matrule) {
 892           const Form *form = globalAD->globalNames()[component->_type];
 893           assert( form, "component type must be a defined form");
 894           OperandForm *op   = form->is_operand();
 895           if (op->_interface && op->_interface->is_RegInterface()) {
 896             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
 897                                  _ident, opForm->_ident, name);
 898           }
 899         }
 900       } else {
 901         // This would be a nice warning but it triggers in a few places in a benign way
 902         // if (_matrule != NULL && !expands()) {
 903         //   globalAD->syntax_err(_linenum, "%s: %s %s not mentioned in effect or match rule\n",
 904         //                        _ident, opForm->_ident, name);
 905         // }
 906         _components.insert(name, opForm->_ident, Component::INVALID, false);
 907       }
 908     }
 909     else if (e) {
 910       // Component was found in the list
 911       // Check if there is a new effect that requires an extra component.
 912       // This happens when adding 'USE' to a component that is not yet one.
 913       if ((!component->isa( Component::USE) && ((e->_use_def & Component::USE) != 0))) {
 914         if (component->isa(Component::USE) && _matrule) {
 915           const Form *form = globalAD->globalNames()[component->_type];
 916           assert( form, "component type must be a defined form");
 917           OperandForm *op   = form->is_operand();
 918           if (op->_interface && op->_interface->is_RegInterface()) {
 919             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
 920                                  _ident, opForm->_ident, name);
 921           }
 922         }
 923         _components.insert(name, opForm->_ident, e->_use_def, false);
 924       } else {
 925         Component  *comp = (Component*)component;
 926         comp->promote_use_def_info(e->_use_def);
 927       }
 928       // Component positions are zero based.
 929       int  pos  = _components.operand_position(name);
 930       assert( ! (component->isa(Component::DEF) && (pos >= 1)),
 931               "Component::DEF can only occur in the first position");
 932     }
 933   }
 934 
 935   // Resolving the interactions between expand rules and TEMPs would
 936   // be complex so simply disallow it.
 937   if (_matrule == NULL && has_temp) {
 938     globalAD->syntax_err(_linenum, "%s: TEMPs without match rule isn't supported\n", _ident);
 939   }
 940 
 941   return;
 942 }
 943 
 944 // Return zero-based position in component list;  -1 if not in list.
 945 int   InstructForm::operand_position(const char *name, int usedef) {
 946   return unique_opnds_idx(_components.operand_position(name, usedef));
 947 }
 948 
 949 int   InstructForm::operand_position_format(const char *name) {
 950   return unique_opnds_idx(_components.operand_position_format(name));
 951 }
 952 
 953 // Return zero-based position in component list; -1 if not in list.
 954 int   InstructForm::label_position() {
 955   return unique_opnds_idx(_components.label_position());
 956 }
 957 
 958 int   InstructForm::method_position() {
 959   return unique_opnds_idx(_components.method_position());
 960 }
 961 
 962 // Return number of relocation entries needed for this instruction.
 963 uint  InstructForm::reloc(FormDict &globals) {
 964   uint reloc_entries  = 0;
 965   // Check for "Call" nodes
 966   if ( is_ideal_call() )      ++reloc_entries;
 967   if ( is_ideal_return() )    ++reloc_entries;
 968   if ( is_ideal_safepoint() ) ++reloc_entries;
 969 
 970 
 971   // Check if operands MAYBE oop pointers, by checking for ConP elements
 972   // Proceed through the leaves of the match-tree and check for ConPs
 973   if ( _matrule != NULL ) {
 974     uint         position = 0;
 975     const char  *result   = NULL;
 976     const char  *name     = NULL;
 977     const char  *opType   = NULL;
 978     while (_matrule->base_operand(position, globals, result, name, opType)) {
 979       if ( strcmp(opType,"ConP") == 0 ) {
 980 #ifdef SPARC
 981         reloc_entries += 2; // 1 for sethi + 1 for setlo
 982 #else
 983         ++reloc_entries;
 984 #endif
 985       }
 986       ++position;
 987     }
 988   }
 989 
 990   // Above is only a conservative estimate
 991   // because it did not check contents of operand classes.
 992   // !!!!! !!!!!
 993   // Add 1 to reloc info for each operand class in the component list.
 994   Component  *comp;
 995   _components.reset();
 996   while ( (comp = _components.iter()) != NULL ) {
 997     const Form        *form = globals[comp->_type];
 998     assert( form, "Did not find component's type in global names");
 999     const OpClassForm *opc  = form->is_opclass();
1000     const OperandForm *oper = form->is_operand();
1001     if ( opc && (oper == NULL) ) {
1002       ++reloc_entries;
1003     } else if ( oper ) {
1004       // floats and doubles loaded out of method's constant pool require reloc info
1005       Form::DataType type = oper->is_base_constant(globals);
1006       if ( (type == Form::idealF) || (type == Form::idealD) ) {
1007         ++reloc_entries;
1008       }
1009     }
1010   }
1011 
1012   // Float and Double constants may come from the CodeBuffer table
1013   // and require relocatable addresses for access
1014   // !!!!!
1015   // Check for any component being an immediate float or double.
1016   Form::DataType data_type = is_chain_of_constant(globals);
1017   if( data_type==idealD || data_type==idealF ) {
1018 #ifdef SPARC
1019     // sparc required more relocation entries for floating constants
1020     // (expires 9/98)
1021     reloc_entries += 6;
1022 #else
1023     reloc_entries++;
1024 #endif
1025   }
1026 
1027   return reloc_entries;
1028 }
1029 
1030 // Utility function defined in archDesc.cpp
1031 extern bool is_def(int usedef);
1032 
1033 // Return the result of reducing an instruction
1034 const char *InstructForm::reduce_result() {
1035   const char* result = "Universe";  // default
1036   _components.reset();
1037   Component *comp = _components.iter();
1038   if (comp != NULL && comp->isa(Component::DEF)) {
1039     result = comp->_type;
1040     // Override this if the rule is a store operation:
1041     if (_matrule && _matrule->_rChild &&
1042         is_store_to_memory(_matrule->_rChild->_opType))
1043       result = "Universe";
1044   }
1045   return result;
1046 }
1047 
1048 // Return the name of the operand on the right hand side of the binary match
1049 // Return NULL if there is no right hand side
1050 const char *InstructForm::reduce_right(FormDict &globals)  const {
1051   if( _matrule == NULL ) return NULL;
1052   return  _matrule->reduce_right(globals);
1053 }
1054 
1055 // Similar for left
1056 const char *InstructForm::reduce_left(FormDict &globals)   const {
1057   if( _matrule == NULL ) return NULL;
1058   return  _matrule->reduce_left(globals);
1059 }
1060 
1061 
1062 // Base class for this instruction, MachNode except for calls
1063 const char *InstructForm::mach_base_class(FormDict &globals)  const {
1064   if( is_ideal_call() == Form::JAVA_STATIC ) {
1065     return "MachCallStaticJavaNode";
1066   }
1067   else if( is_ideal_call() == Form::JAVA_DYNAMIC ) {
1068     return "MachCallDynamicJavaNode";
1069   }
1070   else if( is_ideal_call() == Form::JAVA_RUNTIME ) {
1071     return "MachCallRuntimeNode";
1072   }
1073   else if( is_ideal_call() == Form::JAVA_LEAF ) {
1074     return "MachCallLeafNode";
1075   }
1076   else if (is_ideal_return()) {
1077     return "MachReturnNode";
1078   }
1079   else if (is_ideal_halt()) {
1080     return "MachHaltNode";
1081   }
1082   else if (is_ideal_safepoint()) {
1083     return "MachSafePointNode";
1084   }
1085   else if (is_ideal_if()) {
1086     return "MachIfNode";
1087   }
1088   else if (is_ideal_goto()) {
1089     return "MachGotoNode";
1090   }
1091   else if (is_ideal_fastlock()) {
1092     return "MachFastLockNode";
1093   }
1094   else if (is_ideal_nop()) {
1095     return "MachNopNode";
1096   }
1097   else if (is_mach_constant()) {
1098     return "MachConstantNode";
1099   }
1100   else if (captures_bottom_type(globals)) {
1101     return "MachTypeNode";
1102   } else {
1103     return "MachNode";
1104   }
1105   assert( false, "ShouldNotReachHere()");
1106   return NULL;
1107 }
1108 
1109 // Compare the instruction predicates for textual equality
1110 bool equivalent_predicates( const InstructForm *instr1, const InstructForm *instr2 ) {
1111   const Predicate *pred1  = instr1->_predicate;
1112   const Predicate *pred2  = instr2->_predicate;
1113   if( pred1 == NULL && pred2 == NULL ) {
1114     // no predicates means they are identical
1115     return true;
1116   }
1117   if( pred1 != NULL && pred2 != NULL ) {
1118     // compare the predicates
1119     if (ADLParser::equivalent_expressions(pred1->_pred, pred2->_pred)) {
1120       return true;
1121     }
1122   }
1123 
1124   return false;
1125 }
1126 
1127 // Check if this instruction can cisc-spill to 'alternate'
1128 bool InstructForm::cisc_spills_to(ArchDesc &AD, InstructForm *instr) {
1129   assert( _matrule != NULL && instr->_matrule != NULL, "must have match rules");
1130   // Do not replace if a cisc-version has been found.
1131   if( cisc_spill_operand() != Not_cisc_spillable ) return false;
1132 
1133   int         cisc_spill_operand = Maybe_cisc_spillable;
1134   char       *result             = NULL;
1135   char       *result2            = NULL;
1136   const char *op_name            = NULL;
1137   const char *reg_type           = NULL;
1138   FormDict   &globals            = AD.globalNames();
1139   cisc_spill_operand = _matrule->matchrule_cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
1140   if( (cisc_spill_operand != Not_cisc_spillable) && (op_name != NULL) && equivalent_predicates(this, instr) ) {
1141     cisc_spill_operand = operand_position(op_name, Component::USE);
1142     int def_oper  = operand_position(op_name, Component::DEF);
1143     if( def_oper == NameList::Not_in_list && instr->num_opnds() == num_opnds()) {
1144       // Do not support cisc-spilling for destination operands and
1145       // make sure they have the same number of operands.
1146       _cisc_spill_alternate = instr;
1147       instr->set_cisc_alternate(true);
1148       if( AD._cisc_spill_debug ) {
1149         fprintf(stderr, "Instruction %s cisc-spills-to %s\n", _ident, instr->_ident);
1150         fprintf(stderr, "   using operand %s %s at index %d\n", reg_type, op_name, cisc_spill_operand);
1151       }
1152       // Record that a stack-version of the reg_mask is needed
1153       // !!!!!
1154       OperandForm *oper = (OperandForm*)(globals[reg_type]->is_operand());
1155       assert( oper != NULL, "cisc-spilling non operand");
1156       const char *reg_class_name = oper->constrained_reg_class();
1157       AD.set_stack_or_reg(reg_class_name);
1158       const char *reg_mask_name  = AD.reg_mask(*oper);
1159       set_cisc_reg_mask_name(reg_mask_name);
1160       const char *stack_or_reg_mask_name = AD.stack_or_reg_mask(*oper);
1161     } else {
1162       cisc_spill_operand = Not_cisc_spillable;
1163     }
1164   } else {
1165     cisc_spill_operand = Not_cisc_spillable;
1166   }
1167 
1168   set_cisc_spill_operand(cisc_spill_operand);
1169   return (cisc_spill_operand != Not_cisc_spillable);
1170 }
1171 
1172 // Check to see if this instruction can be replaced with the short branch
1173 // instruction `short-branch'
1174 bool InstructForm::check_branch_variant(ArchDesc &AD, InstructForm *short_branch) {
1175   if (_matrule != NULL &&
1176       this != short_branch &&   // Don't match myself
1177       !is_short_branch() &&     // Don't match another short branch variant
1178       reduce_result() != NULL &&
1179       strcmp(reduce_result(), short_branch->reduce_result()) == 0 &&
1180       _matrule->equivalent(AD.globalNames(), short_branch->_matrule)) {
1181     // The instructions are equivalent.
1182     if (AD._short_branch_debug) {
1183       fprintf(stderr, "Instruction %s has short form %s\n", _ident, short_branch->_ident);
1184     }
1185     _short_branch_form = short_branch;
1186     return true;
1187   }
1188   return false;
1189 }
1190 
1191 
1192 // --------------------------- FILE *output_routines
1193 //
1194 // Generate the format call for the replacement variable
1195 void InstructForm::rep_var_format(FILE *fp, const char *rep_var) {
1196   // Handle special constant table variables.
1197   if (strcmp(rep_var, "constanttablebase") == 0) {
1198     fprintf(fp, "char reg[128];  ra->dump_register(in(mach_constant_base_node_input()), reg);\n");
1199     fprintf(fp, "st->print(\"%%s\");\n");
1200     return;
1201   }
1202   if (strcmp(rep_var, "constantoffset") == 0) {
1203     fprintf(fp, "st->print(\"#%%d\", constant_offset());\n");
1204     return;
1205   }
1206   if (strcmp(rep_var, "constantaddress") == 0) {
1207     fprintf(fp, "st->print(\"constant table base + #%%d\", constant_offset());\n");
1208     return;
1209   }
1210 
1211   // Find replacement variable's type
1212   const Form *form   = _localNames[rep_var];
1213   if (form == NULL) {
1214     fprintf(stderr, "unknown replacement variable in format statement: '%s'\n", rep_var);
1215     assert(false, "ShouldNotReachHere()");
1216   }
1217   OpClassForm *opc   = form->is_opclass();
1218   assert( opc, "replacement variable was not found in local names");
1219   // Lookup the index position of the replacement variable
1220   int idx  = operand_position_format(rep_var);
1221   if ( idx == -1 ) {
1222     assert( strcmp(opc->_ident,"label")==0, "Unimplemented");
1223     assert( false, "ShouldNotReachHere()");
1224   }
1225 
1226   if (is_noninput_operand(idx)) {
1227     // This component isn't in the input array.  Print out the static
1228     // name of the register.
1229     OperandForm* oper = form->is_operand();
1230     if (oper != NULL && oper->is_bound_register()) {
1231       const RegDef* first = oper->get_RegClass()->find_first_elem();
1232       fprintf(fp, "    tty->print(\"%s\");\n", first->_regname);
1233     } else {
1234       globalAD->syntax_err(_linenum, "In %s can't find format for %s %s", _ident, opc->_ident, rep_var);
1235     }
1236   } else {
1237     // Output the format call for this operand
1238     fprintf(fp,"opnd_array(%d)->",idx);
1239     if (idx == 0)
1240       fprintf(fp,"int_format(ra, this, st); // %s\n", rep_var);
1241     else
1242       fprintf(fp,"ext_format(ra, this,idx%d, st); // %s\n", idx, rep_var );
1243   }
1244 }
1245 
1246 // Seach through operands to determine parameters unique positions.
1247 void InstructForm::set_unique_opnds() {
1248   uint* uniq_idx = NULL;
1249   int  nopnds = num_opnds();
1250   uint  num_uniq = nopnds;
1251   int i;
1252   _uniq_idx_length = 0;
1253   if ( nopnds > 0 ) {
1254     // Allocate index array.  Worst case we're mapping from each
1255     // component back to an index and any DEF always goes at 0 so the
1256     // length of the array has to be the number of components + 1.
1257     _uniq_idx_length = _components.count() + 1;
1258     uniq_idx = (uint*) malloc(sizeof(uint)*(_uniq_idx_length));
1259     for( i = 0; i < _uniq_idx_length; i++ ) {
1260       uniq_idx[i] = i;
1261     }
1262   }
1263   // Do it only if there is a match rule and no expand rule.  With an
1264   // expand rule it is done by creating new mach node in Expand()
1265   // method.
1266   if ( nopnds > 0 && _matrule != NULL && _exprule == NULL ) {
1267     const char *name;
1268     uint count;
1269     bool has_dupl_use = false;
1270 
1271     _parameters.reset();
1272     while( (name = _parameters.iter()) != NULL ) {
1273       count = 0;
1274       int position = 0;
1275       int uniq_position = 0;
1276       _components.reset();
1277       Component *comp = NULL;
1278       if( sets_result() ) {
1279         comp = _components.iter();
1280         position++;
1281       }
1282       // The next code is copied from the method operand_position().
1283       for (; (comp = _components.iter()) != NULL; ++position) {
1284         // When the first component is not a DEF,
1285         // leave space for the result operand!
1286         if ( position==0 && (! comp->isa(Component::DEF)) ) {
1287           ++position;
1288         }
1289         if( strcmp(name, comp->_name)==0 ) {
1290           if( ++count > 1 ) {
1291             assert(position < _uniq_idx_length, "out of bounds");
1292             uniq_idx[position] = uniq_position;
1293             has_dupl_use = true;
1294           } else {
1295             uniq_position = position;
1296           }
1297         }
1298         if( comp->isa(Component::DEF)
1299             && comp->isa(Component::USE) ) {
1300           ++position;
1301           if( position != 1 )
1302             --position;   // only use two slots for the 1st USE_DEF
1303         }
1304       }
1305     }
1306     if( has_dupl_use ) {
1307       for( i = 1; i < nopnds; i++ )
1308         if( i != uniq_idx[i] )
1309           break;
1310       int  j = i;
1311       for( ; i < nopnds; i++ )
1312         if( i == uniq_idx[i] )
1313           uniq_idx[i] = j++;
1314       num_uniq = j;
1315     }
1316   }
1317   _uniq_idx = uniq_idx;
1318   _num_uniq = num_uniq;
1319 }
1320 
1321 // Generate index values needed for determining the operand position
1322 void InstructForm::index_temps(FILE *fp, FormDict &globals, const char *prefix, const char *receiver) {
1323   uint  idx = 0;                  // position of operand in match rule
1324   int   cur_num_opnds = num_opnds();
1325 
1326   // Compute the index into vector of operand pointers:
1327   // idx0=0 is used to indicate that info comes from this same node, not from input edge.
1328   // idx1 starts at oper_input_base()
1329   if ( cur_num_opnds >= 1 ) {
1330     fprintf(fp,"    // Start at oper_input_base() and count operands\n");
1331     fprintf(fp,"    unsigned %sidx0 = %d;\n", prefix, oper_input_base(globals));
1332     fprintf(fp,"    unsigned %sidx1 = %d;\n", prefix, oper_input_base(globals));
1333 
1334     // Generate starting points for other unique operands if they exist
1335     for ( idx = 2; idx < num_unique_opnds(); ++idx ) {
1336       if( *receiver == 0 ) {
1337         fprintf(fp,"    unsigned %sidx%d = %sidx%d + opnd_array(%d)->num_edges();\n",
1338                 prefix, idx, prefix, idx-1, idx-1 );
1339       } else {
1340         fprintf(fp,"    unsigned %sidx%d = %sidx%d + %s_opnds[%d]->num_edges();\n",
1341                 prefix, idx, prefix, idx-1, receiver, idx-1 );
1342       }
1343     }
1344   }
1345   if( *receiver != 0 ) {
1346     // This value is used by generate_peepreplace when copying a node.
1347     // Don't emit it in other cases since it can hide bugs with the
1348     // use invalid idx's.
1349     fprintf(fp,"    unsigned %sidx%d = %sreq(); \n", prefix, idx, receiver);
1350   }
1351 
1352 }
1353 
1354 // ---------------------------
1355 bool InstructForm::verify() {
1356   // !!!!! !!!!!
1357   // Check that a "label" operand occurs last in the operand list, if present
1358   return true;
1359 }
1360 
1361 void InstructForm::dump() {
1362   output(stderr);
1363 }
1364 
1365 void InstructForm::output(FILE *fp) {
1366   fprintf(fp,"\nInstruction: %s\n", (_ident?_ident:""));
1367   if (_matrule)   _matrule->output(fp);
1368   if (_insencode) _insencode->output(fp);
1369   if (_constant)  _constant->output(fp);
1370   if (_opcode)    _opcode->output(fp);
1371   if (_attribs)   _attribs->output(fp);
1372   if (_predicate) _predicate->output(fp);
1373   if (_effects.Size()) {
1374     fprintf(fp,"Effects\n");
1375     _effects.dump();
1376   }
1377   if (_exprule)   _exprule->output(fp);
1378   if (_rewrule)   _rewrule->output(fp);
1379   if (_format)    _format->output(fp);
1380   if (_peephole)  _peephole->output(fp);
1381 }
1382 
1383 void MachNodeForm::dump() {
1384   output(stderr);
1385 }
1386 
1387 void MachNodeForm::output(FILE *fp) {
1388   fprintf(fp,"\nMachNode: %s\n", (_ident?_ident:""));
1389 }
1390 
1391 //------------------------------build_predicate--------------------------------
1392 // Build instruction predicates.  If the user uses the same operand name
1393 // twice, we need to check that the operands are pointer-eequivalent in
1394 // the DFA during the labeling process.
1395 Predicate *InstructForm::build_predicate() {
1396   char buf[1024], *s=buf;
1397   Dict names(cmpstr,hashstr,Form::arena);       // Map Names to counts
1398 
1399   MatchNode *mnode =
1400     strcmp(_matrule->_opType, "Set") ? _matrule : _matrule->_rChild;
1401   mnode->count_instr_names(names);
1402 
1403   uint first = 1;
1404   // Start with the predicate supplied in the .ad file.
1405   if( _predicate ) {
1406     if( first ) first=0;
1407     strcpy(s,"("); s += strlen(s);
1408     strcpy(s,_predicate->_pred);
1409     s += strlen(s);
1410     strcpy(s,")"); s += strlen(s);
1411   }
1412   for( DictI i(&names); i.test(); ++i ) {
1413     uintptr_t cnt = (uintptr_t)i._value;
1414     if( cnt > 1 ) {             // Need a predicate at all?
1415       assert( cnt == 2, "Unimplemented" );
1416       // Handle many pairs
1417       if( first ) first=0;
1418       else {                    // All tests must pass, so use '&&'
1419         strcpy(s," && ");
1420         s += strlen(s);
1421       }
1422       // Add predicate to working buffer
1423       sprintf(s,"/*%s*/(",(char*)i._key);
1424       s += strlen(s);
1425       mnode->build_instr_pred(s,(char*)i._key,0);
1426       s += strlen(s);
1427       strcpy(s," == "); s += strlen(s);
1428       mnode->build_instr_pred(s,(char*)i._key,1);
1429       s += strlen(s);
1430       strcpy(s,")"); s += strlen(s);
1431     }
1432   }
1433   if( s == buf ) s = NULL;
1434   else {
1435     assert( strlen(buf) < sizeof(buf), "String buffer overflow" );
1436     s = strdup(buf);
1437   }
1438   return new Predicate(s);
1439 }
1440 
1441 //------------------------------EncodeForm-------------------------------------
1442 // Constructor
1443 EncodeForm::EncodeForm()
1444   : _encClass(cmpstr,hashstr, Form::arena) {
1445 }
1446 EncodeForm::~EncodeForm() {
1447 }
1448 
1449 // record a new register class
1450 EncClass *EncodeForm::add_EncClass(const char *className) {
1451   EncClass *encClass = new EncClass(className);
1452   _eclasses.addName(className);
1453   _encClass.Insert(className,encClass);
1454   return encClass;
1455 }
1456 
1457 // Lookup the function body for an encoding class
1458 EncClass  *EncodeForm::encClass(const char *className) {
1459   assert( className != NULL, "Must provide a defined encoding name");
1460 
1461   EncClass *encClass = (EncClass*)_encClass[className];
1462   return encClass;
1463 }
1464 
1465 // Lookup the function body for an encoding class
1466 const char *EncodeForm::encClassBody(const char *className) {
1467   if( className == NULL ) return NULL;
1468 
1469   EncClass *encClass = (EncClass*)_encClass[className];
1470   assert( encClass != NULL, "Encode Class is missing.");
1471   encClass->_code.reset();
1472   const char *code = (const char*)encClass->_code.iter();
1473   assert( code != NULL, "Found an empty encode class body.");
1474 
1475   return code;
1476 }
1477 
1478 // Lookup the function body for an encoding class
1479 const char *EncodeForm::encClassPrototype(const char *className) {
1480   assert( className != NULL, "Encode class name must be non NULL.");
1481 
1482   return className;
1483 }
1484 
1485 void EncodeForm::dump() {                  // Debug printer
1486   output(stderr);
1487 }
1488 
1489 void EncodeForm::output(FILE *fp) {          // Write info to output files
1490   const char *name;
1491   fprintf(fp,"\n");
1492   fprintf(fp,"-------------------- Dump EncodeForm --------------------\n");
1493   for (_eclasses.reset(); (name = _eclasses.iter()) != NULL;) {
1494     ((EncClass*)_encClass[name])->output(fp);
1495   }
1496   fprintf(fp,"-------------------- end  EncodeForm --------------------\n");
1497 }
1498 //------------------------------EncClass---------------------------------------
1499 EncClass::EncClass(const char *name)
1500   : _localNames(cmpstr,hashstr, Form::arena), _name(name) {
1501 }
1502 EncClass::~EncClass() {
1503 }
1504 
1505 // Add a parameter <type,name> pair
1506 void EncClass::add_parameter(const char *parameter_type, const char *parameter_name) {
1507   _parameter_type.addName( parameter_type );
1508   _parameter_name.addName( parameter_name );
1509 }
1510 
1511 // Verify operand types in parameter list
1512 bool EncClass::check_parameter_types(FormDict &globals) {
1513   // !!!!!
1514   return false;
1515 }
1516 
1517 // Add the decomposed "code" sections of an encoding's code-block
1518 void EncClass::add_code(const char *code) {
1519   _code.addName(code);
1520 }
1521 
1522 // Add the decomposed "replacement variables" of an encoding's code-block
1523 void EncClass::add_rep_var(char *replacement_var) {
1524   _code.addName(NameList::_signal);
1525   _rep_vars.addName(replacement_var);
1526 }
1527 
1528 // Lookup the function body for an encoding class
1529 int EncClass::rep_var_index(const char *rep_var) {
1530   uint        position = 0;
1531   const char *name     = NULL;
1532 
1533   _parameter_name.reset();
1534   while ( (name = _parameter_name.iter()) != NULL ) {
1535     if ( strcmp(rep_var,name) == 0 ) return position;
1536     ++position;
1537   }
1538 
1539   return -1;
1540 }
1541 
1542 // Check after parsing
1543 bool EncClass::verify() {
1544   // 1!!!!
1545   // Check that each replacement variable, '$name' in architecture description
1546   // is actually a local variable for this encode class, or a reserved name
1547   // "primary, secondary, tertiary"
1548   return true;
1549 }
1550 
1551 void EncClass::dump() {
1552   output(stderr);
1553 }
1554 
1555 // Write info to output files
1556 void EncClass::output(FILE *fp) {
1557   fprintf(fp,"EncClass: %s", (_name ? _name : ""));
1558 
1559   // Output the parameter list
1560   _parameter_type.reset();
1561   _parameter_name.reset();
1562   const char *type = _parameter_type.iter();
1563   const char *name = _parameter_name.iter();
1564   fprintf(fp, " ( ");
1565   for ( ; (type != NULL) && (name != NULL);
1566         (type = _parameter_type.iter()), (name = _parameter_name.iter()) ) {
1567     fprintf(fp, " %s %s,", type, name);
1568   }
1569   fprintf(fp, " ) ");
1570 
1571   // Output the code block
1572   _code.reset();
1573   _rep_vars.reset();
1574   const char *code;
1575   while ( (code = _code.iter()) != NULL ) {
1576     if ( _code.is_signal(code) ) {
1577       // A replacement variable
1578       const char *rep_var = _rep_vars.iter();
1579       fprintf(fp,"($%s)", rep_var);
1580     } else {
1581       // A section of code
1582       fprintf(fp,"%s", code);
1583     }
1584   }
1585 
1586 }
1587 
1588 //------------------------------Opcode-----------------------------------------
1589 Opcode::Opcode(char *primary, char *secondary, char *tertiary)
1590   : _primary(primary), _secondary(secondary), _tertiary(tertiary) {
1591 }
1592 
1593 Opcode::~Opcode() {
1594 }
1595 
1596 Opcode::opcode_type Opcode::as_opcode_type(const char *param) {
1597   if( strcmp(param,"primary") == 0 ) {
1598     return Opcode::PRIMARY;
1599   }
1600   else if( strcmp(param,"secondary") == 0 ) {
1601     return Opcode::SECONDARY;
1602   }
1603   else if( strcmp(param,"tertiary") == 0 ) {
1604     return Opcode::TERTIARY;
1605   }
1606   return Opcode::NOT_AN_OPCODE;
1607 }
1608 
1609 bool Opcode::print_opcode(FILE *fp, Opcode::opcode_type desired_opcode) {
1610   // Default values previously provided by MachNode::primary()...
1611   const char *description = NULL;
1612   const char *value       = NULL;
1613   // Check if user provided any opcode definitions
1614   if( this != NULL ) {
1615     // Update 'value' if user provided a definition in the instruction
1616     switch (desired_opcode) {
1617     case PRIMARY:
1618       description = "primary()";
1619       if( _primary   != NULL)  { value = _primary;     }
1620       break;
1621     case SECONDARY:
1622       description = "secondary()";
1623       if( _secondary != NULL ) { value = _secondary;   }
1624       break;
1625     case TERTIARY:
1626       description = "tertiary()";
1627       if( _tertiary  != NULL ) { value = _tertiary;    }
1628       break;
1629     default:
1630       assert( false, "ShouldNotReachHere();");
1631       break;
1632     }
1633   }
1634   if (value != NULL) {
1635     fprintf(fp, "(%s /*%s*/)", value, description);
1636   }
1637   return value != NULL;
1638 }
1639 
1640 void Opcode::dump() {
1641   output(stderr);
1642 }
1643 
1644 // Write info to output files
1645 void Opcode::output(FILE *fp) {
1646   if (_primary   != NULL) fprintf(fp,"Primary   opcode: %s\n", _primary);
1647   if (_secondary != NULL) fprintf(fp,"Secondary opcode: %s\n", _secondary);
1648   if (_tertiary  != NULL) fprintf(fp,"Tertiary  opcode: %s\n", _tertiary);
1649 }
1650 
1651 //------------------------------InsEncode--------------------------------------
1652 InsEncode::InsEncode() {
1653 }
1654 InsEncode::~InsEncode() {
1655 }
1656 
1657 // Add "encode class name" and its parameters
1658 NameAndList *InsEncode::add_encode(char *encoding) {
1659   assert( encoding != NULL, "Must provide name for encoding");
1660 
1661   // add_parameter(NameList::_signal);
1662   NameAndList *encode = new NameAndList(encoding);
1663   _encoding.addName((char*)encode);
1664 
1665   return encode;
1666 }
1667 
1668 // Access the list of encodings
1669 void InsEncode::reset() {
1670   _encoding.reset();
1671   // _parameter.reset();
1672 }
1673 const char* InsEncode::encode_class_iter() {
1674   NameAndList  *encode_class = (NameAndList*)_encoding.iter();
1675   return  ( encode_class != NULL ? encode_class->name() : NULL );
1676 }
1677 // Obtain parameter name from zero based index
1678 const char *InsEncode::rep_var_name(InstructForm &inst, uint param_no) {
1679   NameAndList *params = (NameAndList*)_encoding.current();
1680   assert( params != NULL, "Internal Error");
1681   const char *param = (*params)[param_no];
1682 
1683   // Remove '$' if parser placed it there.
1684   return ( param != NULL && *param == '$') ? (param+1) : param;
1685 }
1686 
1687 void InsEncode::dump() {
1688   output(stderr);
1689 }
1690 
1691 // Write info to output files
1692 void InsEncode::output(FILE *fp) {
1693   NameAndList *encoding  = NULL;
1694   const char  *parameter = NULL;
1695 
1696   fprintf(fp,"InsEncode: ");
1697   _encoding.reset();
1698 
1699   while ( (encoding = (NameAndList*)_encoding.iter()) != 0 ) {
1700     // Output the encoding being used
1701     fprintf(fp,"%s(", encoding->name() );
1702 
1703     // Output its parameter list, if any
1704     bool first_param = true;
1705     encoding->reset();
1706     while (  (parameter = encoding->iter()) != 0 ) {
1707       // Output the ',' between parameters
1708       if ( ! first_param )  fprintf(fp,", ");
1709       first_param = false;
1710       // Output the parameter
1711       fprintf(fp,"%s", parameter);
1712     } // done with parameters
1713     fprintf(fp,")  ");
1714   } // done with encodings
1715 
1716   fprintf(fp,"\n");
1717 }
1718 
1719 //------------------------------Effect-----------------------------------------
1720 static int effect_lookup(const char *name) {
1721   if(!strcmp(name, "USE")) return Component::USE;
1722   if(!strcmp(name, "DEF")) return Component::DEF;
1723   if(!strcmp(name, "USE_DEF")) return Component::USE_DEF;
1724   if(!strcmp(name, "KILL")) return Component::KILL;
1725   if(!strcmp(name, "USE_KILL")) return Component::USE_KILL;
1726   if(!strcmp(name, "TEMP")) return Component::TEMP;
1727   if(!strcmp(name, "INVALID")) return Component::INVALID;
1728   assert( false,"Invalid effect name specified\n");
1729   return Component::INVALID;
1730 }
1731 
1732 Effect::Effect(const char *name) : _name(name), _use_def(effect_lookup(name)) {
1733   _ftype = Form::EFF;
1734 }
1735 Effect::~Effect() {
1736 }
1737 
1738 // Dynamic type check
1739 Effect *Effect::is_effect() const {
1740   return (Effect*)this;
1741 }
1742 
1743 
1744 // True if this component is equal to the parameter.
1745 bool Effect::is(int use_def_kill_enum) const {
1746   return (_use_def == use_def_kill_enum ? true : false);
1747 }
1748 // True if this component is used/def'd/kill'd as the parameter suggests.
1749 bool Effect::isa(int use_def_kill_enum) const {
1750   return (_use_def & use_def_kill_enum) == use_def_kill_enum;
1751 }
1752 
1753 void Effect::dump() {
1754   output(stderr);
1755 }
1756 
1757 void Effect::output(FILE *fp) {          // Write info to output files
1758   fprintf(fp,"Effect: %s\n", (_name?_name:""));
1759 }
1760 
1761 //------------------------------ExpandRule-------------------------------------
1762 ExpandRule::ExpandRule() : _expand_instrs(),
1763                            _newopconst(cmpstr, hashstr, Form::arena) {
1764   _ftype = Form::EXP;
1765 }
1766 
1767 ExpandRule::~ExpandRule() {                  // Destructor
1768 }
1769 
1770 void ExpandRule::add_instruction(NameAndList *instruction_name_and_operand_list) {
1771   _expand_instrs.addName((char*)instruction_name_and_operand_list);
1772 }
1773 
1774 void ExpandRule::reset_instructions() {
1775   _expand_instrs.reset();
1776 }
1777 
1778 NameAndList* ExpandRule::iter_instructions() {
1779   return (NameAndList*)_expand_instrs.iter();
1780 }
1781 
1782 
1783 void ExpandRule::dump() {
1784   output(stderr);
1785 }
1786 
1787 void ExpandRule::output(FILE *fp) {         // Write info to output files
1788   NameAndList *expand_instr = NULL;
1789   const char *opid = NULL;
1790 
1791   fprintf(fp,"\nExpand Rule:\n");
1792 
1793   // Iterate over the instructions 'node' expands into
1794   for(reset_instructions(); (expand_instr = iter_instructions()) != NULL; ) {
1795     fprintf(fp,"%s(", expand_instr->name());
1796 
1797     // iterate over the operand list
1798     for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1799       fprintf(fp,"%s ", opid);
1800     }
1801     fprintf(fp,");\n");
1802   }
1803 }
1804 
1805 //------------------------------RewriteRule------------------------------------
1806 RewriteRule::RewriteRule(char* params, char* block)
1807   : _tempParams(params), _tempBlock(block) { };  // Constructor
1808 RewriteRule::~RewriteRule() {                 // Destructor
1809 }
1810 
1811 void RewriteRule::dump() {
1812   output(stderr);
1813 }
1814 
1815 void RewriteRule::output(FILE *fp) {         // Write info to output files
1816   fprintf(fp,"\nRewrite Rule:\n%s\n%s\n",
1817           (_tempParams?_tempParams:""),
1818           (_tempBlock?_tempBlock:""));
1819 }
1820 
1821 
1822 //==============================MachNodes======================================
1823 //------------------------------MachNodeForm-----------------------------------
1824 MachNodeForm::MachNodeForm(char *id)
1825   : _ident(id) {
1826 }
1827 
1828 MachNodeForm::~MachNodeForm() {
1829 }
1830 
1831 MachNodeForm *MachNodeForm::is_machnode() const {
1832   return (MachNodeForm*)this;
1833 }
1834 
1835 //==============================Operand Classes================================
1836 //------------------------------OpClassForm------------------------------------
1837 OpClassForm::OpClassForm(const char* id) : _ident(id) {
1838   _ftype = Form::OPCLASS;
1839 }
1840 
1841 OpClassForm::~OpClassForm() {
1842 }
1843 
1844 bool OpClassForm::ideal_only() const { return 0; }
1845 
1846 OpClassForm *OpClassForm::is_opclass() const {
1847   return (OpClassForm*)this;
1848 }
1849 
1850 Form::InterfaceType OpClassForm::interface_type(FormDict &globals) const {
1851   if( _oplst.count() == 0 ) return Form::no_interface;
1852 
1853   // Check that my operands have the same interface type
1854   Form::InterfaceType  interface;
1855   bool  first = true;
1856   NameList &op_list = (NameList &)_oplst;
1857   op_list.reset();
1858   const char *op_name;
1859   while( (op_name = op_list.iter()) != NULL ) {
1860     const Form  *form    = globals[op_name];
1861     OperandForm *operand = form->is_operand();
1862     assert( operand, "Entry in operand class that is not an operand");
1863     if( first ) {
1864       first     = false;
1865       interface = operand->interface_type(globals);
1866     } else {
1867       interface = (interface == operand->interface_type(globals) ? interface : Form::no_interface);
1868     }
1869   }
1870   return interface;
1871 }
1872 
1873 bool OpClassForm::stack_slots_only(FormDict &globals) const {
1874   if( _oplst.count() == 0 ) return false;  // how?
1875 
1876   NameList &op_list = (NameList &)_oplst;
1877   op_list.reset();
1878   const char *op_name;
1879   while( (op_name = op_list.iter()) != NULL ) {
1880     const Form  *form    = globals[op_name];
1881     OperandForm *operand = form->is_operand();
1882     assert( operand, "Entry in operand class that is not an operand");
1883     if( !operand->stack_slots_only(globals) )  return false;
1884   }
1885   return true;
1886 }
1887 
1888 
1889 void OpClassForm::dump() {
1890   output(stderr);
1891 }
1892 
1893 void OpClassForm::output(FILE *fp) {
1894   const char *name;
1895   fprintf(fp,"\nOperand Class: %s\n", (_ident?_ident:""));
1896   fprintf(fp,"\nCount = %d\n", _oplst.count());
1897   for(_oplst.reset(); (name = _oplst.iter()) != NULL;) {
1898     fprintf(fp,"%s, ",name);
1899   }
1900   fprintf(fp,"\n");
1901 }
1902 
1903 
1904 //==============================Operands=======================================
1905 //------------------------------OperandForm------------------------------------
1906 OperandForm::OperandForm(const char* id)
1907   : OpClassForm(id), _ideal_only(false),
1908     _localNames(cmpstr, hashstr, Form::arena) {
1909       _ftype = Form::OPER;
1910 
1911       _matrule   = NULL;
1912       _interface = NULL;
1913       _attribs   = NULL;
1914       _predicate = NULL;
1915       _constraint= NULL;
1916       _construct = NULL;
1917       _format    = NULL;
1918 }
1919 OperandForm::OperandForm(const char* id, bool ideal_only)
1920   : OpClassForm(id), _ideal_only(ideal_only),
1921     _localNames(cmpstr, hashstr, Form::arena) {
1922       _ftype = Form::OPER;
1923 
1924       _matrule   = NULL;
1925       _interface = NULL;
1926       _attribs   = NULL;
1927       _predicate = NULL;
1928       _constraint= NULL;
1929       _construct = NULL;
1930       _format    = NULL;
1931 }
1932 OperandForm::~OperandForm() {
1933 }
1934 
1935 
1936 OperandForm *OperandForm::is_operand() const {
1937   return (OperandForm*)this;
1938 }
1939 
1940 bool OperandForm::ideal_only() const {
1941   return _ideal_only;
1942 }
1943 
1944 Form::InterfaceType OperandForm::interface_type(FormDict &globals) const {
1945   if( _interface == NULL )  return Form::no_interface;
1946 
1947   return _interface->interface_type(globals);
1948 }
1949 
1950 
1951 bool OperandForm::stack_slots_only(FormDict &globals) const {
1952   if( _constraint == NULL )  return false;
1953   return _constraint->stack_slots_only();
1954 }
1955 
1956 
1957 // Access op_cost attribute or return NULL.
1958 const char* OperandForm::cost() {
1959   for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
1960     if( strcmp(cur->_ident,AttributeForm::_op_cost) == 0 ) {
1961       return cur->_val;
1962     }
1963   }
1964   return NULL;
1965 }
1966 
1967 // Return the number of leaves below this complex operand
1968 uint OperandForm::num_leaves() const {
1969   if ( ! _matrule) return 0;
1970 
1971   int num_leaves = _matrule->_numleaves;
1972   return num_leaves;
1973 }
1974 
1975 // Return the number of constants contained within this complex operand
1976 uint OperandForm::num_consts(FormDict &globals) const {
1977   if ( ! _matrule) return 0;
1978 
1979   // This is a recursive invocation on all operands in the matchrule
1980   return _matrule->num_consts(globals);
1981 }
1982 
1983 // Return the number of constants in match rule with specified type
1984 uint OperandForm::num_consts(FormDict &globals, Form::DataType type) const {
1985   if ( ! _matrule) return 0;
1986 
1987   // This is a recursive invocation on all operands in the matchrule
1988   return _matrule->num_consts(globals, type);
1989 }
1990 
1991 // Return the number of pointer constants contained within this complex operand
1992 uint OperandForm::num_const_ptrs(FormDict &globals) const {
1993   if ( ! _matrule) return 0;
1994 
1995   // This is a recursive invocation on all operands in the matchrule
1996   return _matrule->num_const_ptrs(globals);
1997 }
1998 
1999 uint OperandForm::num_edges(FormDict &globals) const {
2000   uint edges  = 0;
2001   uint leaves = num_leaves();
2002   uint consts = num_consts(globals);
2003 
2004   // If we are matching a constant directly, there are no leaves.
2005   edges = ( leaves > consts ) ? leaves - consts : 0;
2006 
2007   // !!!!!
2008   // Special case operands that do not have a corresponding ideal node.
2009   if( (edges == 0) && (consts == 0) ) {
2010     if( constrained_reg_class() != NULL ) {
2011       edges = 1;
2012     } else {
2013       if( _matrule
2014           && (_matrule->_lChild == NULL) && (_matrule->_rChild == NULL) ) {
2015         const Form *form = globals[_matrule->_opType];
2016         OperandForm *oper = form ? form->is_operand() : NULL;
2017         if( oper ) {
2018           return oper->num_edges(globals);
2019         }
2020       }
2021     }
2022   }
2023 
2024   return edges;
2025 }
2026 
2027 
2028 // Check if this operand is usable for cisc-spilling
2029 bool  OperandForm::is_cisc_reg(FormDict &globals) const {
2030   const char *ideal = ideal_type(globals);
2031   bool is_cisc_reg = (ideal && (ideal_to_Reg_type(ideal) != none));
2032   return is_cisc_reg;
2033 }
2034 
2035 bool  OpClassForm::is_cisc_mem(FormDict &globals) const {
2036   Form::InterfaceType my_interface = interface_type(globals);
2037   return (my_interface == memory_interface);
2038 }
2039 
2040 
2041 // node matches ideal 'Bool'
2042 bool OperandForm::is_ideal_bool() const {
2043   if( _matrule == NULL ) return false;
2044 
2045   return _matrule->is_ideal_bool();
2046 }
2047 
2048 // Require user's name for an sRegX to be stackSlotX
2049 Form::DataType OperandForm::is_user_name_for_sReg() const {
2050   DataType data_type = none;
2051   if( _ident != NULL ) {
2052     if(      strcmp(_ident,"stackSlotI") == 0 ) data_type = Form::idealI;
2053     else if( strcmp(_ident,"stackSlotP") == 0 ) data_type = Form::idealP;
2054     else if( strcmp(_ident,"stackSlotD") == 0 ) data_type = Form::idealD;
2055     else if( strcmp(_ident,"stackSlotF") == 0 ) data_type = Form::idealF;
2056     else if( strcmp(_ident,"stackSlotL") == 0 ) data_type = Form::idealL;
2057   }
2058   assert((data_type == none) || (_matrule == NULL), "No match-rule for stackSlotX");
2059 
2060   return data_type;
2061 }
2062 
2063 
2064 // Return ideal type, if there is a single ideal type for this operand
2065 const char *OperandForm::ideal_type(FormDict &globals, RegisterForm *registers) const {
2066   const char *type = NULL;
2067   if (ideal_only()) type = _ident;
2068   else if( _matrule == NULL ) {
2069     // Check for condition code register
2070     const char *rc_name = constrained_reg_class();
2071     // !!!!!
2072     if (rc_name == NULL) return NULL;
2073     // !!!!! !!!!!
2074     // Check constraints on result's register class
2075     if( registers ) {
2076       RegClass *reg_class  = registers->getRegClass(rc_name);
2077       assert( reg_class != NULL, "Register class is not defined");
2078 
2079       // Check for ideal type of entries in register class, all are the same type
2080       reg_class->reset();
2081       RegDef *reg_def = reg_class->RegDef_iter();
2082       assert( reg_def != NULL, "No entries in register class");
2083       assert( reg_def->_idealtype != NULL, "Did not define ideal type for register");
2084       // Return substring that names the register's ideal type
2085       type = reg_def->_idealtype + 3;
2086       assert( *(reg_def->_idealtype + 0) == 'O', "Expect Op_ prefix");
2087       assert( *(reg_def->_idealtype + 1) == 'p', "Expect Op_ prefix");
2088       assert( *(reg_def->_idealtype + 2) == '_', "Expect Op_ prefix");
2089     }
2090   }
2091   else if( _matrule->_lChild == NULL && _matrule->_rChild == NULL ) {
2092     // This operand matches a single type, at the top level.
2093     // Check for ideal type
2094     type = _matrule->_opType;
2095     if( strcmp(type,"Bool") == 0 )
2096       return "Bool";
2097     // transitive lookup
2098     const Form *frm = globals[type];
2099     OperandForm *op = frm->is_operand();
2100     type = op->ideal_type(globals, registers);
2101   }
2102   return type;
2103 }
2104 
2105 
2106 // If there is a single ideal type for this interface field, return it.
2107 const char *OperandForm::interface_ideal_type(FormDict &globals,
2108                                               const char *field) const {
2109   const char  *ideal_type = NULL;
2110   const char  *value      = NULL;
2111 
2112   // Check if "field" is valid for this operand's interface
2113   if ( ! is_interface_field(field, value) )   return ideal_type;
2114 
2115   // !!!!! !!!!! !!!!!
2116   // If a valid field has a constant value, identify "ConI" or "ConP" or ...
2117 
2118   // Else, lookup type of field's replacement variable
2119 
2120   return ideal_type;
2121 }
2122 
2123 
2124 RegClass* OperandForm::get_RegClass() const {
2125   if (_interface && !_interface->is_RegInterface()) return NULL;
2126   return globalAD->get_registers()->getRegClass(constrained_reg_class());
2127 }
2128 
2129 
2130 bool OperandForm::is_bound_register() const {
2131   RegClass *reg_class  = get_RegClass();
2132   if (reg_class == NULL) return false;
2133 
2134   const char * name = ideal_type(globalAD->globalNames());
2135   if (name == NULL) return false;
2136 
2137   int size = 0;
2138   if (strcmp(name,"RegFlags")==0) size =  1;
2139   if (strcmp(name,"RegI")==0) size =  1;
2140   if (strcmp(name,"RegF")==0) size =  1;
2141   if (strcmp(name,"RegD")==0) size =  2;
2142   if (strcmp(name,"RegL")==0) size =  2;
2143   if (strcmp(name,"RegN")==0) size =  1;
2144   if (strcmp(name,"RegP")==0) size =  globalAD->get_preproc_def("_LP64") ? 2 : 1;
2145   if (size == 0) return false;
2146   return size == reg_class->size();
2147 }
2148 
2149 
2150 // Check if this is a valid field for this operand,
2151 // Return 'true' if valid, and set the value to the string the user provided.
2152 bool  OperandForm::is_interface_field(const char *field,
2153                                       const char * &value) const {
2154   return false;
2155 }
2156 
2157 
2158 // Return register class name if a constraint specifies the register class.
2159 const char *OperandForm::constrained_reg_class() const {
2160   const char *reg_class  = NULL;
2161   if ( _constraint ) {
2162     // !!!!!
2163     Constraint *constraint = _constraint;
2164     if ( strcmp(_constraint->_func,"ALLOC_IN_RC") == 0 ) {
2165       reg_class = _constraint->_arg;
2166     }
2167   }
2168 
2169   return reg_class;
2170 }
2171 
2172 
2173 // Return the register class associated with 'leaf'.
2174 const char *OperandForm::in_reg_class(uint leaf, FormDict &globals) {
2175   const char *reg_class = NULL; // "RegMask::Empty";
2176 
2177   if((_matrule == NULL) || (_matrule->is_chain_rule(globals))) {
2178     reg_class = constrained_reg_class();
2179     return reg_class;
2180   }
2181   const char *result   = NULL;
2182   const char *name     = NULL;
2183   const char *type     = NULL;
2184   // iterate through all base operands
2185   // until we reach the register that corresponds to "leaf"
2186   // This function is not looking for an ideal type.  It needs the first
2187   // level user type associated with the leaf.
2188   for(uint idx = 0;_matrule->base_operand(idx,globals,result,name,type);++idx) {
2189     const Form *form = (_localNames[name] ? _localNames[name] : globals[result]);
2190     OperandForm *oper = form ? form->is_operand() : NULL;
2191     if( oper ) {
2192       reg_class = oper->constrained_reg_class();
2193       if( reg_class ) {
2194         reg_class = reg_class;
2195       } else {
2196         // ShouldNotReachHere();
2197       }
2198     } else {
2199       // ShouldNotReachHere();
2200     }
2201 
2202     // Increment our target leaf position if current leaf is not a candidate.
2203     if( reg_class == NULL)    ++leaf;
2204     // Exit the loop with the value of reg_class when at the correct index
2205     if( idx == leaf )         break;
2206     // May iterate through all base operands if reg_class for 'leaf' is NULL
2207   }
2208   return reg_class;
2209 }
2210 
2211 
2212 // Recursive call to construct list of top-level operands.
2213 // Implementation does not modify state of internal structures
2214 void OperandForm::build_components() {
2215   if (_matrule)  _matrule->append_components(_localNames, _components);
2216 
2217   // Add parameters that "do not appear in match rule".
2218   const char *name;
2219   for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
2220     OperandForm *opForm = (OperandForm*)_localNames[name];
2221 
2222     if ( _components.operand_position(name) == -1 ) {
2223       _components.insert(name, opForm->_ident, Component::INVALID, false);
2224     }
2225   }
2226 
2227   return;
2228 }
2229 
2230 int OperandForm::operand_position(const char *name, int usedef) {
2231   return _components.operand_position(name, usedef);
2232 }
2233 
2234 
2235 // Return zero-based position in component list, only counting constants;
2236 // Return -1 if not in list.
2237 int OperandForm::constant_position(FormDict &globals, const Component *last) {
2238   // Iterate through components and count constants preceding 'constant'
2239   int position = 0;
2240   Component *comp;
2241   _components.reset();
2242   while( (comp = _components.iter()) != NULL  && (comp != last) ) {
2243     // Special case for operands that take a single user-defined operand
2244     // Skip the initial definition in the component list.
2245     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2246 
2247     const char *type = comp->_type;
2248     // Lookup operand form for replacement variable's type
2249     const Form *form = globals[type];
2250     assert( form != NULL, "Component's type not found");
2251     OperandForm *oper = form ? form->is_operand() : NULL;
2252     if( oper ) {
2253       if( oper->_matrule->is_base_constant(globals) != Form::none ) {
2254         ++position;
2255       }
2256     }
2257   }
2258 
2259   // Check for being passed a component that was not in the list
2260   if( comp != last )  position = -1;
2261 
2262   return position;
2263 }
2264 // Provide position of constant by "name"
2265 int OperandForm::constant_position(FormDict &globals, const char *name) {
2266   const Component *comp = _components.search(name);
2267   int idx = constant_position( globals, comp );
2268 
2269   return idx;
2270 }
2271 
2272 
2273 // Return zero-based position in component list, only counting constants;
2274 // Return -1 if not in list.
2275 int OperandForm::register_position(FormDict &globals, const char *reg_name) {
2276   // Iterate through components and count registers preceding 'last'
2277   uint  position = 0;
2278   Component *comp;
2279   _components.reset();
2280   while( (comp = _components.iter()) != NULL
2281          && (strcmp(comp->_name,reg_name) != 0) ) {
2282     // Special case for operands that take a single user-defined operand
2283     // Skip the initial definition in the component list.
2284     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2285 
2286     const char *type = comp->_type;
2287     // Lookup operand form for component's type
2288     const Form *form = globals[type];
2289     assert( form != NULL, "Component's type not found");
2290     OperandForm *oper = form ? form->is_operand() : NULL;
2291     if( oper ) {
2292       if( oper->_matrule->is_base_register(globals) ) {
2293         ++position;
2294       }
2295     }
2296   }
2297 
2298   return position;
2299 }
2300 
2301 
2302 const char *OperandForm::reduce_result()  const {
2303   return _ident;
2304 }
2305 // Return the name of the operand on the right hand side of the binary match
2306 // Return NULL if there is no right hand side
2307 const char *OperandForm::reduce_right(FormDict &globals)  const {
2308   return  ( _matrule ? _matrule->reduce_right(globals) : NULL );
2309 }
2310 
2311 // Similar for left
2312 const char *OperandForm::reduce_left(FormDict &globals)   const {
2313   return  ( _matrule ? _matrule->reduce_left(globals) : NULL );
2314 }
2315 
2316 
2317 // --------------------------- FILE *output_routines
2318 //
2319 // Output code for disp_is_oop, if true.
2320 void OperandForm::disp_is_oop(FILE *fp, FormDict &globals) {
2321   //  Check it is a memory interface with a non-user-constant disp field
2322   if ( this->_interface == NULL ) return;
2323   MemInterface *mem_interface = this->_interface->is_MemInterface();
2324   if ( mem_interface == NULL )    return;
2325   const char   *disp  = mem_interface->_disp;
2326   if ( *disp != '$' )             return;
2327 
2328   // Lookup replacement variable in operand's component list
2329   const char   *rep_var = disp + 1;
2330   const Component *comp = this->_components.search(rep_var);
2331   assert( comp != NULL, "Replacement variable not found in components");
2332   // Lookup operand form for replacement variable's type
2333   const char      *type = comp->_type;
2334   Form            *form = (Form*)globals[type];
2335   assert( form != NULL, "Replacement variable's type not found");
2336   OperandForm     *op   = form->is_operand();
2337   assert( op, "Memory Interface 'disp' can only emit an operand form");
2338   // Check if this is a ConP, which may require relocation
2339   if ( op->is_base_constant(globals) == Form::idealP ) {
2340     // Find the constant's index:  _c0, _c1, _c2, ... , _cN
2341     uint idx  = op->constant_position( globals, rep_var);
2342     fprintf(fp,"  virtual bool disp_is_oop() const {");
2343     fprintf(fp,  "  return _c%d->isa_oop_ptr();", idx);
2344     fprintf(fp, " }\n");
2345   }
2346 }
2347 
2348 // Generate code for internal and external format methods
2349 //
2350 // internal access to reg# node->_idx
2351 // access to subsumed constant _c0, _c1,
2352 void  OperandForm::int_format(FILE *fp, FormDict &globals, uint index) {
2353   Form::DataType dtype;
2354   if (_matrule && (_matrule->is_base_register(globals) ||
2355                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2356     // !!!!! !!!!!
2357     fprintf(fp,    "{ char reg_str[128];\n");
2358     fprintf(fp,"      ra->dump_register(node,reg_str);\n");
2359     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2360     fprintf(fp,"    }\n");
2361   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2362     format_constant( fp, index, dtype );
2363   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2364     // Special format for Stack Slot Register
2365     fprintf(fp,    "{ char reg_str[128];\n");
2366     fprintf(fp,"      ra->dump_register(node,reg_str);\n");
2367     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2368     fprintf(fp,"    }\n");
2369   } else {
2370     fprintf(fp,"tty->print(\"No format defined for %s\n\");\n", _ident);
2371     fflush(fp);
2372     fprintf(stderr,"No format defined for %s\n", _ident);
2373     dump();
2374     assert( false,"Internal error:\n  output_internal_operand() attempting to output other than a Register or Constant");
2375   }
2376 }
2377 
2378 // Similar to "int_format" but for cases where data is external to operand
2379 // external access to reg# node->in(idx)->_idx,
2380 void  OperandForm::ext_format(FILE *fp, FormDict &globals, uint index) {
2381   Form::DataType dtype;
2382   if (_matrule && (_matrule->is_base_register(globals) ||
2383                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2384     fprintf(fp,    "{ char reg_str[128];\n");
2385     fprintf(fp,"      ra->dump_register(node->in(idx");
2386     if ( index != 0 ) fprintf(fp,                  "+%d",index);
2387     fprintf(fp,                                       "),reg_str);\n");
2388     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2389     fprintf(fp,"    }\n");
2390   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2391     format_constant( fp, index, dtype );
2392   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2393     // Special format for Stack Slot Register
2394     fprintf(fp,    "{ char reg_str[128];\n");
2395     fprintf(fp,"      ra->dump_register(node->in(idx");
2396     if ( index != 0 ) fprintf(fp,                  "+%d",index);
2397     fprintf(fp,                                       "),reg_str);\n");
2398     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2399     fprintf(fp,"    }\n");
2400   } else {
2401     fprintf(fp,"tty->print(\"No format defined for %s\n\");\n", _ident);
2402     assert( false,"Internal error:\n  output_external_operand() attempting to output other than a Register or Constant");
2403   }
2404 }
2405 
2406 void OperandForm::format_constant(FILE *fp, uint const_index, uint const_type) {
2407   switch(const_type) {
2408   case Form::idealI:  fprintf(fp,"st->print(\"#%%d\", _c%d);\n", const_index); break;
2409   case Form::idealP:  fprintf(fp,"_c%d->dump_on(st);\n",         const_index); break;
2410   case Form::idealN:  fprintf(fp,"_c%d->dump_on(st);\n",         const_index); break;
2411   case Form::idealL:  fprintf(fp,"st->print(\"#%%lld\", _c%d);\n", const_index); break;
2412   case Form::idealF:  fprintf(fp,"st->print(\"#%%f\", _c%d);\n", const_index); break;
2413   case Form::idealD:  fprintf(fp,"st->print(\"#%%f\", _c%d);\n", const_index); break;
2414   default:
2415     assert( false, "ShouldNotReachHere()");
2416   }
2417 }
2418 
2419 // Return the operand form corresponding to the given index, else NULL.
2420 OperandForm *OperandForm::constant_operand(FormDict &globals,
2421                                            uint      index) {
2422   // !!!!!
2423   // Check behavior on complex operands
2424   uint n_consts = num_consts(globals);
2425   if( n_consts > 0 ) {
2426     uint i = 0;
2427     const char *type;
2428     Component  *comp;
2429     _components.reset();
2430     if ((comp = _components.iter()) == NULL) {
2431       assert(n_consts == 1, "Bad component list detected.\n");
2432       // Current operand is THE operand
2433       if ( index == 0 ) {
2434         return this;
2435       }
2436     } // end if NULL
2437     else {
2438       // Skip the first component, it can not be a DEF of a constant
2439       do {
2440         type = comp->base_type(globals);
2441         // Check that "type" is a 'ConI', 'ConP', ...
2442         if ( ideal_to_const_type(type) != Form::none ) {
2443           // When at correct component, get corresponding Operand
2444           if ( index == 0 ) {
2445             return globals[comp->_type]->is_operand();
2446           }
2447           // Decrement number of constants to go
2448           --index;
2449         }
2450       } while((comp = _components.iter()) != NULL);
2451     }
2452   }
2453 
2454   // Did not find a constant for this index.
2455   return NULL;
2456 }
2457 
2458 // If this operand has a single ideal type, return its type
2459 Form::DataType OperandForm::simple_type(FormDict &globals) const {
2460   const char *type_name = ideal_type(globals);
2461   Form::DataType type   = type_name ? ideal_to_const_type( type_name )
2462                                     : Form::none;
2463   return type;
2464 }
2465 
2466 Form::DataType OperandForm::is_base_constant(FormDict &globals) const {
2467   if ( _matrule == NULL )    return Form::none;
2468 
2469   return _matrule->is_base_constant(globals);
2470 }
2471 
2472 // "true" if this operand is a simple type that is swallowed
2473 bool  OperandForm::swallowed(FormDict &globals) const {
2474   Form::DataType type   = simple_type(globals);
2475   if( type != Form::none ) {
2476     return true;
2477   }
2478 
2479   return false;
2480 }
2481 
2482 // Output code to access the value of the index'th constant
2483 void OperandForm::access_constant(FILE *fp, FormDict &globals,
2484                                   uint const_index) {
2485   OperandForm *oper = constant_operand(globals, const_index);
2486   assert( oper, "Index exceeds number of constants in operand");
2487   Form::DataType dtype = oper->is_base_constant(globals);
2488 
2489   switch(dtype) {
2490   case idealI: fprintf(fp,"_c%d",           const_index); break;
2491   case idealP: fprintf(fp,"_c%d->get_con()",const_index); break;
2492   case idealL: fprintf(fp,"_c%d",           const_index); break;
2493   case idealF: fprintf(fp,"_c%d",           const_index); break;
2494   case idealD: fprintf(fp,"_c%d",           const_index); break;
2495   default:
2496     assert( false, "ShouldNotReachHere()");
2497   }
2498 }
2499 
2500 
2501 void OperandForm::dump() {
2502   output(stderr);
2503 }
2504 
2505 void OperandForm::output(FILE *fp) {
2506   fprintf(fp,"\nOperand: %s\n", (_ident?_ident:""));
2507   if (_matrule)    _matrule->dump();
2508   if (_interface)  _interface->dump();
2509   if (_attribs)    _attribs->dump();
2510   if (_predicate)  _predicate->dump();
2511   if (_constraint) _constraint->dump();
2512   if (_construct)  _construct->dump();
2513   if (_format)     _format->dump();
2514 }
2515 
2516 //------------------------------Constraint-------------------------------------
2517 Constraint::Constraint(const char *func, const char *arg)
2518   : _func(func), _arg(arg) {
2519 }
2520 Constraint::~Constraint() { /* not owner of char* */
2521 }
2522 
2523 bool Constraint::stack_slots_only() const {
2524   return strcmp(_func, "ALLOC_IN_RC") == 0
2525       && strcmp(_arg,  "stack_slots") == 0;
2526 }
2527 
2528 void Constraint::dump() {
2529   output(stderr);
2530 }
2531 
2532 void Constraint::output(FILE *fp) {           // Write info to output files
2533   assert((_func != NULL && _arg != NULL),"missing constraint function or arg");
2534   fprintf(fp,"Constraint: %s ( %s )\n", _func, _arg);
2535 }
2536 
2537 //------------------------------Predicate--------------------------------------
2538 Predicate::Predicate(char *pr)
2539   : _pred(pr) {
2540 }
2541 Predicate::~Predicate() {
2542 }
2543 
2544 void Predicate::dump() {
2545   output(stderr);
2546 }
2547 
2548 void Predicate::output(FILE *fp) {
2549   fprintf(fp,"Predicate");  // Write to output files
2550 }
2551 //------------------------------Interface--------------------------------------
2552 Interface::Interface(const char *name) : _name(name) {
2553 }
2554 Interface::~Interface() {
2555 }
2556 
2557 Form::InterfaceType Interface::interface_type(FormDict &globals) const {
2558   Interface *thsi = (Interface*)this;
2559   if ( thsi->is_RegInterface()   ) return Form::register_interface;
2560   if ( thsi->is_MemInterface()   ) return Form::memory_interface;
2561   if ( thsi->is_ConstInterface() ) return Form::constant_interface;
2562   if ( thsi->is_CondInterface()  ) return Form::conditional_interface;
2563 
2564   return Form::no_interface;
2565 }
2566 
2567 RegInterface   *Interface::is_RegInterface() {
2568   if ( strcmp(_name,"REG_INTER") != 0 )
2569     return NULL;
2570   return (RegInterface*)this;
2571 }
2572 MemInterface   *Interface::is_MemInterface() {
2573   if ( strcmp(_name,"MEMORY_INTER") != 0 )  return NULL;
2574   return (MemInterface*)this;
2575 }
2576 ConstInterface *Interface::is_ConstInterface() {
2577   if ( strcmp(_name,"CONST_INTER") != 0 )  return NULL;
2578   return (ConstInterface*)this;
2579 }
2580 CondInterface  *Interface::is_CondInterface() {
2581   if ( strcmp(_name,"COND_INTER") != 0 )  return NULL;
2582   return (CondInterface*)this;
2583 }
2584 
2585 
2586 void Interface::dump() {
2587   output(stderr);
2588 }
2589 
2590 // Write info to output files
2591 void Interface::output(FILE *fp) {
2592   fprintf(fp,"Interface: %s\n", (_name ? _name : "") );
2593 }
2594 
2595 //------------------------------RegInterface-----------------------------------
2596 RegInterface::RegInterface() : Interface("REG_INTER") {
2597 }
2598 RegInterface::~RegInterface() {
2599 }
2600 
2601 void RegInterface::dump() {
2602   output(stderr);
2603 }
2604 
2605 // Write info to output files
2606 void RegInterface::output(FILE *fp) {
2607   Interface::output(fp);
2608 }
2609 
2610 //------------------------------ConstInterface---------------------------------
2611 ConstInterface::ConstInterface() : Interface("CONST_INTER") {
2612 }
2613 ConstInterface::~ConstInterface() {
2614 }
2615 
2616 void ConstInterface::dump() {
2617   output(stderr);
2618 }
2619 
2620 // Write info to output files
2621 void ConstInterface::output(FILE *fp) {
2622   Interface::output(fp);
2623 }
2624 
2625 //------------------------------MemInterface-----------------------------------
2626 MemInterface::MemInterface(char *base, char *index, char *scale, char *disp)
2627   : Interface("MEMORY_INTER"), _base(base), _index(index), _scale(scale), _disp(disp) {
2628 }
2629 MemInterface::~MemInterface() {
2630   // not owner of any character arrays
2631 }
2632 
2633 void MemInterface::dump() {
2634   output(stderr);
2635 }
2636 
2637 // Write info to output files
2638 void MemInterface::output(FILE *fp) {
2639   Interface::output(fp);
2640   if ( _base  != NULL ) fprintf(fp,"  base  == %s\n", _base);
2641   if ( _index != NULL ) fprintf(fp,"  index == %s\n", _index);
2642   if ( _scale != NULL ) fprintf(fp,"  scale == %s\n", _scale);
2643   if ( _disp  != NULL ) fprintf(fp,"  disp  == %s\n", _disp);
2644   // fprintf(fp,"\n");
2645 }
2646 
2647 //------------------------------CondInterface----------------------------------
2648 CondInterface::CondInterface(const char* equal,         const char* equal_format,
2649                              const char* not_equal,     const char* not_equal_format,
2650                              const char* less,          const char* less_format,
2651                              const char* greater_equal, const char* greater_equal_format,
2652                              const char* less_equal,    const char* less_equal_format,
2653                              const char* greater,       const char* greater_format)
2654   : Interface("COND_INTER"),
2655     _equal(equal),                 _equal_format(equal_format),
2656     _not_equal(not_equal),         _not_equal_format(not_equal_format),
2657     _less(less),                   _less_format(less_format),
2658     _greater_equal(greater_equal), _greater_equal_format(greater_equal_format),
2659     _less_equal(less_equal),       _less_equal_format(less_equal_format),
2660     _greater(greater),             _greater_format(greater_format) {
2661 }
2662 CondInterface::~CondInterface() {
2663   // not owner of any character arrays
2664 }
2665 
2666 void CondInterface::dump() {
2667   output(stderr);
2668 }
2669 
2670 // Write info to output files
2671 void CondInterface::output(FILE *fp) {
2672   Interface::output(fp);
2673   if ( _equal  != NULL )     fprintf(fp," equal       == %s\n", _equal);
2674   if ( _not_equal  != NULL ) fprintf(fp," not_equal   == %s\n", _not_equal);
2675   if ( _less  != NULL )      fprintf(fp," less        == %s\n", _less);
2676   if ( _greater_equal  != NULL ) fprintf(fp," greater_equal   == %s\n", _greater_equal);
2677   if ( _less_equal  != NULL ) fprintf(fp," less_equal  == %s\n", _less_equal);
2678   if ( _greater  != NULL )    fprintf(fp," greater     == %s\n", _greater);
2679   // fprintf(fp,"\n");
2680 }
2681 
2682 //------------------------------ConstructRule----------------------------------
2683 ConstructRule::ConstructRule(char *cnstr)
2684   : _construct(cnstr) {
2685 }
2686 ConstructRule::~ConstructRule() {
2687 }
2688 
2689 void ConstructRule::dump() {
2690   output(stderr);
2691 }
2692 
2693 void ConstructRule::output(FILE *fp) {
2694   fprintf(fp,"\nConstruct Rule\n");  // Write to output files
2695 }
2696 
2697 
2698 //==============================Shared Forms===================================
2699 //------------------------------AttributeForm----------------------------------
2700 int         AttributeForm::_insId   = 0;           // start counter at 0
2701 int         AttributeForm::_opId    = 0;           // start counter at 0
2702 const char* AttributeForm::_ins_cost = "ins_cost"; // required name
2703 const char* AttributeForm::_op_cost  = "op_cost";  // required name
2704 
2705 AttributeForm::AttributeForm(char *attr, int type, char *attrdef)
2706   : Form(Form::ATTR), _attrname(attr), _atype(type), _attrdef(attrdef) {
2707     if (type==OP_ATTR) {
2708       id = ++_opId;
2709     }
2710     else if (type==INS_ATTR) {
2711       id = ++_insId;
2712     }
2713     else assert( false,"");
2714 }
2715 AttributeForm::~AttributeForm() {
2716 }
2717 
2718 // Dynamic type check
2719 AttributeForm *AttributeForm::is_attribute() const {
2720   return (AttributeForm*)this;
2721 }
2722 
2723 
2724 // inlined  // int  AttributeForm::type() { return id;}
2725 
2726 void AttributeForm::dump() {
2727   output(stderr);
2728 }
2729 
2730 void AttributeForm::output(FILE *fp) {
2731   if( _attrname && _attrdef ) {
2732     fprintf(fp,"\n// AttributeForm \nstatic const int %s = %s;\n",
2733             _attrname, _attrdef);
2734   }
2735   else {
2736     fprintf(fp,"\n// AttributeForm missing name %s or definition %s\n",
2737             (_attrname?_attrname:""), (_attrdef?_attrdef:"") );
2738   }
2739 }
2740 
2741 //------------------------------Component--------------------------------------
2742 Component::Component(const char *name, const char *type, int usedef)
2743   : _name(name), _type(type), _usedef(usedef) {
2744     _ftype = Form::COMP;
2745 }
2746 Component::~Component() {
2747 }
2748 
2749 // True if this component is equal to the parameter.
2750 bool Component::is(int use_def_kill_enum) const {
2751   return (_usedef == use_def_kill_enum ? true : false);
2752 }
2753 // True if this component is used/def'd/kill'd as the parameter suggests.
2754 bool Component::isa(int use_def_kill_enum) const {
2755   return (_usedef & use_def_kill_enum) == use_def_kill_enum;
2756 }
2757 
2758 // Extend this component with additional use/def/kill behavior
2759 int Component::promote_use_def_info(int new_use_def) {
2760   _usedef |= new_use_def;
2761 
2762   return _usedef;
2763 }
2764 
2765 // Check the base type of this component, if it has one
2766 const char *Component::base_type(FormDict &globals) {
2767   const Form *frm = globals[_type];
2768   if (frm == NULL) return NULL;
2769   OperandForm *op = frm->is_operand();
2770   if (op == NULL) return NULL;
2771   if (op->ideal_only()) return op->_ident;
2772   return (char *)op->ideal_type(globals);
2773 }
2774 
2775 void Component::dump() {
2776   output(stderr);
2777 }
2778 
2779 void Component::output(FILE *fp) {
2780   fprintf(fp,"Component:");  // Write to output files
2781   fprintf(fp, "  name = %s", _name);
2782   fprintf(fp, ", type = %s", _type);
2783   const char * usedef = "Undefined Use/Def info";
2784   switch (_usedef) {
2785     case USE:      usedef = "USE";      break;
2786     case USE_DEF:  usedef = "USE_DEF";  break;
2787     case USE_KILL: usedef = "USE_KILL"; break;
2788     case KILL:     usedef = "KILL";     break;
2789     case TEMP:     usedef = "TEMP";     break;
2790     case DEF:      usedef = "DEF";      break;
2791     default: assert(false, "unknown effect");
2792   }
2793   fprintf(fp, ", use/def = %s\n", usedef);
2794 }
2795 
2796 
2797 //------------------------------ComponentList---------------------------------
2798 ComponentList::ComponentList() : NameList(), _matchcnt(0) {
2799 }
2800 ComponentList::~ComponentList() {
2801   // // This list may not own its elements if copied via assignment
2802   // Component *component;
2803   // for (reset(); (component = iter()) != NULL;) {
2804   //   delete component;
2805   // }
2806 }
2807 
2808 void   ComponentList::insert(Component *component, bool mflag) {
2809   NameList::addName((char *)component);
2810   if(mflag) _matchcnt++;
2811 }
2812 void   ComponentList::insert(const char *name, const char *opType, int usedef,
2813                              bool mflag) {
2814   Component * component = new Component(name, opType, usedef);
2815   insert(component, mflag);
2816 }
2817 Component *ComponentList::current() { return (Component*)NameList::current(); }
2818 Component *ComponentList::iter()    { return (Component*)NameList::iter(); }
2819 Component *ComponentList::match_iter() {
2820   if(_iter < _matchcnt) return (Component*)NameList::iter();
2821   return NULL;
2822 }
2823 Component *ComponentList::post_match_iter() {
2824   Component *comp = iter();
2825   // At end of list?
2826   if ( comp == NULL ) {
2827     return comp;
2828   }
2829   // In post-match components?
2830   if (_iter > match_count()-1) {
2831     return comp;
2832   }
2833 
2834   return post_match_iter();
2835 }
2836 
2837 void       ComponentList::reset()   { NameList::reset(); }
2838 int        ComponentList::count()   { return NameList::count(); }
2839 
2840 Component *ComponentList::operator[](int position) {
2841   // Shortcut complete iteration if there are not enough entries
2842   if (position >= count()) return NULL;
2843 
2844   int        index     = 0;
2845   Component *component = NULL;
2846   for (reset(); (component = iter()) != NULL;) {
2847     if (index == position) {
2848       return component;
2849     }
2850     ++index;
2851   }
2852 
2853   return NULL;
2854 }
2855 
2856 const Component *ComponentList::search(const char *name) {
2857   PreserveIter pi(this);
2858   reset();
2859   for( Component *comp = NULL; ((comp = iter()) != NULL); ) {
2860     if( strcmp(comp->_name,name) == 0 ) return comp;
2861   }
2862 
2863   return NULL;
2864 }
2865 
2866 // Return number of USEs + number of DEFs
2867 // When there are no components, or the first component is a USE,
2868 // then we add '1' to hold a space for the 'result' operand.
2869 int ComponentList::num_operands() {
2870   PreserveIter pi(this);
2871   uint       count = 1;           // result operand
2872   uint       position = 0;
2873 
2874   Component *component  = NULL;
2875   for( reset(); (component = iter()) != NULL; ++position ) {
2876     if( component->isa(Component::USE) ||
2877         ( position == 0 && (! component->isa(Component::DEF))) ) {
2878       ++count;
2879     }
2880   }
2881 
2882   return count;
2883 }
2884 
2885 // Return zero-based position in list;  -1 if not in list.
2886 // if parameter 'usedef' is ::USE, it will match USE, USE_DEF, ...
2887 int ComponentList::operand_position(const char *name, int usedef) {
2888   PreserveIter pi(this);
2889   int position = 0;
2890   int num_opnds = num_operands();
2891   Component *component;
2892   Component* preceding_non_use = NULL;
2893   Component* first_def = NULL;
2894   for (reset(); (component = iter()) != NULL; ++position) {
2895     // When the first component is not a DEF,
2896     // leave space for the result operand!
2897     if ( position==0 && (! component->isa(Component::DEF)) ) {
2898       ++position;
2899       ++num_opnds;
2900     }
2901     if (strcmp(name, component->_name)==0 && (component->isa(usedef))) {
2902       // When the first entry in the component list is a DEF and a USE
2903       // Treat them as being separate, a DEF first, then a USE
2904       if( position==0
2905           && usedef==Component::USE && component->isa(Component::DEF) ) {
2906         assert(position+1 < num_opnds, "advertised index in bounds");
2907         return position+1;
2908       } else {
2909         if( preceding_non_use && strcmp(component->_name, preceding_non_use->_name) ) {
2910           fprintf(stderr, "the name '%s' should not precede the name '%s'\n", preceding_non_use->_name, name);
2911         }
2912         if( position >= num_opnds ) {
2913           fprintf(stderr, "the name '%s' is too late in its name list\n", name);
2914         }
2915         assert(position < num_opnds, "advertised index in bounds");
2916         return position;
2917       }
2918     }
2919     if( component->isa(Component::DEF)
2920         && component->isa(Component::USE) ) {
2921       ++position;
2922       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2923     }
2924     if( component->isa(Component::DEF) && !first_def ) {
2925       first_def = component;
2926     }
2927     if( !component->isa(Component::USE) && component != first_def ) {
2928       preceding_non_use = component;
2929     } else if( preceding_non_use && !strcmp(component->_name, preceding_non_use->_name) ) {
2930       preceding_non_use = NULL;
2931     }
2932   }
2933   return Not_in_list;
2934 }
2935 
2936 // Find position for this name, regardless of use/def information
2937 int ComponentList::operand_position(const char *name) {
2938   PreserveIter pi(this);
2939   int position = 0;
2940   Component *component;
2941   for (reset(); (component = iter()) != NULL; ++position) {
2942     // When the first component is not a DEF,
2943     // leave space for the result operand!
2944     if ( position==0 && (! component->isa(Component::DEF)) ) {
2945       ++position;
2946     }
2947     if (strcmp(name, component->_name)==0) {
2948       return position;
2949     }
2950     if( component->isa(Component::DEF)
2951         && component->isa(Component::USE) ) {
2952       ++position;
2953       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2954     }
2955   }
2956   return Not_in_list;
2957 }
2958 
2959 int ComponentList::operand_position_format(const char *name) {
2960   PreserveIter pi(this);
2961   int  first_position = operand_position(name);
2962   int  use_position   = operand_position(name, Component::USE);
2963 
2964   return ((first_position < use_position) ? use_position : first_position);
2965 }
2966 
2967 int ComponentList::label_position() {
2968   PreserveIter pi(this);
2969   int position = 0;
2970   reset();
2971   for( Component *comp; (comp = iter()) != NULL; ++position) {
2972     // When the first component is not a DEF,
2973     // leave space for the result operand!
2974     if ( position==0 && (! comp->isa(Component::DEF)) ) {
2975       ++position;
2976     }
2977     if (strcmp(comp->_type, "label")==0) {
2978       return position;
2979     }
2980     if( comp->isa(Component::DEF)
2981         && comp->isa(Component::USE) ) {
2982       ++position;
2983       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2984     }
2985   }
2986 
2987   return -1;
2988 }
2989 
2990 int ComponentList::method_position() {
2991   PreserveIter pi(this);
2992   int position = 0;
2993   reset();
2994   for( Component *comp; (comp = iter()) != NULL; ++position) {
2995     // When the first component is not a DEF,
2996     // leave space for the result operand!
2997     if ( position==0 && (! comp->isa(Component::DEF)) ) {
2998       ++position;
2999     }
3000     if (strcmp(comp->_type, "method")==0) {
3001       return position;
3002     }
3003     if( comp->isa(Component::DEF)
3004         && comp->isa(Component::USE) ) {
3005       ++position;
3006       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3007     }
3008   }
3009 
3010   return -1;
3011 }
3012 
3013 void ComponentList::dump() { output(stderr); }
3014 
3015 void ComponentList::output(FILE *fp) {
3016   PreserveIter pi(this);
3017   fprintf(fp, "\n");
3018   Component *component;
3019   for (reset(); (component = iter()) != NULL;) {
3020     component->output(fp);
3021   }
3022   fprintf(fp, "\n");
3023 }
3024 
3025 //------------------------------MatchNode--------------------------------------
3026 MatchNode::MatchNode(ArchDesc &ad, const char *result, const char *mexpr,
3027                      const char *opType, MatchNode *lChild, MatchNode *rChild)
3028   : _AD(ad), _result(result), _name(mexpr), _opType(opType),
3029     _lChild(lChild), _rChild(rChild), _internalop(0), _numleaves(0),
3030     _commutative_id(0) {
3031   _numleaves = (lChild ? lChild->_numleaves : 0)
3032                + (rChild ? rChild->_numleaves : 0);
3033 }
3034 
3035 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode)
3036   : _AD(ad), _result(mnode._result), _name(mnode._name),
3037     _opType(mnode._opType), _lChild(mnode._lChild), _rChild(mnode._rChild),
3038     _internalop(0), _numleaves(mnode._numleaves),
3039     _commutative_id(mnode._commutative_id) {
3040 }
3041 
3042 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode, int clone)
3043   : _AD(ad), _result(mnode._result), _name(mnode._name),
3044     _opType(mnode._opType),
3045     _internalop(0), _numleaves(mnode._numleaves),
3046     _commutative_id(mnode._commutative_id) {
3047   if (mnode._lChild) {
3048     _lChild = new MatchNode(ad, *mnode._lChild, clone);
3049   } else {
3050     _lChild = NULL;
3051   }
3052   if (mnode._rChild) {
3053     _rChild = new MatchNode(ad, *mnode._rChild, clone);
3054   } else {
3055     _rChild = NULL;
3056   }
3057 }
3058 
3059 MatchNode::~MatchNode() {
3060   // // This node may not own its children if copied via assignment
3061   // if( _lChild ) delete _lChild;
3062   // if( _rChild ) delete _rChild;
3063 }
3064 
3065 bool  MatchNode::find_type(const char *type, int &position) const {
3066   if ( (_lChild != NULL) && (_lChild->find_type(type, position)) ) return true;
3067   if ( (_rChild != NULL) && (_rChild->find_type(type, position)) ) return true;
3068 
3069   if (strcmp(type,_opType)==0)  {
3070     return true;
3071   } else {
3072     ++position;
3073   }
3074   return false;
3075 }
3076 
3077 // Recursive call collecting info on top-level operands, not transitive.
3078 // Implementation does not modify state of internal structures.
3079 void MatchNode::append_components(FormDict& locals, ComponentList& components,
3080                                   bool def_flag) const {
3081   int usedef = def_flag ? Component::DEF : Component::USE;
3082   FormDict &globals = _AD.globalNames();
3083 
3084   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3085   // Base case
3086   if (_lChild==NULL && _rChild==NULL) {
3087     // If _opType is not an operation, do not build a component for it #####
3088     const Form *f = globals[_opType];
3089     if( f != NULL ) {
3090       // Add non-ideals that are operands, operand-classes,
3091       if( ! f->ideal_only()
3092           && (f->is_opclass() || f->is_operand()) ) {
3093         components.insert(_name, _opType, usedef, true);
3094       }
3095     }
3096     return;
3097   }
3098   // Promote results of "Set" to DEF
3099   bool tmpdef_flag = (!strcmp(_opType, "Set")) ? true : false;
3100   if (_lChild) _lChild->append_components(locals, components, tmpdef_flag);
3101   tmpdef_flag = false;   // only applies to component immediately following 'Set'
3102   if (_rChild) _rChild->append_components(locals, components, tmpdef_flag);
3103 }
3104 
3105 // Find the n'th base-operand in the match node,
3106 // recursively investigates match rules of user-defined operands.
3107 //
3108 // Implementation does not modify state of internal structures since they
3109 // can be shared.
3110 bool MatchNode::base_operand(uint &position, FormDict &globals,
3111                              const char * &result, const char * &name,
3112                              const char * &opType) const {
3113   assert (_name != NULL, "MatchNode::base_operand encountered empty node\n");
3114   // Base case
3115   if (_lChild==NULL && _rChild==NULL) {
3116     // Check for special case: "Universe", "label"
3117     if (strcmp(_opType,"Universe") == 0 || strcmp(_opType,"label")==0 ) {
3118       if (position == 0) {
3119         result = _result;
3120         name   = _name;
3121         opType = _opType;
3122         return 1;
3123       } else {
3124         -- position;
3125         return 0;
3126       }
3127     }
3128 
3129     const Form *form = globals[_opType];
3130     MatchNode *matchNode = NULL;
3131     // Check for user-defined type
3132     if (form) {
3133       // User operand or instruction?
3134       OperandForm  *opForm = form->is_operand();
3135       InstructForm *inForm = form->is_instruction();
3136       if ( opForm ) {
3137         matchNode = (MatchNode*)opForm->_matrule;
3138       } else if ( inForm ) {
3139         matchNode = (MatchNode*)inForm->_matrule;
3140       }
3141     }
3142     // if this is user-defined, recurse on match rule
3143     // User-defined operand and instruction forms have a match-rule.
3144     if (matchNode) {
3145       return (matchNode->base_operand(position,globals,result,name,opType));
3146     } else {
3147       // Either not a form, or a system-defined form (no match rule).
3148       if (position==0) {
3149         result = _result;
3150         name   = _name;
3151         opType = _opType;
3152         return 1;
3153       } else {
3154         --position;
3155         return 0;
3156       }
3157     }
3158 
3159   } else {
3160     // Examine the left child and right child as well
3161     if (_lChild) {
3162       if (_lChild->base_operand(position, globals, result, name, opType))
3163         return 1;
3164     }
3165 
3166     if (_rChild) {
3167       if (_rChild->base_operand(position, globals, result, name, opType))
3168         return 1;
3169     }
3170   }
3171 
3172   return 0;
3173 }
3174 
3175 // Recursive call on all operands' match rules in my match rule.
3176 uint  MatchNode::num_consts(FormDict &globals) const {
3177   uint        index      = 0;
3178   uint        num_consts = 0;
3179   const char *result;
3180   const char *name;
3181   const char *opType;
3182 
3183   for (uint position = index;
3184        base_operand(position,globals,result,name,opType); position = index) {
3185     ++index;
3186     if( ideal_to_const_type(opType) )        num_consts++;
3187   }
3188 
3189   return num_consts;
3190 }
3191 
3192 // Recursive call on all operands' match rules in my match rule.
3193 // Constants in match rule subtree with specified type
3194 uint  MatchNode::num_consts(FormDict &globals, Form::DataType type) const {
3195   uint        index      = 0;
3196   uint        num_consts = 0;
3197   const char *result;
3198   const char *name;
3199   const char *opType;
3200 
3201   for (uint position = index;
3202        base_operand(position,globals,result,name,opType); position = index) {
3203     ++index;
3204     if( ideal_to_const_type(opType) == type ) num_consts++;
3205   }
3206 
3207   return num_consts;
3208 }
3209 
3210 // Recursive call on all operands' match rules in my match rule.
3211 uint  MatchNode::num_const_ptrs(FormDict &globals) const {
3212   return  num_consts( globals, Form::idealP );
3213 }
3214 
3215 bool  MatchNode::sets_result() const {
3216   return   ( (strcmp(_name,"Set") == 0) ? true : false );
3217 }
3218 
3219 const char *MatchNode::reduce_right(FormDict &globals) const {
3220   // If there is no right reduction, return NULL.
3221   const char      *rightStr    = NULL;
3222 
3223   // If we are a "Set", start from the right child.
3224   const MatchNode *const mnode = sets_result() ?
3225     (const MatchNode *const)this->_rChild :
3226     (const MatchNode *const)this;
3227 
3228   // If our right child exists, it is the right reduction
3229   if ( mnode->_rChild ) {
3230     rightStr = mnode->_rChild->_internalop ? mnode->_rChild->_internalop
3231       : mnode->_rChild->_opType;
3232   }
3233   // Else, May be simple chain rule: (Set dst operand_form), rightStr=NULL;
3234   return rightStr;
3235 }
3236 
3237 const char *MatchNode::reduce_left(FormDict &globals) const {
3238   // If there is no left reduction, return NULL.
3239   const char  *leftStr  = NULL;
3240 
3241   // If we are a "Set", start from the right child.
3242   const MatchNode *const mnode = sets_result() ?
3243     (const MatchNode *const)this->_rChild :
3244     (const MatchNode *const)this;
3245 
3246   // If our left child exists, it is the left reduction
3247   if ( mnode->_lChild ) {
3248     leftStr = mnode->_lChild->_internalop ? mnode->_lChild->_internalop
3249       : mnode->_lChild->_opType;
3250   } else {
3251     // May be simple chain rule: (Set dst operand_form_source)
3252     if ( sets_result() ) {
3253       OperandForm *oper = globals[mnode->_opType]->is_operand();
3254       if( oper ) {
3255         leftStr = mnode->_opType;
3256       }
3257     }
3258   }
3259   return leftStr;
3260 }
3261 
3262 //------------------------------count_instr_names------------------------------
3263 // Count occurrences of operands names in the leaves of the instruction
3264 // match rule.
3265 void MatchNode::count_instr_names( Dict &names ) {
3266   if( !this ) return;
3267   if( _lChild ) _lChild->count_instr_names(names);
3268   if( _rChild ) _rChild->count_instr_names(names);
3269   if( !_lChild && !_rChild ) {
3270     uintptr_t cnt = (uintptr_t)names[_name];
3271     cnt++;                      // One more name found
3272     names.Insert(_name,(void*)cnt);
3273   }
3274 }
3275 
3276 //------------------------------build_instr_pred-------------------------------
3277 // Build a path to 'name' in buf.  Actually only build if cnt is zero, so we
3278 // can skip some leading instances of 'name'.
3279 int MatchNode::build_instr_pred( char *buf, const char *name, int cnt ) {
3280   if( _lChild ) {
3281     if( !cnt ) strcpy( buf, "_kids[0]->" );
3282     cnt = _lChild->build_instr_pred( buf+strlen(buf), name, cnt );
3283     if( cnt < 0 ) return cnt;   // Found it, all done
3284   }
3285   if( _rChild ) {
3286     if( !cnt ) strcpy( buf, "_kids[1]->" );
3287     cnt = _rChild->build_instr_pred( buf+strlen(buf), name, cnt );
3288     if( cnt < 0 ) return cnt;   // Found it, all done
3289   }
3290   if( !_lChild && !_rChild ) {  // Found a leaf
3291     // Wrong name?  Give up...
3292     if( strcmp(name,_name) ) return cnt;
3293     if( !cnt ) strcpy(buf,"_leaf");
3294     return cnt-1;
3295   }
3296   return cnt;
3297 }
3298 
3299 
3300 //------------------------------build_internalop-------------------------------
3301 // Build string representation of subtree
3302 void MatchNode::build_internalop( ) {
3303   char *iop, *subtree;
3304   const char *lstr, *rstr;
3305   // Build string representation of subtree
3306   // Operation lchildType rchildType
3307   int len = (int)strlen(_opType) + 4;
3308   lstr = (_lChild) ? ((_lChild->_internalop) ?
3309                        _lChild->_internalop : _lChild->_opType) : "";
3310   rstr = (_rChild) ? ((_rChild->_internalop) ?
3311                        _rChild->_internalop : _rChild->_opType) : "";
3312   len += (int)strlen(lstr) + (int)strlen(rstr);
3313   subtree = (char *)malloc(len);
3314   sprintf(subtree,"_%s_%s_%s", _opType, lstr, rstr);
3315   // Hash the subtree string in _internalOps; if a name exists, use it
3316   iop = (char *)_AD._internalOps[subtree];
3317   // Else create a unique name, and add it to the hash table
3318   if (iop == NULL) {
3319     iop = subtree;
3320     _AD._internalOps.Insert(subtree, iop);
3321     _AD._internalOpNames.addName(iop);
3322     _AD._internalMatch.Insert(iop, this);
3323   }
3324   // Add the internal operand name to the MatchNode
3325   _internalop = iop;
3326   _result = iop;
3327 }
3328 
3329 
3330 void MatchNode::dump() {
3331   output(stderr);
3332 }
3333 
3334 void MatchNode::output(FILE *fp) {
3335   if (_lChild==0 && _rChild==0) {
3336     fprintf(fp," %s",_name);    // operand
3337   }
3338   else {
3339     fprintf(fp," (%s ",_name);  // " (opcodeName "
3340     if(_lChild) _lChild->output(fp); //               left operand
3341     if(_rChild) _rChild->output(fp); //                    right operand
3342     fprintf(fp,")");                 //                                 ")"
3343   }
3344 }
3345 
3346 int MatchNode::needs_ideal_memory_edge(FormDict &globals) const {
3347   static const char *needs_ideal_memory_list[] = {
3348     "StoreI","StoreL","StoreP","StoreN","StoreD","StoreF" ,
3349     "StoreB","StoreC","Store" ,"StoreFP",
3350     "LoadI", "LoadUI2L", "LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
3351     "LoadB" , "LoadUB", "LoadUS" ,"LoadS" ,"Load"   ,
3352     "Store4I","Store2I","Store2L","Store2D","Store4F","Store2F","Store16B",
3353     "Store8B","Store4B","Store8C","Store4C","Store2C",
3354     "Load4I" ,"Load2I" ,"Load2L" ,"Load2D" ,"Load4F" ,"Load2F" ,"Load16B" ,
3355     "Load8B" ,"Load4B" ,"Load8C" ,"Load4C" ,"Load2C" ,"Load8S", "Load4S","Load2S",
3356     "LoadRange", "LoadKlass", "LoadNKlass", "LoadL_unaligned", "LoadD_unaligned",
3357     "LoadPLocked", "LoadLLocked",
3358     "StorePConditional", "StoreIConditional", "StoreLConditional",
3359     "CompareAndSwapI", "CompareAndSwapL", "CompareAndSwapP", "CompareAndSwapN",
3360     "StoreCM",
3361     "ClearArray"
3362   };
3363   int cnt = sizeof(needs_ideal_memory_list)/sizeof(char*);
3364   if( strcmp(_opType,"PrefetchRead")==0 || strcmp(_opType,"PrefetchWrite")==0 )
3365     return 1;
3366   if( _lChild ) {
3367     const char *opType = _lChild->_opType;
3368     for( int i=0; i<cnt; i++ )
3369       if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3370         return 1;
3371     if( _lChild->needs_ideal_memory_edge(globals) )
3372       return 1;
3373   }
3374   if( _rChild ) {
3375     const char *opType = _rChild->_opType;
3376     for( int i=0; i<cnt; i++ )
3377       if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3378         return 1;
3379     if( _rChild->needs_ideal_memory_edge(globals) )
3380       return 1;
3381   }
3382 
3383   return 0;
3384 }
3385 
3386 // TRUE if defines a derived oop, and so needs a base oop edge present
3387 // post-matching.
3388 int MatchNode::needs_base_oop_edge() const {
3389   if( !strcmp(_opType,"AddP") ) return 1;
3390   if( strcmp(_opType,"Set") ) return 0;
3391   return !strcmp(_rChild->_opType,"AddP");
3392 }
3393 
3394 int InstructForm::needs_base_oop_edge(FormDict &globals) const {
3395   if( is_simple_chain_rule(globals) ) {
3396     const char *src = _matrule->_rChild->_opType;
3397     OperandForm *src_op = globals[src]->is_operand();
3398     assert( src_op, "Not operand class of chain rule" );
3399     return src_op->_matrule ? src_op->_matrule->needs_base_oop_edge() : 0;
3400   }                             // Else check instruction
3401 
3402   return _matrule ? _matrule->needs_base_oop_edge() : 0;
3403 }
3404 
3405 
3406 //-------------------------cisc spilling methods-------------------------------
3407 // helper routines and methods for detecting cisc-spilling instructions
3408 //-------------------------cisc_spill_merge------------------------------------
3409 int MatchNode::cisc_spill_merge(int left_spillable, int right_spillable) {
3410   int cisc_spillable  = Maybe_cisc_spillable;
3411 
3412   // Combine results of left and right checks
3413   if( (left_spillable == Maybe_cisc_spillable) && (right_spillable == Maybe_cisc_spillable) ) {
3414     // neither side is spillable, nor prevents cisc spilling
3415     cisc_spillable = Maybe_cisc_spillable;
3416   }
3417   else if( (left_spillable == Maybe_cisc_spillable) && (right_spillable > Maybe_cisc_spillable) ) {
3418     // right side is spillable
3419     cisc_spillable = right_spillable;
3420   }
3421   else if( (right_spillable == Maybe_cisc_spillable) && (left_spillable > Maybe_cisc_spillable) ) {
3422     // left side is spillable
3423     cisc_spillable = left_spillable;
3424   }
3425   else if( (left_spillable == Not_cisc_spillable) || (right_spillable == Not_cisc_spillable) ) {
3426     // left or right prevents cisc spilling this instruction
3427     cisc_spillable = Not_cisc_spillable;
3428   }
3429   else {
3430     // Only allow one to spill
3431     cisc_spillable = Not_cisc_spillable;
3432   }
3433 
3434   return cisc_spillable;
3435 }
3436 
3437 //-------------------------root_ops_match--------------------------------------
3438 bool static root_ops_match(FormDict &globals, const char *op1, const char *op2) {
3439   // Base Case: check that the current operands/operations match
3440   assert( op1, "Must have op's name");
3441   assert( op2, "Must have op's name");
3442   const Form *form1 = globals[op1];
3443   const Form *form2 = globals[op2];
3444 
3445   return (form1 == form2);
3446 }
3447 
3448 //-------------------------cisc_spill_match_node-------------------------------
3449 // Recursively check two MatchRules for legal conversion via cisc-spilling
3450 int MatchNode::cisc_spill_match(FormDict& globals, RegisterForm* registers, MatchNode* mRule2, const char* &operand, const char* &reg_type) {
3451   int cisc_spillable  = Maybe_cisc_spillable;
3452   int left_spillable  = Maybe_cisc_spillable;
3453   int right_spillable = Maybe_cisc_spillable;
3454 
3455   // Check that each has same number of operands at this level
3456   if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) )
3457     return Not_cisc_spillable;
3458 
3459   // Base Case: check that the current operands/operations match
3460   // or are CISC spillable
3461   assert( _opType, "Must have _opType");
3462   assert( mRule2->_opType, "Must have _opType");
3463   const Form *form  = globals[_opType];
3464   const Form *form2 = globals[mRule2->_opType];
3465   if( form == form2 ) {
3466     cisc_spillable = Maybe_cisc_spillable;
3467   } else {
3468     const InstructForm *form2_inst = form2 ? form2->is_instruction() : NULL;
3469     const char *name_left  = mRule2->_lChild ? mRule2->_lChild->_opType : NULL;
3470     const char *name_right = mRule2->_rChild ? mRule2->_rChild->_opType : NULL;
3471     DataType data_type = Form::none;
3472     if (form->is_operand()) {
3473       // Make sure the loadX matches the type of the reg
3474       data_type = form->ideal_to_Reg_type(form->is_operand()->ideal_type(globals));
3475     }
3476     // Detect reg vs (loadX memory)
3477     if( form->is_cisc_reg(globals)
3478         && form2_inst
3479         && data_type != Form::none
3480         && (is_load_from_memory(mRule2->_opType) == data_type) // reg vs. (load memory)
3481         && (name_left != NULL)       // NOT (load)
3482         && (name_right == NULL) ) {  // NOT (load memory foo)
3483       const Form *form2_left = name_left ? globals[name_left] : NULL;
3484       if( form2_left && form2_left->is_cisc_mem(globals) ) {
3485         cisc_spillable = Is_cisc_spillable;
3486         operand        = _name;
3487         reg_type       = _result;
3488         return Is_cisc_spillable;
3489       } else {
3490         cisc_spillable = Not_cisc_spillable;
3491       }
3492     }
3493     // Detect reg vs memory
3494     else if( form->is_cisc_reg(globals) && form2->is_cisc_mem(globals) ) {
3495       cisc_spillable = Is_cisc_spillable;
3496       operand        = _name;
3497       reg_type       = _result;
3498       return Is_cisc_spillable;
3499     } else {
3500       cisc_spillable = Not_cisc_spillable;
3501     }
3502   }
3503 
3504   // If cisc is still possible, check rest of tree
3505   if( cisc_spillable == Maybe_cisc_spillable ) {
3506     // Check that each has same number of operands at this level
3507     if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3508 
3509     // Check left operands
3510     if( (_lChild == NULL) && (mRule2->_lChild == NULL) ) {
3511       left_spillable = Maybe_cisc_spillable;
3512     } else {
3513       left_spillable = _lChild->cisc_spill_match(globals, registers, mRule2->_lChild, operand, reg_type);
3514     }
3515 
3516     // Check right operands
3517     if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3518       right_spillable =  Maybe_cisc_spillable;
3519     } else {
3520       right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3521     }
3522 
3523     // Combine results of left and right checks
3524     cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3525   }
3526 
3527   return cisc_spillable;
3528 }
3529 
3530 //---------------------------cisc_spill_match_rule------------------------------
3531 // Recursively check two MatchRules for legal conversion via cisc-spilling
3532 // This method handles the root of Match tree,
3533 // general recursive checks done in MatchNode
3534 int  MatchRule::matchrule_cisc_spill_match(FormDict& globals, RegisterForm* registers,
3535                                            MatchRule* mRule2, const char* &operand,
3536                                            const char* &reg_type) {
3537   int cisc_spillable  = Maybe_cisc_spillable;
3538   int left_spillable  = Maybe_cisc_spillable;
3539   int right_spillable = Maybe_cisc_spillable;
3540 
3541   // Check that each sets a result
3542   if( !(sets_result() && mRule2->sets_result()) ) return Not_cisc_spillable;
3543   // Check that each has same number of operands at this level
3544   if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3545 
3546   // Check left operands: at root, must be target of 'Set'
3547   if( (_lChild == NULL) || (mRule2->_lChild == NULL) ) {
3548     left_spillable = Not_cisc_spillable;
3549   } else {
3550     // Do not support cisc-spilling instruction's target location
3551     if( root_ops_match(globals, _lChild->_opType, mRule2->_lChild->_opType) ) {
3552       left_spillable = Maybe_cisc_spillable;
3553     } else {
3554       left_spillable = Not_cisc_spillable;
3555     }
3556   }
3557 
3558   // Check right operands: recursive walk to identify reg->mem operand
3559   if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3560     right_spillable =  Maybe_cisc_spillable;
3561   } else {
3562     right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3563   }
3564 
3565   // Combine results of left and right checks
3566   cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3567 
3568   return cisc_spillable;
3569 }
3570 
3571 //----------------------------- equivalent ------------------------------------
3572 // Recursively check to see if two match rules are equivalent.
3573 // This rule handles the root.
3574 bool MatchRule::equivalent(FormDict &globals, MatchNode *mRule2) {
3575   // Check that each sets a result
3576   if (sets_result() != mRule2->sets_result()) {
3577     return false;
3578   }
3579 
3580   // Check that the current operands/operations match
3581   assert( _opType, "Must have _opType");
3582   assert( mRule2->_opType, "Must have _opType");
3583   const Form *form  = globals[_opType];
3584   const Form *form2 = globals[mRule2->_opType];
3585   if( form != form2 ) {
3586     return false;
3587   }
3588 
3589   if (_lChild ) {
3590     if( !_lChild->equivalent(globals, mRule2->_lChild) )
3591       return false;
3592   } else if (mRule2->_lChild) {
3593     return false; // I have NULL left child, mRule2 has non-NULL left child.
3594   }
3595 
3596   if (_rChild ) {
3597     if( !_rChild->equivalent(globals, mRule2->_rChild) )
3598       return false;
3599   } else if (mRule2->_rChild) {
3600     return false; // I have NULL right child, mRule2 has non-NULL right child.
3601   }
3602 
3603   // We've made it through the gauntlet.
3604   return true;
3605 }
3606 
3607 //----------------------------- equivalent ------------------------------------
3608 // Recursively check to see if two match rules are equivalent.
3609 // This rule handles the operands.
3610 bool MatchNode::equivalent(FormDict &globals, MatchNode *mNode2) {
3611   if( !mNode2 )
3612     return false;
3613 
3614   // Check that the current operands/operations match
3615   assert( _opType, "Must have _opType");
3616   assert( mNode2->_opType, "Must have _opType");
3617   const Form *form  = globals[_opType];
3618   const Form *form2 = globals[mNode2->_opType];
3619   if( form != form2 ) {
3620     return false;
3621   }
3622 
3623   // Check that their children also match
3624   if (_lChild ) {
3625     if( !_lChild->equivalent(globals, mNode2->_lChild) )
3626       return false;
3627   } else if (mNode2->_lChild) {
3628     return false; // I have NULL left child, mNode2 has non-NULL left child.
3629   }
3630 
3631   if (_rChild ) {
3632     if( !_rChild->equivalent(globals, mNode2->_rChild) )
3633       return false;
3634   } else if (mNode2->_rChild) {
3635     return false; // I have NULL right child, mNode2 has non-NULL right child.
3636   }
3637 
3638   // We've made it through the gauntlet.
3639   return true;
3640 }
3641 
3642 //-------------------------- has_commutative_op -------------------------------
3643 // Recursively check for commutative operations with subtree operands
3644 // which could be swapped.
3645 void MatchNode::count_commutative_op(int& count) {
3646   static const char *commut_op_list[] = {
3647     "AddI","AddL","AddF","AddD",
3648     "AndI","AndL",
3649     "MaxI","MinI",
3650     "MulI","MulL","MulF","MulD",
3651     "OrI" ,"OrL" ,
3652     "XorI","XorL"
3653   };
3654   int cnt = sizeof(commut_op_list)/sizeof(char*);
3655 
3656   if( _lChild && _rChild && (_lChild->_lChild || _rChild->_lChild) ) {
3657     // Don't swap if right operand is an immediate constant.
3658     bool is_const = false;
3659     if( _rChild->_lChild == NULL && _rChild->_rChild == NULL ) {
3660       FormDict &globals = _AD.globalNames();
3661       const Form *form = globals[_rChild->_opType];
3662       if ( form ) {
3663         OperandForm  *oper = form->is_operand();
3664         if( oper && oper->interface_type(globals) == Form::constant_interface )
3665           is_const = true;
3666       }
3667     }
3668     if( !is_const ) {
3669       for( int i=0; i<cnt; i++ ) {
3670         if( strcmp(_opType, commut_op_list[i]) == 0 ) {
3671           count++;
3672           _commutative_id = count; // id should be > 0
3673           break;
3674         }
3675       }
3676     }
3677   }
3678   if( _lChild )
3679     _lChild->count_commutative_op(count);
3680   if( _rChild )
3681     _rChild->count_commutative_op(count);
3682 }
3683 
3684 //-------------------------- swap_commutative_op ------------------------------
3685 // Recursively swap specified commutative operation with subtree operands.
3686 void MatchNode::swap_commutative_op(bool atroot, int id) {
3687   if( _commutative_id == id ) { // id should be > 0
3688     assert(_lChild && _rChild && (_lChild->_lChild || _rChild->_lChild ),
3689             "not swappable operation");
3690     MatchNode* tmp = _lChild;
3691     _lChild = _rChild;
3692     _rChild = tmp;
3693     // Don't exit here since we need to build internalop.
3694   }
3695 
3696   bool is_set = ( strcmp(_opType, "Set") == 0 );
3697   if( _lChild )
3698     _lChild->swap_commutative_op(is_set, id);
3699   if( _rChild )
3700     _rChild->swap_commutative_op(is_set, id);
3701 
3702   // If not the root, reduce this subtree to an internal operand
3703   if( !atroot && (_lChild || _rChild) ) {
3704     build_internalop();
3705   }
3706 }
3707 
3708 //-------------------------- swap_commutative_op ------------------------------
3709 // Recursively swap specified commutative operation with subtree operands.
3710 void MatchRule::matchrule_swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt) {
3711   assert(match_rules_cnt < 100," too many match rule clones");
3712   // Clone
3713   MatchRule* clone = new MatchRule(_AD, this);
3714   // Swap operands of commutative operation
3715   ((MatchNode*)clone)->swap_commutative_op(true, count);
3716   char* buf = (char*) malloc(strlen(instr_ident) + 4);
3717   sprintf(buf, "%s_%d", instr_ident, match_rules_cnt++);
3718   clone->_result = buf;
3719 
3720   clone->_next = this->_next;
3721   this-> _next = clone;
3722   if( (--count) > 0 ) {
3723     this-> matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
3724     clone->matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
3725   }
3726 }
3727 
3728 //------------------------------MatchRule--------------------------------------
3729 MatchRule::MatchRule(ArchDesc &ad)
3730   : MatchNode(ad), _depth(0), _construct(NULL), _numchilds(0) {
3731     _next = NULL;
3732 }
3733 
3734 MatchRule::MatchRule(ArchDesc &ad, MatchRule* mRule)
3735   : MatchNode(ad, *mRule, 0), _depth(mRule->_depth),
3736     _construct(mRule->_construct), _numchilds(mRule->_numchilds) {
3737     _next = NULL;
3738 }
3739 
3740 MatchRule::MatchRule(ArchDesc &ad, MatchNode* mroot, int depth, char *cnstr,
3741                      int numleaves)
3742   : MatchNode(ad,*mroot), _depth(depth), _construct(cnstr),
3743     _numchilds(0) {
3744       _next = NULL;
3745       mroot->_lChild = NULL;
3746       mroot->_rChild = NULL;
3747       delete mroot;
3748       _numleaves = numleaves;
3749       _numchilds = (_lChild ? 1 : 0) + (_rChild ? 1 : 0);
3750 }
3751 MatchRule::~MatchRule() {
3752 }
3753 
3754 // Recursive call collecting info on top-level operands, not transitive.
3755 // Implementation does not modify state of internal structures.
3756 void MatchRule::append_components(FormDict& locals, ComponentList& components, bool def_flag) const {
3757   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3758 
3759   MatchNode::append_components(locals, components,
3760                                false /* not necessarily a def */);
3761 }
3762 
3763 // Recursive call on all operands' match rules in my match rule.
3764 // Implementation does not modify state of internal structures  since they
3765 // can be shared.
3766 // The MatchNode that is called first treats its
3767 bool MatchRule::base_operand(uint &position0, FormDict &globals,
3768                              const char *&result, const char * &name,
3769                              const char * &opType)const{
3770   uint position = position0;
3771 
3772   return (MatchNode::base_operand( position, globals, result, name, opType));
3773 }
3774 
3775 
3776 bool MatchRule::is_base_register(FormDict &globals) const {
3777   uint   position = 1;
3778   const char  *result   = NULL;
3779   const char  *name     = NULL;
3780   const char  *opType   = NULL;
3781   if (!base_operand(position, globals, result, name, opType)) {
3782     position = 0;
3783     if( base_operand(position, globals, result, name, opType) &&
3784         (strcmp(opType,"RegI")==0 ||
3785          strcmp(opType,"RegP")==0 ||
3786          strcmp(opType,"RegN")==0 ||
3787          strcmp(opType,"RegL")==0 ||
3788          strcmp(opType,"RegF")==0 ||
3789          strcmp(opType,"RegD")==0 ||
3790          strcmp(opType,"Reg" )==0) ) {
3791       return 1;
3792     }
3793   }
3794   return 0;
3795 }
3796 
3797 Form::DataType MatchRule::is_base_constant(FormDict &globals) const {
3798   uint         position = 1;
3799   const char  *result   = NULL;
3800   const char  *name     = NULL;
3801   const char  *opType   = NULL;
3802   if (!base_operand(position, globals, result, name, opType)) {
3803     position = 0;
3804     if (base_operand(position, globals, result, name, opType)) {
3805       return ideal_to_const_type(opType);
3806     }
3807   }
3808   return Form::none;
3809 }
3810 
3811 bool MatchRule::is_chain_rule(FormDict &globals) const {
3812 
3813   // Check for chain rule, and do not generate a match list for it
3814   if ((_lChild == NULL) && (_rChild == NULL) ) {
3815     const Form *form = globals[_opType];
3816     // If this is ideal, then it is a base match, not a chain rule.
3817     if ( form && form->is_operand() && (!form->ideal_only())) {
3818       return true;
3819     }
3820   }
3821   // Check for "Set" form of chain rule, and do not generate a match list
3822   if (_rChild) {
3823     const char *rch = _rChild->_opType;
3824     const Form *form = globals[rch];
3825     if ((!strcmp(_opType,"Set") &&
3826          ((form) && form->is_operand()))) {
3827       return true;
3828     }
3829   }
3830   return false;
3831 }
3832 
3833 int MatchRule::is_ideal_copy() const {
3834   if( _rChild ) {
3835     const char  *opType = _rChild->_opType;
3836 #if 1
3837     if( strcmp(opType,"CastIP")==0 )
3838       return 1;
3839 #else
3840     if( strcmp(opType,"CastII")==0 )
3841       return 1;
3842     // Do not treat *CastPP this way, because it
3843     // may transfer a raw pointer to an oop.
3844     // If the register allocator were to coalesce this
3845     // into a single LRG, the GC maps would be incorrect.
3846     //if( strcmp(opType,"CastPP")==0 )
3847     //  return 1;
3848     //if( strcmp(opType,"CheckCastPP")==0 )
3849     //  return 1;
3850     //
3851     // Do not treat CastX2P or CastP2X this way, because
3852     // raw pointers and int types are treated differently
3853     // when saving local & stack info for safepoints in
3854     // Output().
3855     //if( strcmp(opType,"CastX2P")==0 )
3856     //  return 1;
3857     //if( strcmp(opType,"CastP2X")==0 )
3858     //  return 1;
3859 #endif
3860   }
3861   if( is_chain_rule(_AD.globalNames()) &&
3862       _lChild && strncmp(_lChild->_opType,"stackSlot",9)==0 )
3863     return 1;
3864   return 0;
3865 }
3866 
3867 
3868 int MatchRule::is_expensive() const {
3869   if( _rChild ) {
3870     const char  *opType = _rChild->_opType;
3871     if( strcmp(opType,"AtanD")==0 ||
3872         strcmp(opType,"CosD")==0 ||
3873         strcmp(opType,"DivD")==0 ||
3874         strcmp(opType,"DivF")==0 ||
3875         strcmp(opType,"DivI")==0 ||
3876         strcmp(opType,"ExpD")==0 ||
3877         strcmp(opType,"LogD")==0 ||
3878         strcmp(opType,"Log10D")==0 ||
3879         strcmp(opType,"ModD")==0 ||
3880         strcmp(opType,"ModF")==0 ||
3881         strcmp(opType,"ModI")==0 ||
3882         strcmp(opType,"PowD")==0 ||
3883         strcmp(opType,"SinD")==0 ||
3884         strcmp(opType,"SqrtD")==0 ||
3885         strcmp(opType,"TanD")==0 ||
3886         strcmp(opType,"ConvD2F")==0 ||
3887         strcmp(opType,"ConvD2I")==0 ||
3888         strcmp(opType,"ConvD2L")==0 ||
3889         strcmp(opType,"ConvF2D")==0 ||
3890         strcmp(opType,"ConvF2I")==0 ||
3891         strcmp(opType,"ConvF2L")==0 ||
3892         strcmp(opType,"ConvI2D")==0 ||
3893         strcmp(opType,"ConvI2F")==0 ||
3894         strcmp(opType,"ConvI2L")==0 ||
3895         strcmp(opType,"ConvL2D")==0 ||
3896         strcmp(opType,"ConvL2F")==0 ||
3897         strcmp(opType,"ConvL2I")==0 ||
3898         strcmp(opType,"DecodeN")==0 ||
3899         strcmp(opType,"EncodeP")==0 ||
3900         strcmp(opType,"RoundDouble")==0 ||
3901         strcmp(opType,"RoundFloat")==0 ||
3902         strcmp(opType,"ReverseBytesI")==0 ||
3903         strcmp(opType,"ReverseBytesL")==0 ||
3904         strcmp(opType,"ReverseBytesUS")==0 ||
3905         strcmp(opType,"ReverseBytesS")==0 ||
3906         strcmp(opType,"Replicate16B")==0 ||
3907         strcmp(opType,"Replicate8B")==0 ||
3908         strcmp(opType,"Replicate4B")==0 ||
3909         strcmp(opType,"Replicate8C")==0 ||
3910         strcmp(opType,"Replicate4C")==0 ||
3911         strcmp(opType,"Replicate8S")==0 ||
3912         strcmp(opType,"Replicate4S")==0 ||
3913         strcmp(opType,"Replicate4I")==0 ||
3914         strcmp(opType,"Replicate2I")==0 ||
3915         strcmp(opType,"Replicate2L")==0 ||
3916         strcmp(opType,"Replicate4F")==0 ||
3917         strcmp(opType,"Replicate2F")==0 ||
3918         strcmp(opType,"Replicate2D")==0 ||
3919         0 /* 0 to line up columns nicely */ )
3920       return 1;
3921   }
3922   return 0;
3923 }
3924 
3925 bool MatchRule::is_ideal_if() const {
3926   if( !_opType ) return false;
3927   return
3928     !strcmp(_opType,"If"            ) ||
3929     !strcmp(_opType,"CountedLoopEnd");
3930 }
3931 
3932 bool MatchRule::is_ideal_fastlock() const {
3933   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3934     return (strcmp(_rChild->_opType,"FastLock") == 0);
3935   }
3936   return false;
3937 }
3938 
3939 bool MatchRule::is_ideal_membar() const {
3940   if( !_opType ) return false;
3941   return
3942     !strcmp(_opType,"MemBarAcquire"  ) ||
3943     !strcmp(_opType,"MemBarRelease"  ) ||
3944     !strcmp(_opType,"MemBarVolatile" ) ||
3945     !strcmp(_opType,"MemBarCPUOrder" ) ;
3946 }
3947 
3948 bool MatchRule::is_ideal_loadPC() const {
3949   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3950     return (strcmp(_rChild->_opType,"LoadPC") == 0);
3951   }
3952   return false;
3953 }
3954 
3955 bool MatchRule::is_ideal_box() const {
3956   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3957     return (strcmp(_rChild->_opType,"Box") == 0);
3958   }
3959   return false;
3960 }
3961 
3962 bool MatchRule::is_ideal_goto() const {
3963   bool   ideal_goto = false;
3964 
3965   if( _opType && (strcmp(_opType,"Goto") == 0) ) {
3966     ideal_goto = true;
3967   }
3968   return ideal_goto;
3969 }
3970 
3971 bool MatchRule::is_ideal_jump() const {
3972   if( _opType ) {
3973     if( !strcmp(_opType,"Jump") )
3974       return true;
3975   }
3976   return false;
3977 }
3978 
3979 bool MatchRule::is_ideal_bool() const {
3980   if( _opType ) {
3981     if( !strcmp(_opType,"Bool") )
3982       return true;
3983   }
3984   return false;
3985 }
3986 
3987 
3988 Form::DataType MatchRule::is_ideal_load() const {
3989   Form::DataType ideal_load = Form::none;
3990 
3991   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3992     const char *opType = _rChild->_opType;
3993     ideal_load = is_load_from_memory(opType);
3994   }
3995 
3996   return ideal_load;
3997 }
3998 
3999 
4000 bool MatchRule::skip_antidep_check() const {
4001   // Some loads operate on what is effectively immutable memory so we
4002   // should skip the anti dep computations.  For some of these nodes
4003   // the rewritable field keeps the anti dep logic from triggering but
4004   // for certain kinds of LoadKlass it does not since they are
4005   // actually reading memory which could be rewritten by the runtime,
4006   // though never by generated code.  This disables it uniformly for
4007   // the nodes that behave like this: LoadKlass, LoadNKlass and
4008   // LoadRange.
4009   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4010     const char *opType = _rChild->_opType;
4011     if (strcmp("LoadKlass", opType) == 0 ||
4012         strcmp("LoadNKlass", opType) == 0 ||
4013         strcmp("LoadRange", opType) == 0) {
4014       return true;
4015     }
4016   }
4017 
4018   return false;
4019 }
4020 
4021 
4022 Form::DataType MatchRule::is_ideal_store() const {
4023   Form::DataType ideal_store = Form::none;
4024 
4025   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4026     const char *opType = _rChild->_opType;
4027     ideal_store = is_store_to_memory(opType);
4028   }
4029 
4030   return ideal_store;
4031 }
4032 
4033 
4034 void MatchRule::dump() {
4035   output(stderr);
4036 }
4037 
4038 void MatchRule::output(FILE *fp) {
4039   fprintf(fp,"MatchRule: ( %s",_name);
4040   if (_lChild) _lChild->output(fp);
4041   if (_rChild) _rChild->output(fp);
4042   fprintf(fp," )\n");
4043   fprintf(fp,"   nesting depth = %d\n", _depth);
4044   if (_result) fprintf(fp,"   Result Type = %s", _result);
4045   fprintf(fp,"\n");
4046 }
4047 
4048 //------------------------------Attribute--------------------------------------
4049 Attribute::Attribute(char *id, char* val, int type)
4050   : _ident(id), _val(val), _atype(type) {
4051 }
4052 Attribute::~Attribute() {
4053 }
4054 
4055 int Attribute::int_val(ArchDesc &ad) {
4056   // Make sure it is an integer constant:
4057   int result = 0;
4058   if (!_val || !ADLParser::is_int_token(_val, result)) {
4059     ad.syntax_err(0, "Attribute %s must have an integer value: %s",
4060                   _ident, _val ? _val : "");
4061   }
4062   return result;
4063 }
4064 
4065 void Attribute::dump() {
4066   output(stderr);
4067 } // Debug printer
4068 
4069 // Write to output files
4070 void Attribute::output(FILE *fp) {
4071   fprintf(fp,"Attribute: %s  %s\n", (_ident?_ident:""), (_val?_val:""));
4072 }
4073 
4074 //------------------------------FormatRule----------------------------------
4075 FormatRule::FormatRule(char *temp)
4076   : _temp(temp) {
4077 }
4078 FormatRule::~FormatRule() {
4079 }
4080 
4081 void FormatRule::dump() {
4082   output(stderr);
4083 }
4084 
4085 // Write to output files
4086 void FormatRule::output(FILE *fp) {
4087   fprintf(fp,"\nFormat Rule: \n%s", (_temp?_temp:""));
4088   fprintf(fp,"\n");
4089 }