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