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