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