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