1 //
   2 // Copyright (c) 1997, 2013, 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 
  26 // archDesc.cpp - Internal format for architecture definition
  27 #include "adlc.hpp"
  28 
  29 static FILE *errfile = stderr;
  30 
  31 //--------------------------- utility functions -----------------------------
  32 inline char toUpper(char lower) {
  33   return (('a' <= lower && lower <= 'z') ? ((char) (lower + ('A'-'a'))) : lower);
  34 }
  35 char *toUpper(const char *str) {
  36   char *upper  = new char[strlen(str)+1];
  37   char *result = upper;
  38   const char *end    = str + strlen(str);
  39   for (; str < end; ++str, ++upper) {
  40     *upper = toUpper(*str);
  41   }
  42   *upper = '\0';
  43   return result;
  44 }
  45 
  46 // Utilities to characterize effect statements
  47 static bool is_def(int usedef) {
  48   switch(usedef) {
  49   case Component::DEF:
  50   case Component::USE_DEF: return true; break;
  51   }
  52   return false;
  53 }
  54 
  55 static bool is_use(int usedef) {
  56   switch(usedef) {
  57   case Component::USE:
  58   case Component::USE_DEF:
  59   case Component::USE_KILL: return true; break;
  60   }
  61   return false;
  62 }
  63 
  64 static bool is_kill(int usedef) {
  65   switch(usedef) {
  66   case Component::KILL:
  67   case Component::USE_KILL: return true; break;
  68   }
  69   return false;
  70 }
  71 
  72 //---------------------------ChainList Methods-------------------------------
  73 ChainList::ChainList() {
  74 }
  75 
  76 void ChainList::insert(const char *name, const char *cost, const char *rule) {
  77   _name.addName(name);
  78   _cost.addName(cost);
  79   _rule.addName(rule);
  80 }
  81 
  82 bool ChainList::search(const char *name) {
  83   return _name.search(name);
  84 }
  85 
  86 void ChainList::reset() {
  87   _name.reset();
  88   _cost.reset();
  89   _rule.reset();
  90 }
  91 
  92 bool ChainList::iter(const char * &name, const char * &cost, const char * &rule) {
  93   bool        notDone = false;
  94   const char *n       = _name.iter();
  95   const char *c       = _cost.iter();
  96   const char *r       = _rule.iter();
  97 
  98   if (n && c && r) {
  99     notDone = true;
 100     name = n;
 101     cost = c;
 102     rule = r;
 103   }
 104 
 105   return notDone;
 106 }
 107 
 108 void ChainList::dump() {
 109   output(stderr);
 110 }
 111 
 112 void ChainList::output(FILE *fp) {
 113   fprintf(fp, "\nChain Rules: output resets iterator\n");
 114   const char   *cost  = NULL;
 115   const char   *name  = NULL;
 116   const char   *rule  = NULL;
 117   bool   chains_exist = false;
 118   for(reset(); (iter(name,cost,rule)) == true; ) {
 119     fprintf(fp, "Chain to <%s> at cost #%s using %s_rule\n",name, cost ? cost : "0", rule);
 120     //  // Check for transitive chain rules
 121     //  Form *form = (Form *)_globalNames[rule];
 122     //  if (form->is_instruction()) {
 123     //    // chain_rule(fp, indent, name, cost, rule);
 124     //    chain_rule(fp, indent, name, cost, rule);
 125     //  }
 126   }
 127   reset();
 128   if( ! chains_exist ) {
 129     fprintf(fp, "No entries in this ChainList\n");
 130   }
 131 }
 132 
 133 
 134 //---------------------------MatchList Methods-------------------------------
 135 bool MatchList::search(const char *opc, const char *res, const char *lch,
 136                        const char *rch, Predicate *pr) {
 137   bool tmp = false;
 138   if ((res == _resultStr) || (res && _resultStr && !strcmp(res, _resultStr))) {
 139     if ((lch == _lchild) || (lch && _lchild && !strcmp(lch, _lchild))) {
 140       if ((rch == _rchild) || (rch && _rchild && !strcmp(rch, _rchild))) {
 141         char * predStr = get_pred();
 142         char * prStr = pr?pr->_pred:NULL;
 143         if (ADLParser::equivalent_expressions(prStr, predStr)) {
 144           return true;
 145         }
 146       }
 147     }
 148   }
 149   if (_next) {
 150     tmp = _next->search(opc, res, lch, rch, pr);
 151   }
 152   return tmp;
 153 }
 154 
 155 
 156 void MatchList::dump() {
 157   output(stderr);
 158 }
 159 
 160 void MatchList::output(FILE *fp) {
 161   fprintf(fp, "\nMatchList output is Unimplemented();\n");
 162 }
 163 
 164 
 165 //---------------------------ArchDesc Constructor and Destructor-------------
 166 
 167 ArchDesc::ArchDesc()
 168   : _globalNames(cmpstr,hashstr, Form::arena),
 169     _globalDefs(cmpstr,hashstr, Form::arena),
 170     _preproc_table(cmpstr,hashstr, Form::arena),
 171     _idealIndex(cmpstr,hashstr, Form::arena),
 172     _internalOps(cmpstr,hashstr, Form::arena),
 173     _internalMatch(cmpstr,hashstr, Form::arena),
 174     _chainRules(cmpstr,hashstr, Form::arena),
 175     _cisc_spill_operand(NULL),
 176     _needs_clone_jvms(false) {
 177 
 178       // Initialize the opcode to MatchList table with NULLs
 179       for( int i=0; i<_last_opcode; ++i ) {
 180         _mlistab[i] = NULL;
 181       }
 182 
 183       // Set-up the global tables
 184       initKeywords(_globalNames);    // Initialize the Name Table with keywords
 185 
 186       // Prime user-defined types with predefined types: Set, RegI, RegF, ...
 187       initBaseOpTypes();
 188 
 189       // Initialize flags & counters
 190       _TotalLines        = 0;
 191       _no_output         = 0;
 192       _quiet_mode        = 0;
 193       _disable_warnings  = 0;
 194       _dfa_debug         = 0;
 195       _dfa_small         = 0;
 196       _adl_debug         = 0;
 197       _adlocation_debug  = 0;
 198       _internalOpCounter = 0;
 199       _cisc_spill_debug  = false;
 200       _short_branch_debug = false;
 201 
 202       // Initialize match rule flags
 203       for (int i = 0; i < _last_opcode; i++) {
 204         _has_match_rule[i] = false;
 205       }
 206 
 207       // Error/Warning Counts
 208       _syntax_errs       = 0;
 209       _semantic_errs     = 0;
 210       _warnings          = 0;
 211       _internal_errs     = 0;
 212 
 213       // Initialize I/O Files
 214       _ADL_file._name = NULL; _ADL_file._fp = NULL;
 215       // Machine dependent output files
 216       _DFA_file._name    = NULL;  _DFA_file._fp = NULL;
 217       _HPP_file._name    = NULL;  _HPP_file._fp = NULL;
 218       _CPP_file._name    = NULL;  _CPP_file._fp = NULL;
 219       _bug_file._name    = "bugs.out";      _bug_file._fp = NULL;
 220 
 221       // Initialize Register & Pipeline Form Pointers
 222       _register = NULL;
 223       _encode = NULL;
 224       _pipeline = NULL;
 225       _frame = NULL;
 226 }
 227 
 228 ArchDesc::~ArchDesc() {
 229   // Clean-up and quit
 230 
 231 }
 232 
 233 //---------------------------ArchDesc methods: Public ----------------------
 234 // Store forms according to type
 235 void ArchDesc::addForm(PreHeaderForm *ptr) { _pre_header.addForm(ptr); };
 236 void ArchDesc::addForm(HeaderForm    *ptr) { _header.addForm(ptr); };
 237 void ArchDesc::addForm(SourceForm    *ptr) { _source.addForm(ptr); };
 238 void ArchDesc::addForm(EncodeForm    *ptr) { _encode = ptr; };
 239 void ArchDesc::addForm(InstructForm  *ptr) { _instructions.addForm(ptr); };
 240 void ArchDesc::addForm(MachNodeForm  *ptr) { _machnodes.addForm(ptr); };
 241 void ArchDesc::addForm(OperandForm   *ptr) { _operands.addForm(ptr); };
 242 void ArchDesc::addForm(OpClassForm   *ptr) { _opclass.addForm(ptr); };
 243 void ArchDesc::addForm(AttributeForm *ptr) { _attributes.addForm(ptr); };
 244 void ArchDesc::addForm(RegisterForm  *ptr) { _register = ptr; };
 245 void ArchDesc::addForm(FrameForm     *ptr) { _frame = ptr; };
 246 void ArchDesc::addForm(PipelineForm  *ptr) { _pipeline = ptr; };
 247 
 248 // Build MatchList array and construct MatchLists
 249 void ArchDesc::generateMatchLists() {
 250   // Call inspection routines to populate array
 251   inspectOperands();
 252   inspectInstructions();
 253 }
 254 
 255 // Build MatchList structures for operands
 256 void ArchDesc::inspectOperands() {
 257 
 258   // Iterate through all operands
 259   _operands.reset();
 260   OperandForm *op;
 261   for( ; (op = (OperandForm*)_operands.iter()) != NULL;) {
 262     // Construct list of top-level operands (components)
 263     op->build_components();
 264 
 265     // Ensure that match field is defined.
 266     if ( op->_matrule == NULL )  continue;
 267 
 268     // Type check match rules
 269     check_optype(op->_matrule);
 270 
 271     // Construct chain rules
 272     build_chain_rule(op);
 273 
 274     MatchRule &mrule = *op->_matrule;
 275     Predicate *pred  =  op->_predicate;
 276 
 277     // Grab the machine type of the operand
 278     const char  *rootOp    = op->_ident;
 279     mrule._machType  = rootOp;
 280 
 281     // Check for special cases
 282     if (strcmp(rootOp,"Universe")==0) continue;
 283     if (strcmp(rootOp,"label")==0) continue;
 284     // !!!!! !!!!!
 285     assert( strcmp(rootOp,"sReg") != 0, "Disable untyped 'sReg'");
 286     if (strcmp(rootOp,"sRegI")==0) continue;
 287     if (strcmp(rootOp,"sRegP")==0) continue;
 288     if (strcmp(rootOp,"sRegF")==0) continue;
 289     if (strcmp(rootOp,"sRegD")==0) continue;
 290     if (strcmp(rootOp,"sRegL")==0) continue;
 291 
 292     // Cost for this match
 293     const char *costStr     = op->cost();
 294     const char *defaultCost =
 295       ((AttributeForm*)_globalNames[AttributeForm::_op_cost])->_attrdef;
 296     const char *cost        =  costStr? costStr : defaultCost;
 297 
 298     // Find result type for match.
 299     const char *result      = op->reduce_result();
 300     bool        has_root    = false;
 301 
 302     // Construct a MatchList for this entry
 303     buildMatchList(op->_matrule, result, rootOp, pred, cost);
 304   }
 305 }
 306 
 307 // Build MatchList structures for instructions
 308 void ArchDesc::inspectInstructions() {
 309 
 310   // Iterate through all instructions
 311   _instructions.reset();
 312   InstructForm *instr;
 313   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
 314     // Construct list of top-level operands (components)
 315     instr->build_components();
 316 
 317     // Ensure that match field is defined.
 318     if ( instr->_matrule == NULL )  continue;
 319 
 320     MatchRule &mrule = *instr->_matrule;
 321     Predicate *pred  =  instr->build_predicate();
 322 
 323     // Grab the machine type of the operand
 324     const char  *rootOp    = instr->_ident;
 325     mrule._machType  = rootOp;
 326 
 327     // Cost for this match
 328     const char *costStr = instr->cost();
 329     const char *defaultCost =
 330       ((AttributeForm*)_globalNames[AttributeForm::_ins_cost])->_attrdef;
 331     const char *cost    =  costStr? costStr : defaultCost;
 332 
 333     // Find result type for match
 334     const char *result  = instr->reduce_result();
 335 
 336     if ( instr->is_ideal_branch() && instr->label_position() == -1 ||
 337         !instr->is_ideal_branch() && instr->label_position() != -1) {
 338       syntax_err(instr->_linenum, "%s: Only branches to a label are supported\n", rootOp);
 339     }
 340 
 341     Attribute *attr = instr->_attribs;
 342     while (attr != NULL) {
 343       if (strcmp(attr->_ident,"ins_short_branch") == 0 &&
 344           attr->int_val(*this) != 0) {
 345         if (!instr->is_ideal_branch() || instr->label_position() == -1) {
 346           syntax_err(instr->_linenum, "%s: Only short branch to a label is supported\n", rootOp);
 347         }
 348         instr->set_short_branch(true);
 349       } else if (strcmp(attr->_ident,"ins_alignment") == 0 &&
 350           attr->int_val(*this) != 0) {
 351         instr->set_alignment(attr->int_val(*this));
 352       }
 353       attr = (Attribute *)attr->_next;
 354     }
 355 
 356     if (!instr->is_short_branch()) {
 357       buildMatchList(instr->_matrule, result, mrule._machType, pred, cost);
 358     }
 359   }
 360 }
 361 
 362 static int setsResult(MatchRule &mrule) {
 363   if (strcmp(mrule._name,"Set") == 0) return 1;
 364   return 0;
 365 }
 366 
 367 const char *ArchDesc::getMatchListIndex(MatchRule &mrule) {
 368   if (setsResult(mrule)) {
 369     // right child
 370     return mrule._rChild->_opType;
 371   } else {
 372     // first entry
 373     return mrule._opType;
 374   }
 375 }
 376 
 377 
 378 //------------------------------result of reduction----------------------------
 379 
 380 
 381 //------------------------------left reduction---------------------------------
 382 // Return the left reduction associated with an internal name
 383 const char *ArchDesc::reduceLeft(char         *internalName) {
 384   const char *left  = NULL;
 385   MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
 386   if (mnode->_lChild) {
 387     mnode = mnode->_lChild;
 388     left = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 389   }
 390   return left;
 391 }
 392 
 393 
 394 //------------------------------right reduction--------------------------------
 395 const char *ArchDesc::reduceRight(char  *internalName) {
 396   const char *right  = NULL;
 397   MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
 398   if (mnode->_rChild) {
 399     mnode = mnode->_rChild;
 400     right = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 401   }
 402   return right;
 403 }
 404 
 405 
 406 //------------------------------check_optype-----------------------------------
 407 void ArchDesc::check_optype(MatchRule *mrule) {
 408   MatchRule *rule = mrule;
 409 
 410   //   !!!!!
 411   //   // Cycle through the list of match rules
 412   //   while(mrule) {
 413   //     // Check for a filled in type field
 414   //     if (mrule->_opType == NULL) {
 415   //     const Form  *form    = operands[_result];
 416   //     OpClassForm *opcForm = form ? form->is_opclass() : NULL;
 417   //     assert(opcForm != NULL, "Match Rule contains invalid operand name.");
 418   //     }
 419   //     char *opType = opcForm->_ident;
 420   //   }
 421 }
 422 
 423 //------------------------------add_chain_rule_entry--------------------------
 424 void ArchDesc::add_chain_rule_entry(const char *src, const char *cost,
 425                                     const char *result) {
 426   // Look-up the operation in chain rule table
 427   ChainList *lst = (ChainList *)_chainRules[src];
 428   if (lst == NULL) {
 429     lst = new ChainList();
 430     _chainRules.Insert(src, lst);
 431   }
 432   if (!lst->search(result)) {
 433     if (cost == NULL) {
 434       cost = ((AttributeForm*)_globalNames[AttributeForm::_op_cost])->_attrdef;
 435     }
 436     lst->insert(result, cost, result);
 437   }
 438 }
 439 
 440 //------------------------------build_chain_rule-------------------------------
 441 void ArchDesc::build_chain_rule(OperandForm *oper) {
 442   MatchRule     *rule;
 443 
 444   // Check for chain rules here
 445   // If this is only a chain rule
 446   if ((oper->_matrule) && (oper->_matrule->_lChild == NULL) &&
 447       (oper->_matrule->_rChild == NULL)) {
 448 
 449     {
 450       const Form *form = _globalNames[oper->_matrule->_opType];
 451       if ((form) && form->is_operand() &&
 452           (form->ideal_only() == false)) {
 453         add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
 454       }
 455     }
 456     // Check for additional chain rules
 457     if (oper->_matrule->_next) {
 458       rule = oper->_matrule;
 459       do {
 460         rule = rule->_next;
 461         // Any extra match rules after the first must be chain rules
 462         const Form *form = _globalNames[rule->_opType];
 463         if ((form) && form->is_operand() &&
 464             (form->ideal_only() == false)) {
 465           add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
 466         }
 467       } while(rule->_next != NULL);
 468     }
 469   }
 470   else if ((oper->_matrule) && (oper->_matrule->_next)) {
 471     // Regardles of whether the first matchrule is a chain rule, check the list
 472     rule = oper->_matrule;
 473     do {
 474       rule = rule->_next;
 475       // Any extra match rules after the first must be chain rules
 476       const Form *form = _globalNames[rule->_opType];
 477       if ((form) && form->is_operand() &&
 478           (form->ideal_only() == false)) {
 479         assert( oper->cost(), "This case expects NULL cost, not default cost");
 480         add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
 481       }
 482     } while(rule->_next != NULL);
 483   }
 484 
 485 }
 486 
 487 //------------------------------buildMatchList---------------------------------
 488 // operands and instructions provide the result
 489 void ArchDesc::buildMatchList(MatchRule *mrule, const char *resultStr,
 490                               const char *rootOp, Predicate *pred,
 491                               const char *cost) {
 492   const char *leftstr, *rightstr;
 493   MatchNode  *mnode;
 494 
 495   leftstr = rightstr = NULL;
 496   // Check for chain rule, and do not generate a match list for it
 497   if ( mrule->is_chain_rule(_globalNames) ) {
 498     return;
 499   }
 500 
 501   // Identify index position among ideal operands
 502   intptr_t    index     = _last_opcode;
 503   const char  *indexStr  = getMatchListIndex(*mrule);
 504   index  = (intptr_t)_idealIndex[indexStr];
 505   if (index == 0) {
 506     fprintf(stderr, "Ideal node missing: %s\n", indexStr);
 507     assert(index != 0, "Failed lookup of ideal node\n");
 508   }
 509 
 510   // Check that this will be placed appropriately in the DFA
 511   if (index >= _last_opcode) {
 512     fprintf(stderr, "Invalid match rule %s <-- ( %s )\n",
 513             resultStr ? resultStr : " ",
 514             rootOp    ? rootOp    : " ");
 515     assert(index < _last_opcode, "Matching item not in ideal graph\n");
 516     return;
 517   }
 518 
 519 
 520   // Walk the MatchRule, generating MatchList entries for each level
 521   // of the rule (each nesting of parentheses)
 522   // Check for "Set"
 523   if (!strcmp(mrule->_opType, "Set")) {
 524     mnode = mrule->_rChild;
 525     buildMList(mnode, rootOp, resultStr, pred, cost);
 526     return;
 527   }
 528   // Build MatchLists for children
 529   // Check each child for an internal operand name, and use that name
 530   // for the parent's matchlist entry if it exists
 531   mnode = mrule->_lChild;
 532   if (mnode) {
 533     buildMList(mnode, NULL, NULL, NULL, NULL);
 534     leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 535   }
 536   mnode = mrule->_rChild;
 537   if (mnode) {
 538     buildMList(mnode, NULL, NULL, NULL, NULL);
 539     rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 540   }
 541   // Search for an identical matchlist entry already on the list
 542   if ((_mlistab[index] == NULL) ||
 543       (_mlistab[index] &&
 544        !_mlistab[index]->search(rootOp, resultStr, leftstr, rightstr, pred))) {
 545     // Place this match rule at front of list
 546     MatchList *mList =
 547       new MatchList(_mlistab[index], pred, cost,
 548                     rootOp, resultStr, leftstr, rightstr);
 549     _mlistab[index] = mList;
 550   }
 551 }
 552 
 553 // Recursive call for construction of match lists
 554 void ArchDesc::buildMList(MatchNode *node, const char *rootOp,
 555                           const char *resultOp, Predicate *pred,
 556                           const char *cost) {
 557   const char *leftstr, *rightstr;
 558   const char *resultop;
 559   const char *opcode;
 560   MatchNode  *mnode;
 561   Form       *form;
 562 
 563   leftstr = rightstr = NULL;
 564   // Do not process leaves of the Match Tree if they are not ideal
 565   if ((node) && (node->_lChild == NULL) && (node->_rChild == NULL) &&
 566       ((form = (Form *)_globalNames[node->_opType]) != NULL) &&
 567       (!form->ideal_only())) {
 568     return;
 569   }
 570 
 571   // Identify index position among ideal operands
 572   intptr_t    index     = _last_opcode;
 573   const char *indexStr  = node ? node->_opType : (char *) " ";
 574   index            = (intptr_t)_idealIndex[indexStr];
 575   if (index == 0) {
 576     fprintf(stderr, "error: operand \"%s\" not found\n", indexStr);
 577     assert(0, "fatal error");
 578   }
 579 
 580   // Build MatchLists for children
 581   // Check each child for an internal operand name, and use that name
 582   // for the parent's matchlist entry if it exists
 583   mnode = node->_lChild;
 584   if (mnode) {
 585     buildMList(mnode, NULL, NULL, NULL, NULL);
 586     leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 587   }
 588   mnode = node->_rChild;
 589   if (mnode) {
 590     buildMList(mnode, NULL, NULL, NULL, NULL);
 591     rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 592   }
 593   // Grab the string for the opcode of this list entry
 594   if (rootOp == NULL) {
 595     opcode = (node->_internalop) ? node->_internalop : node->_opType;
 596   } else {
 597     opcode = rootOp;
 598   }
 599   // Grab the string for the result of this list entry
 600   if (resultOp == NULL) {
 601     resultop = (node->_internalop) ? node->_internalop : node->_opType;
 602   }
 603   else resultop = resultOp;
 604   // Search for an identical matchlist entry already on the list
 605   if ((_mlistab[index] == NULL) || (_mlistab[index] &&
 606                                     !_mlistab[index]->search(opcode, resultop, leftstr, rightstr, pred))) {
 607     // Place this match rule at front of list
 608     MatchList *mList =
 609       new MatchList(_mlistab[index],pred,cost,
 610                     opcode, resultop, leftstr, rightstr);
 611     _mlistab[index] = mList;
 612   }
 613 }
 614 
 615 // Count number of OperandForms defined
 616 int  ArchDesc::operandFormCount() {
 617   // Only interested in ones with non-NULL match rule
 618   int  count = 0; _operands.reset();
 619   OperandForm *cur;
 620   for( ; (cur = (OperandForm*)_operands.iter()) != NULL; ) {
 621     if (cur->_matrule != NULL) ++count;
 622   };
 623   return count;
 624 }
 625 
 626 // Count number of OpClassForms defined
 627 int  ArchDesc::opclassFormCount() {
 628   // Only interested in ones with non-NULL match rule
 629   int  count = 0; _operands.reset();
 630   OpClassForm *cur;
 631   for( ; (cur = (OpClassForm*)_opclass.iter()) != NULL; ) {
 632     ++count;
 633   };
 634   return count;
 635 }
 636 
 637 // Count number of InstructForms defined
 638 int  ArchDesc::instructFormCount() {
 639   // Only interested in ones with non-NULL match rule
 640   int  count = 0; _instructions.reset();
 641   InstructForm *cur;
 642   for( ; (cur = (InstructForm*)_instructions.iter()) != NULL; ) {
 643     if (cur->_matrule != NULL) ++count;
 644   };
 645   return count;
 646 }
 647 
 648 
 649 //------------------------------get_preproc_def--------------------------------
 650 // Return the textual binding for a given CPP flag name.
 651 // Return NULL if there is no binding, or it has been #undef-ed.
 652 char* ArchDesc::get_preproc_def(const char* flag) {
 653   // In case of syntax errors, flag may take the value NULL.
 654   SourceForm* deff = NULL;
 655   if (flag != NULL)
 656     deff = (SourceForm*) _preproc_table[flag];
 657   return (deff == NULL) ? NULL : deff->_code;
 658 }
 659 
 660 
 661 //------------------------------set_preproc_def--------------------------------
 662 // Change or create a textual binding for a given CPP flag name.
 663 // Giving NULL means the flag name is to be #undef-ed.
 664 // In any case, _preproc_list collects all names either #defined or #undef-ed.
 665 void ArchDesc::set_preproc_def(const char* flag, const char* def) {
 666   SourceForm* deff = (SourceForm*) _preproc_table[flag];
 667   if (deff == NULL) {
 668     deff = new SourceForm(NULL);
 669     _preproc_table.Insert(flag, deff);
 670     _preproc_list.addName(flag);   // this supports iteration
 671   }
 672   deff->_code = (char*) def;
 673 }
 674 
 675 
 676 bool ArchDesc::verify() {
 677 
 678   if (_register)
 679     assert( _register->verify(), "Register declarations failed verification");
 680   if (!_quiet_mode)
 681     fprintf(stderr,"\n");
 682   // fprintf(stderr,"---------------------------- Verify Operands ---------------\n");
 683   // _operands.verify();
 684   // fprintf(stderr,"\n");
 685   // fprintf(stderr,"---------------------------- Verify Operand Classes --------\n");
 686   // _opclass.verify();
 687   // fprintf(stderr,"\n");
 688   // fprintf(stderr,"---------------------------- Verify Attributes  ------------\n");
 689   // _attributes.verify();
 690   // fprintf(stderr,"\n");
 691   if (!_quiet_mode)
 692     fprintf(stderr,"---------------------------- Verify Instructions ----------------------------\n");
 693   _instructions.verify();
 694   if (!_quiet_mode)
 695     fprintf(stderr,"\n");
 696   // if ( _encode ) {
 697   //   fprintf(stderr,"---------------------------- Verify Encodings --------------\n");
 698   //   _encode->verify();
 699   // }
 700 
 701   //if (_pipeline) _pipeline->verify();
 702 
 703   return true;
 704 }
 705 
 706 
 707 void ArchDesc::dump() {
 708   _pre_header.dump();
 709   _header.dump();
 710   _source.dump();
 711   if (_register) _register->dump();
 712   fprintf(stderr,"\n");
 713   fprintf(stderr,"------------------ Dump Operands ---------------------\n");
 714   _operands.dump();
 715   fprintf(stderr,"\n");
 716   fprintf(stderr,"------------------ Dump Operand Classes --------------\n");
 717   _opclass.dump();
 718   fprintf(stderr,"\n");
 719   fprintf(stderr,"------------------ Dump Attributes  ------------------\n");
 720   _attributes.dump();
 721   fprintf(stderr,"\n");
 722   fprintf(stderr,"------------------ Dump Instructions -----------------\n");
 723   _instructions.dump();
 724   if ( _encode ) {
 725     fprintf(stderr,"------------------ Dump Encodings --------------------\n");
 726     _encode->dump();
 727   }
 728   if (_pipeline) _pipeline->dump();
 729 }
 730 
 731 
 732 //------------------------------init_keywords----------------------------------
 733 // Load the kewords into the global name table
 734 void ArchDesc::initKeywords(FormDict& names) {
 735   // Insert keyword strings into Global Name Table.  Keywords have a NULL value
 736   // field for quick easy identification when checking identifiers.
 737   names.Insert("instruct", NULL);
 738   names.Insert("operand", NULL);
 739   names.Insert("attribute", NULL);
 740   names.Insert("source", NULL);
 741   names.Insert("register", NULL);
 742   names.Insert("pipeline", NULL);
 743   names.Insert("constraint", NULL);
 744   names.Insert("predicate", NULL);
 745   names.Insert("encode", NULL);
 746   names.Insert("enc_class", NULL);
 747   names.Insert("interface", NULL);
 748   names.Insert("opcode", NULL);
 749   names.Insert("ins_encode", NULL);
 750   names.Insert("match", NULL);
 751   names.Insert("effect", NULL);
 752   names.Insert("expand", NULL);
 753   names.Insert("rewrite", NULL);
 754   names.Insert("reg_def", NULL);
 755   names.Insert("reg_class", NULL);
 756   names.Insert("alloc_class", NULL);
 757   names.Insert("resource", NULL);
 758   names.Insert("pipe_class", NULL);
 759   names.Insert("pipe_desc", NULL);
 760 }
 761 
 762 
 763 //------------------------------internal_err----------------------------------
 764 // Issue a parser error message, and skip to the end of the current line
 765 void ArchDesc::internal_err(const char *fmt, ...) {
 766   va_list args;
 767 
 768   va_start(args, fmt);
 769   _internal_errs += emit_msg(0, INTERNAL_ERR, 0, fmt, args);
 770   va_end(args);
 771 
 772   _no_output = 1;
 773 }
 774 
 775 //------------------------------syntax_err----------------------------------
 776 // Issue a parser error message, and skip to the end of the current line
 777 void ArchDesc::syntax_err(int lineno, const char *fmt, ...) {
 778   va_list args;
 779 
 780   va_start(args, fmt);
 781   _internal_errs += emit_msg(0, SYNERR, lineno, fmt, args);
 782   va_end(args);
 783 
 784   _no_output = 1;
 785 }
 786 
 787 //------------------------------emit_msg---------------------------------------
 788 // Emit a user message, typically a warning or error
 789 int ArchDesc::emit_msg(int quiet, int flag, int line, const char *fmt,
 790     va_list args) {
 791   static int  last_lineno = -1;
 792   int         i;
 793   const char *pref;
 794 
 795   switch(flag) {
 796   case 0: pref = "Warning: "; break;
 797   case 1: pref = "Syntax Error: "; break;
 798   case 2: pref = "Semantic Error: "; break;
 799   case 3: pref = "Internal Error: "; break;
 800   default: assert(0, ""); break;
 801   }
 802 
 803   if (line == last_lineno) return 0;
 804   last_lineno = line;
 805 
 806   if (!quiet) {                        /* no output if in quiet mode         */
 807     i = fprintf(errfile, "%s(%d) ", _ADL_file._name, line);
 808     while (i++ <= 15)  fputc(' ', errfile);
 809     fprintf(errfile, "%-8s:", pref);
 810     vfprintf(errfile, fmt, args);
 811     fprintf(errfile, "\n");
 812     fflush(errfile);
 813   }
 814   return 1;
 815 }
 816 
 817 
 818 // ---------------------------------------------------------------------------
 819 //--------Utilities to build mappings for machine registers ------------------
 820 // ---------------------------------------------------------------------------
 821 
 822 // Construct the name of the register mask.
 823 static const char *getRegMask(const char *reg_class_name) {
 824   if( reg_class_name == NULL ) return "RegMask::Empty";
 825 
 826   if (strcmp(reg_class_name,"Universe")==0) {
 827     return "RegMask::Empty";
 828   } else if (strcmp(reg_class_name,"stack_slots")==0) {
 829     return "(Compile::current()->FIRST_STACK_mask())";
 830   } else {
 831     char       *rc_name = toUpper(reg_class_name);
 832     const char *mask    = "_mask";
 833     int         length  = (int)strlen(rc_name) + (int)strlen(mask) + 5;
 834     char       *regMask = new char[length];
 835     sprintf(regMask,"%s%s()", rc_name, mask);
 836     delete[] rc_name;
 837     return regMask;
 838   }
 839 }
 840 
 841 // Convert a register class name to its register mask.
 842 const char *ArchDesc::reg_class_to_reg_mask(const char *rc_name) {
 843   const char *reg_mask = "RegMask::Empty";
 844 
 845   if( _register ) {
 846     RegClass *reg_class  = _register->getRegClass(rc_name);
 847     if (reg_class == NULL) {
 848       syntax_err(0, "Use of an undefined register class %s", rc_name);
 849       return reg_mask;
 850     }
 851 
 852     // Construct the name of the register mask.
 853     reg_mask = getRegMask(rc_name);
 854   }
 855 
 856   return reg_mask;
 857 }
 858 
 859 
 860 // Obtain the name of the RegMask for an OperandForm
 861 const char *ArchDesc::reg_mask(OperandForm  &opForm) {
 862   const char *regMask      = "RegMask::Empty";
 863 
 864   // Check constraints on result's register class
 865   const char *result_class = opForm.constrained_reg_class();
 866   if (result_class == NULL) {
 867     opForm.dump();
 868     syntax_err(opForm._linenum,
 869                "Use of an undefined result class for operand: %s",
 870                opForm._ident);
 871     abort();
 872   }
 873 
 874   regMask = reg_class_to_reg_mask( result_class );
 875 
 876   return regMask;
 877 }
 878 
 879 // Obtain the name of the RegMask for an InstructForm
 880 const char *ArchDesc::reg_mask(InstructForm &inForm) {
 881   const char *result = inForm.reduce_result();
 882 
 883   if (result == NULL) {
 884     syntax_err(inForm._linenum,
 885                "Did not find result operand or RegMask"
 886                " for this instruction: %s",
 887                inForm._ident);
 888     abort();
 889   }
 890 
 891   // Instructions producing 'Universe' use RegMask::Empty
 892   if( strcmp(result,"Universe")==0 ) {
 893     return "RegMask::Empty";
 894   }
 895 
 896   // Lookup this result operand and get its register class
 897   Form *form = (Form*)_globalNames[result];
 898   if (form == NULL) {
 899     syntax_err(inForm._linenum,
 900                "Did not find result operand for result: %s", result);
 901     abort();
 902   }
 903   OperandForm *oper = form->is_operand();
 904   if (oper == NULL) {
 905     syntax_err(inForm._linenum, "Form is not an OperandForm:");
 906     form->dump();
 907     abort();
 908   }
 909   return reg_mask( *oper );
 910 }
 911 
 912 
 913 // Obtain the STACK_OR_reg_mask name for an OperandForm
 914 char *ArchDesc::stack_or_reg_mask(OperandForm  &opForm) {
 915   // name of cisc_spillable version
 916   const char *reg_mask_name = reg_mask(opForm);
 917 
 918   if (reg_mask_name == NULL) {
 919      syntax_err(opForm._linenum,
 920                 "Did not find reg_mask for opForm: %s",
 921                 opForm._ident);
 922      abort();
 923   }
 924 
 925   const char *stack_or = "STACK_OR_";
 926   int   length         = (int)strlen(stack_or) + (int)strlen(reg_mask_name) + 1;
 927   char *result         = new char[length];
 928   sprintf(result,"%s%s", stack_or, reg_mask_name);
 929 
 930   return result;
 931 }
 932 
 933 // Record that the register class must generate a stack_or_reg_mask
 934 void ArchDesc::set_stack_or_reg(const char *reg_class_name) {
 935   if( _register ) {
 936     RegClass *reg_class  = _register->getRegClass(reg_class_name);
 937     reg_class->_stack_or_reg = true;
 938   }
 939 }
 940 
 941 
 942 // Return the type signature for the ideal operation
 943 const char *ArchDesc::getIdealType(const char *idealOp) {
 944   // Find last character in idealOp, it specifies the type
 945   char  last_char = 0;
 946   const char *ptr = idealOp;
 947   for (; *ptr != '\0'; ++ptr) {
 948     last_char = *ptr;
 949   }
 950 
 951   // Match Vector types.
 952   if (strncmp(idealOp, "Vec",3)==0) {
 953     switch(last_char) {
 954     case 'S':  return "TypeVect::VECTS";
 955     case 'D':  return "TypeVect::VECTD";
 956     case 'X':  return "TypeVect::VECTX";
 957     case 'Y':  return "TypeVect::VECTY";
 958     default:
 959       internal_err("Vector type %s with unrecognized type\n",idealOp);
 960     }
 961   }
 962 
 963   // !!!!!
 964   switch(last_char) {
 965   case 'I':    return "TypeInt::INT";
 966   case 'P':    return "TypePtr::BOTTOM";
 967   case 'N':    return "TypeNarrowOop::BOTTOM";
 968   case 'F':    return "Type::FLOAT";
 969   case 'D':    return "Type::DOUBLE";
 970   case 'L':    return "TypeLong::LONG";
 971   case 's':    return "TypeInt::CC /*flags*/";
 972   default:
 973     return NULL;
 974     // !!!!!
 975     // internal_err("Ideal type %s with unrecognized type\n",idealOp);
 976     break;
 977   }
 978 
 979   return NULL;
 980 }
 981 
 982 
 983 
 984 OperandForm *ArchDesc::constructOperand(const char *ident,
 985                                         bool  ideal_only) {
 986   OperandForm *opForm = new OperandForm(ident, ideal_only);
 987   _globalNames.Insert(ident, opForm);
 988   addForm(opForm);
 989 
 990   return opForm;
 991 }
 992 
 993 
 994 // Import predefined base types: Set = 1, RegI, RegP, ...
 995 void ArchDesc::initBaseOpTypes() {
 996   // Create OperandForm and assign type for each opcode.
 997   for (int i = 1; i < _last_machine_leaf; ++i) {
 998     char        *ident   = (char *)NodeClassNames[i];
 999     constructOperand(ident, true);
1000   }
1001   // Create InstructForm and assign type for each ideal instruction.
1002   for ( int j = _last_machine_leaf+1; j < _last_opcode; ++j) {
1003     char         *ident    = (char *)NodeClassNames[j];
1004     if(!strcmp(ident, "ConI") || !strcmp(ident, "ConP") ||
1005        !strcmp(ident, "ConN") || !strcmp(ident, "ConNKlass") ||
1006        !strcmp(ident, "ConF") || !strcmp(ident, "ConD") ||
1007        !strcmp(ident, "ConL") || !strcmp(ident, "Con" ) ||
1008        !strcmp(ident, "Bool") ) {
1009       constructOperand(ident, true);
1010     }
1011     else {
1012       InstructForm *insForm  = new InstructForm(ident, true);
1013       // insForm->_opcode       = nextUserOpType(ident);
1014       _globalNames.Insert(ident,insForm);
1015       addForm(insForm);
1016     }
1017   }
1018 
1019   { OperandForm *opForm;
1020   // Create operand type "Universe" for return instructions.
1021   const char *ident = "Universe";
1022   opForm = constructOperand(ident, false);
1023 
1024   // Create operand type "label" for branch targets
1025   ident = "label";
1026   opForm = constructOperand(ident, false);
1027 
1028   // !!!!! Update - when adding a new sReg/stackSlot type
1029   // Create operand types "sReg[IPFDL]" for stack slot registers
1030   opForm = constructOperand("sRegI", false);
1031   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1032   opForm = constructOperand("sRegP", false);
1033   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1034   opForm = constructOperand("sRegF", false);
1035   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1036   opForm = constructOperand("sRegD", false);
1037   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1038   opForm = constructOperand("sRegL", false);
1039   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1040 
1041   // Create operand type "method" for call targets
1042   ident = "method";
1043   opForm = constructOperand(ident, false);
1044   }
1045 
1046   // Create Effect Forms for each of the legal effects
1047   // USE, DEF, USE_DEF, KILL, USE_KILL
1048   {
1049     const char *ident = "USE";
1050     Effect     *eForm = new Effect(ident);
1051     _globalNames.Insert(ident, eForm);
1052     ident = "DEF";
1053     eForm = new Effect(ident);
1054     _globalNames.Insert(ident, eForm);
1055     ident = "USE_DEF";
1056     eForm = new Effect(ident);
1057     _globalNames.Insert(ident, eForm);
1058     ident = "KILL";
1059     eForm = new Effect(ident);
1060     _globalNames.Insert(ident, eForm);
1061     ident = "USE_KILL";
1062     eForm = new Effect(ident);
1063     _globalNames.Insert(ident, eForm);
1064     ident = "TEMP";
1065     eForm = new Effect(ident);
1066     _globalNames.Insert(ident, eForm);
1067     ident = "CALL";
1068     eForm = new Effect(ident);
1069     _globalNames.Insert(ident, eForm);
1070   }
1071 
1072   //
1073   // Build mapping from ideal names to ideal indices
1074   int idealIndex = 0;
1075   for (idealIndex = 1; idealIndex < _last_machine_leaf; ++idealIndex) {
1076     const char *idealName = NodeClassNames[idealIndex];
1077     _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1078   }
1079   for ( idealIndex = _last_machine_leaf+1;
1080         idealIndex < _last_opcode; ++idealIndex) {
1081     const char *idealName = NodeClassNames[idealIndex];
1082     _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1083   }
1084 
1085 }
1086 
1087 
1088 //---------------------------addSUNcopyright-------------------------------
1089 // output SUN copyright info
1090 void ArchDesc::addSunCopyright(char* legal, int size, FILE *fp) {
1091   size_t count = fwrite(legal, 1, size, fp);
1092   assert(count == (size_t) size, "copyright info truncated");
1093   fprintf(fp,"\n");
1094   fprintf(fp,"// Machine Generated File.  Do Not Edit!\n");
1095   fprintf(fp,"\n");
1096 }
1097 
1098 
1099 //---------------------------addIncludeGuardStart--------------------------
1100 // output the start of an include guard.
1101 void ArchDesc::addIncludeGuardStart(ADLFILE &adlfile, const char* guardString) {
1102   // Build #include lines
1103   fprintf(adlfile._fp, "\n");
1104   fprintf(adlfile._fp, "#ifndef %s\n", guardString);
1105   fprintf(adlfile._fp, "#define %s\n", guardString);
1106   fprintf(adlfile._fp, "\n");
1107 
1108 }
1109 
1110 //---------------------------addIncludeGuardEnd--------------------------
1111 // output the end of an include guard.
1112 void ArchDesc::addIncludeGuardEnd(ADLFILE &adlfile, const char* guardString) {
1113   // Build #include lines
1114   fprintf(adlfile._fp, "\n");
1115   fprintf(adlfile._fp, "#endif // %s\n", guardString);
1116 
1117 }
1118 
1119 //---------------------------addInclude--------------------------
1120 // output the #include line for this file.
1121 void ArchDesc::addInclude(ADLFILE &adlfile, const char* fileName) {
1122   fprintf(adlfile._fp, "#include \"%s\"\n", fileName);
1123 
1124 }
1125 
1126 void ArchDesc::addInclude(ADLFILE &adlfile, const char* includeDir, const char* fileName) {
1127   fprintf(adlfile._fp, "#include \"%s/%s\"\n", includeDir, fileName);
1128 
1129 }
1130 
1131 //---------------------------addPreprocessorChecks-----------------------------
1132 // Output C preprocessor code to verify the backend compilation environment.
1133 // The idea is to force code produced by "adlc -DHS64" to be compiled by a
1134 // command of the form "CC ... -DHS64 ...", so that any #ifdefs in the source
1135 // blocks select C code that is consistent with adlc's selections of AD code.
1136 void ArchDesc::addPreprocessorChecks(FILE *fp) {
1137   const char* flag;
1138   _preproc_list.reset();
1139   if (_preproc_list.count() > 0 && !_preproc_list.current_is_signal()) {
1140     fprintf(fp, "// Check consistency of C++ compilation with ADLC options:\n");
1141   }
1142   for (_preproc_list.reset(); (flag = _preproc_list.iter()) != NULL; ) {
1143     if (_preproc_list.current_is_signal())  break;
1144     char* def = get_preproc_def(flag);
1145     fprintf(fp, "// Check adlc ");
1146     if (def)
1147           fprintf(fp, "-D%s=%s\n", flag, def);
1148     else  fprintf(fp, "-U%s\n", flag);
1149     fprintf(fp, "#%s %s\n",
1150             def ? "ifndef" : "ifdef", flag);
1151     fprintf(fp, "#  error \"%s %s be defined\"\n",
1152             flag, def ? "must" : "must not");
1153     fprintf(fp, "#endif // %s\n", flag);
1154   }
1155 }
1156 
1157 
1158 // Convert operand name into enum name
1159 const char *ArchDesc::machOperEnum(const char *opName) {
1160   return ArchDesc::getMachOperEnum(opName);
1161 }
1162 
1163 // Convert operand name into enum name
1164 const char *ArchDesc::getMachOperEnum(const char *opName) {
1165   return (opName ? toUpper(opName) : opName);
1166 }
1167 
1168 //---------------------------buildMustCloneMap-----------------------------
1169 // Flag cases when machine needs cloned values or instructions
1170 void ArchDesc::buildMustCloneMap(FILE *fp_hpp, FILE *fp_cpp) {
1171   // Build external declarations for mappings
1172   fprintf(fp_hpp, "// Mapping from machine-independent opcode to boolean\n");
1173   fprintf(fp_hpp, "// Flag cases where machine needs cloned values or instructions\n");
1174   fprintf(fp_hpp, "extern const char must_clone[];\n");
1175   fprintf(fp_hpp, "\n");
1176 
1177   // Build mapping from ideal names to ideal indices
1178   fprintf(fp_cpp, "\n");
1179   fprintf(fp_cpp, "// Mapping from machine-independent opcode to boolean\n");
1180   fprintf(fp_cpp, "const        char must_clone[] = {\n");
1181   for (int idealIndex = 0; idealIndex < _last_opcode; ++idealIndex) {
1182     int         must_clone = 0;
1183     const char *idealName = NodeClassNames[idealIndex];
1184     // Previously selected constants for cloning
1185     // !!!!!
1186     // These are the current machine-dependent clones
1187     if ( strcmp(idealName,"CmpI") == 0
1188          || strcmp(idealName,"CmpU") == 0
1189          || strcmp(idealName,"CmpP") == 0
1190          || strcmp(idealName,"CmpN") == 0
1191          || strcmp(idealName,"CmpL") == 0
1192          || strcmp(idealName,"CmpD") == 0
1193          || strcmp(idealName,"CmpF") == 0
1194          || strcmp(idealName,"FastLock") == 0
1195          || strcmp(idealName,"FastUnlock") == 0
1196          || strcmp(idealName,"OverflowAddI") == 0
1197          || strcmp(idealName,"OverflowAddL") == 0
1198          || strcmp(idealName,"OverflowSubI") == 0
1199          || strcmp(idealName,"OverflowSubL") == 0
1200          || strcmp(idealName,"OverflowMulI") == 0
1201          || strcmp(idealName,"OverflowMulL") == 0
1202          || strcmp(idealName,"Bool") == 0
1203          || strcmp(idealName,"Binary") == 0 ) {
1204       // Removed ConI from the must_clone list.  CPUs that cannot use
1205       // large constants as immediates manifest the constant as an
1206       // instruction.  The must_clone flag prevents the constant from
1207       // floating up out of loops.
1208       must_clone = 1;
1209     }
1210     fprintf(fp_cpp, "  %d%s // %s: %d\n", must_clone,
1211       (idealIndex != (_last_opcode - 1)) ? "," : " // no trailing comma",
1212       idealName, idealIndex);
1213   }
1214   // Finish defining table
1215   fprintf(fp_cpp, "};\n");
1216 }