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