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