1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Implement the Parser for TableGen. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TGParser.h" 15 #include "llvm/TableGen/Record.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include <algorithm> 18 #include <sstream> 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/Support/CommandLine.h" 21 using namespace llvm; 22 23 //===----------------------------------------------------------------------===// 24 // Support Code for the Semantic Actions. 25 //===----------------------------------------------------------------------===// 26 27 namespace llvm { 28 struct SubClassReference { 29 SMLoc RefLoc; 30 Record *Rec; 31 std::vector<Init*> TemplateArgs; 32 SubClassReference() : Rec(0) {} 33 34 bool isInvalid() const { return Rec == 0; } 35 }; 36 37 struct SubMultiClassReference { 38 SMLoc RefLoc; 39 MultiClass *MC; 40 std::vector<Init*> TemplateArgs; 41 SubMultiClassReference() : MC(0) {} 42 43 bool isInvalid() const { return MC == 0; } 44 void dump() const; 45 }; 46 47 void SubMultiClassReference::dump() const { 48 errs() << "Multiclass:\n"; 49 50 MC->dump(); 51 52 errs() << "Template args:\n"; 53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(), 54 iend = TemplateArgs.end(); 55 i != iend; 56 ++i) { 57 (*i)->dump(); 58 } 59 } 60 61 } // end namespace llvm 62 63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) { 64 if (CurRec == 0) 65 CurRec = &CurMultiClass->Rec; 66 67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) { 68 // The value already exists in the class, treat this as a set. 69 if (ERV->setValue(RV.getValue())) 70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" + 71 RV.getType()->getAsString() + "' is incompatible with " + 72 "previous definition of type '" + 73 ERV->getType()->getAsString() + "'"); 74 } else { 75 CurRec->addValue(RV); 76 } 77 return false; 78 } 79 80 /// SetValue - 81 /// Return true on error, false on success. 82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName, 83 const std::vector<unsigned> &BitList, Init *V) { 84 if (!V) return false; 85 86 if (CurRec == 0) CurRec = &CurMultiClass->Rec; 87 88 RecordVal *RV = CurRec->getValue(ValName); 89 if (RV == 0) 90 return Error(Loc, "Value '" + ValName->getAsUnquotedString() 91 + "' unknown!"); 92 93 // Do not allow assignments like 'X = X'. This will just cause infinite loops 94 // in the resolution machinery. 95 if (BitList.empty()) 96 if (VarInit *VI = dynamic_cast<VarInit*>(V)) 97 if (VI->getNameInit() == ValName) 98 return false; 99 100 // If we are assigning to a subset of the bits in the value... then we must be 101 // assigning to a field of BitsRecTy, which must have a BitsInit 102 // initializer. 103 // 104 if (!BitList.empty()) { 105 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue()); 106 if (CurVal == 0) 107 return Error(Loc, "Value '" + ValName->getAsUnquotedString() 108 + "' is not a bits type"); 109 110 // Convert the incoming value to a bits type of the appropriate size... 111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size())); 112 if (BI == 0) { 113 V->convertInitializerTo(BitsRecTy::get(BitList.size())); 114 return Error(Loc, "Initializer is not compatible with bit range"); 115 } 116 117 // We should have a BitsInit type now. 118 BitsInit *BInit = dynamic_cast<BitsInit*>(BI); 119 assert(BInit != 0); 120 121 SmallVector<Init *, 16> NewBits(CurVal->getNumBits()); 122 123 // Loop over bits, assigning values as appropriate. 124 for (unsigned i = 0, e = BitList.size(); i != e; ++i) { 125 unsigned Bit = BitList[i]; 126 if (NewBits[Bit]) 127 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" + 128 ValName->getAsUnquotedString() + "' more than once"); 129 NewBits[Bit] = BInit->getBit(i); 130 } 131 132 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i) 133 if (NewBits[i] == 0) 134 NewBits[i] = CurVal->getBit(i); 135 136 V = BitsInit::get(NewBits); 137 } 138 139 if (RV->setValue(V)) 140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '" 141 + RV->getType()->getAsString() + 142 "' is incompatible with initializer '" + V->getAsString() 143 + "'"); 144 return false; 145 } 146 147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template 148 /// args as SubClass's template arguments. 149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) { 150 Record *SC = SubClass.Rec; 151 // Add all of the values in the subclass into the current class. 152 const std::vector<RecordVal> &Vals = SC->getValues(); 153 for (unsigned i = 0, e = Vals.size(); i != e; ++i) 154 if (AddValue(CurRec, SubClass.RefLoc, Vals[i])) 155 return true; 156 157 const std::vector<Init *> &TArgs = SC->getTemplateArgs(); 158 159 // Ensure that an appropriate number of template arguments are specified. 160 if (TArgs.size() < SubClass.TemplateArgs.size()) 161 return Error(SubClass.RefLoc, "More template args specified than expected"); 162 163 // Loop over all of the template arguments, setting them to the specified 164 // value or leaving them as the default if necessary. 165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 166 if (i < SubClass.TemplateArgs.size()) { 167 // If a value is specified for this template arg, set it now. 168 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(), 169 SubClass.TemplateArgs[i])) 170 return true; 171 172 // Resolve it next. 173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i])); 174 175 // Now remove it. 176 CurRec->removeValue(TArgs[i]); 177 178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 179 return Error(SubClass.RefLoc,"Value not specified for template argument #" 180 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString() 181 + ") of subclass '" + SC->getNameInitAsString() + "'!"); 182 } 183 } 184 185 // Since everything went well, we can now set the "superclass" list for the 186 // current record. 187 const std::vector<Record*> &SCs = SC->getSuperClasses(); 188 for (unsigned i = 0, e = SCs.size(); i != e; ++i) { 189 if (CurRec->isSubClassOf(SCs[i])) 190 return Error(SubClass.RefLoc, 191 "Already subclass of '" + SCs[i]->getName() + "'!\n"); 192 CurRec->addSuperClass(SCs[i]); 193 } 194 195 if (CurRec->isSubClassOf(SC)) 196 return Error(SubClass.RefLoc, 197 "Already subclass of '" + SC->getName() + "'!\n"); 198 CurRec->addSuperClass(SC); 199 return false; 200 } 201 202 /// AddSubMultiClass - Add SubMultiClass as a subclass to 203 /// CurMC, resolving its template args as SubMultiClass's 204 /// template arguments. 205 bool TGParser::AddSubMultiClass(MultiClass *CurMC, 206 SubMultiClassReference &SubMultiClass) { 207 MultiClass *SMC = SubMultiClass.MC; 208 Record *CurRec = &CurMC->Rec; 209 210 const std::vector<RecordVal> &MCVals = CurRec->getValues(); 211 212 // Add all of the values in the subclass into the current class. 213 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues(); 214 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i) 215 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i])) 216 return true; 217 218 int newDefStart = CurMC->DefPrototypes.size(); 219 220 // Add all of the defs in the subclass into the current multiclass. 221 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(), 222 iend = SMC->DefPrototypes.end(); 223 i != iend; 224 ++i) { 225 // Clone the def and add it to the current multiclass 226 Record *NewDef = new Record(**i); 227 228 // Add all of the values in the superclass into the current def. 229 for (unsigned i = 0, e = MCVals.size(); i != e; ++i) 230 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i])) 231 return true; 232 233 CurMC->DefPrototypes.push_back(NewDef); 234 } 235 236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs(); 237 238 // Ensure that an appropriate number of template arguments are 239 // specified. 240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size()) 241 return Error(SubMultiClass.RefLoc, 242 "More template args specified than expected"); 243 244 // Loop over all of the template arguments, setting them to the specified 245 // value or leaving them as the default if necessary. 246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) { 247 if (i < SubMultiClass.TemplateArgs.size()) { 248 // If a value is specified for this template arg, set it in the 249 // superclass now. 250 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i], 251 std::vector<unsigned>(), 252 SubMultiClass.TemplateArgs[i])) 253 return true; 254 255 // Resolve it next. 256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i])); 257 258 // Now remove it. 259 CurRec->removeValue(SMCTArgs[i]); 260 261 // If a value is specified for this template arg, set it in the 262 // new defs now. 263 for (MultiClass::RecordVector::iterator j = 264 CurMC->DefPrototypes.begin() + newDefStart, 265 jend = CurMC->DefPrototypes.end(); 266 j != jend; 267 ++j) { 268 Record *Def = *j; 269 270 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i], 271 std::vector<unsigned>(), 272 SubMultiClass.TemplateArgs[i])) 273 return true; 274 275 // Resolve it next. 276 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i])); 277 278 // Now remove it 279 Def->removeValue(SMCTArgs[i]); 280 } 281 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) { 282 return Error(SubMultiClass.RefLoc, 283 "Value not specified for template argument #" 284 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString() 285 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!"); 286 } 287 } 288 289 return false; 290 } 291 292 /// ProcessForeachDefs - Given a record, apply all of the variable 293 /// values in all surrounding foreach loops, creating new records for 294 /// each combination of values. 295 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) { 296 if (Loops.empty()) 297 return false; 298 299 // We want to instantiate a new copy of CurRec for each combination 300 // of nested loop iterator values. We don't want top instantiate 301 // any copies until we have values for each loop iterator. 302 IterSet IterVals; 303 return ProcessForeachDefs(CurRec, Loc, IterVals); 304 } 305 306 /// ProcessForeachDefs - Given a record, a loop and a loop iterator, 307 /// apply each of the variable values in this loop and then process 308 /// subloops. 309 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){ 310 // Recursively build a tuple of iterator values. 311 if (IterVals.size() != Loops.size()) { 312 assert(IterVals.size() < Loops.size()); 313 ForeachLoop &CurLoop = Loops[IterVals.size()]; 314 ListInit *List = dynamic_cast<ListInit *>(CurLoop.ListValue); 315 if (List == 0) { 316 Error(Loc, "Loop list is not a list"); 317 return true; 318 } 319 320 // Process each value. 321 for (int64_t i = 0; i < List->getSize(); ++i) { 322 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i); 323 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal)); 324 if (ProcessForeachDefs(CurRec, Loc, IterVals)) 325 return true; 326 IterVals.pop_back(); 327 } 328 return false; 329 } 330 331 // This is the bottom of the recursion. We have all of the iterator values 332 // for this point in the iteration space. Instantiate a new record to 333 // reflect this combination of values. 334 Record *IterRec = new Record(*CurRec); 335 336 // Set the iterator values now. 337 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) { 338 VarInit *IterVar = IterVals[i].IterVar; 339 TypedInit *IVal = dynamic_cast<TypedInit *>(IterVals[i].IterValue); 340 if (IVal == 0) { 341 Error(Loc, "foreach iterator value is untyped"); 342 return true; 343 } 344 345 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false)); 346 347 if (SetValue(IterRec, Loc, IterVar->getName(), 348 std::vector<unsigned>(), IVal)) { 349 Error(Loc, "when instantiating this def"); 350 return true; 351 } 352 353 // Resolve it next. 354 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName())); 355 356 // Remove it. 357 IterRec->removeValue(IterVar->getName()); 358 } 359 360 if (Records.getDef(IterRec->getNameInitAsString())) { 361 Error(Loc, "def already exists: " + IterRec->getNameInitAsString()); 362 return true; 363 } 364 365 Records.addDef(IterRec); 366 IterRec->resolveReferences(); 367 return false; 368 } 369 370 //===----------------------------------------------------------------------===// 371 // Parser Code 372 //===----------------------------------------------------------------------===// 373 374 /// isObjectStart - Return true if this is a valid first token for an Object. 375 static bool isObjectStart(tgtok::TokKind K) { 376 return K == tgtok::Class || K == tgtok::Def || 377 K == tgtok::Defm || K == tgtok::Let || 378 K == tgtok::MultiClass || K == tgtok::Foreach; 379 } 380 381 static std::string GetNewAnonymousName() { 382 static unsigned AnonCounter = 0; 383 return "anonymous."+utostr(AnonCounter++); 384 } 385 386 /// ParseObjectName - If an object name is specified, return it. Otherwise, 387 /// return an anonymous name. 388 /// ObjectName ::= Value [ '#' Value ]* 389 /// ObjectName ::= /*empty*/ 390 /// 391 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) { 392 switch (Lex.getCode()) { 393 case tgtok::colon: 394 case tgtok::semi: 395 case tgtok::l_brace: 396 // These are all of the tokens that can begin an object body. 397 // Some of these can also begin values but we disallow those cases 398 // because they are unlikely to be useful. 399 return StringInit::get(GetNewAnonymousName()); 400 default: 401 break; 402 } 403 404 Record *CurRec = 0; 405 if (CurMultiClass) 406 CurRec = &CurMultiClass->Rec; 407 408 RecTy *Type = 0; 409 if (CurRec) { 410 const TypedInit *CurRecName = 411 dynamic_cast<const TypedInit *>(CurRec->getNameInit()); 412 if (!CurRecName) { 413 TokError("Record name is not typed!"); 414 return 0; 415 } 416 Type = CurRecName->getType(); 417 } 418 419 return ParseValue(CurRec, Type, ParseNameMode); 420 } 421 422 /// ParseClassID - Parse and resolve a reference to a class name. This returns 423 /// null on error. 424 /// 425 /// ClassID ::= ID 426 /// 427 Record *TGParser::ParseClassID() { 428 if (Lex.getCode() != tgtok::Id) { 429 TokError("expected name for ClassID"); 430 return 0; 431 } 432 433 Record *Result = Records.getClass(Lex.getCurStrVal()); 434 if (Result == 0) 435 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'"); 436 437 Lex.Lex(); 438 return Result; 439 } 440 441 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name. 442 /// This returns null on error. 443 /// 444 /// MultiClassID ::= ID 445 /// 446 MultiClass *TGParser::ParseMultiClassID() { 447 if (Lex.getCode() != tgtok::Id) { 448 TokError("expected name for ClassID"); 449 return 0; 450 } 451 452 MultiClass *Result = MultiClasses[Lex.getCurStrVal()]; 453 if (Result == 0) 454 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'"); 455 456 Lex.Lex(); 457 return Result; 458 } 459 460 Record *TGParser::ParseDefmID() { 461 if (Lex.getCode() != tgtok::Id) { 462 TokError("expected multiclass name"); 463 return 0; 464 } 465 466 MultiClass *MC = MultiClasses[Lex.getCurStrVal()]; 467 if (MC == 0) { 468 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'"); 469 return 0; 470 } 471 472 Lex.Lex(); 473 return &MC->Rec; 474 } 475 476 477 /// ParseSubClassReference - Parse a reference to a subclass or to a templated 478 /// subclass. This returns a SubClassRefTy with a null Record* on error. 479 /// 480 /// SubClassRef ::= ClassID 481 /// SubClassRef ::= ClassID '<' ValueList '>' 482 /// 483 SubClassReference TGParser:: 484 ParseSubClassReference(Record *CurRec, bool isDefm) { 485 SubClassReference Result; 486 Result.RefLoc = Lex.getLoc(); 487 488 if (isDefm) 489 Result.Rec = ParseDefmID(); 490 else 491 Result.Rec = ParseClassID(); 492 if (Result.Rec == 0) return Result; 493 494 // If there is no template arg list, we're done. 495 if (Lex.getCode() != tgtok::less) 496 return Result; 497 Lex.Lex(); // Eat the '<' 498 499 if (Lex.getCode() == tgtok::greater) { 500 TokError("subclass reference requires a non-empty list of template values"); 501 Result.Rec = 0; 502 return Result; 503 } 504 505 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec); 506 if (Result.TemplateArgs.empty()) { 507 Result.Rec = 0; // Error parsing value list. 508 return Result; 509 } 510 511 if (Lex.getCode() != tgtok::greater) { 512 TokError("expected '>' in template value list"); 513 Result.Rec = 0; 514 return Result; 515 } 516 Lex.Lex(); 517 518 return Result; 519 } 520 521 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a 522 /// templated submulticlass. This returns a SubMultiClassRefTy with a null 523 /// Record* on error. 524 /// 525 /// SubMultiClassRef ::= MultiClassID 526 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>' 527 /// 528 SubMultiClassReference TGParser:: 529 ParseSubMultiClassReference(MultiClass *CurMC) { 530 SubMultiClassReference Result; 531 Result.RefLoc = Lex.getLoc(); 532 533 Result.MC = ParseMultiClassID(); 534 if (Result.MC == 0) return Result; 535 536 // If there is no template arg list, we're done. 537 if (Lex.getCode() != tgtok::less) 538 return Result; 539 Lex.Lex(); // Eat the '<' 540 541 if (Lex.getCode() == tgtok::greater) { 542 TokError("subclass reference requires a non-empty list of template values"); 543 Result.MC = 0; 544 return Result; 545 } 546 547 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec); 548 if (Result.TemplateArgs.empty()) { 549 Result.MC = 0; // Error parsing value list. 550 return Result; 551 } 552 553 if (Lex.getCode() != tgtok::greater) { 554 TokError("expected '>' in template value list"); 555 Result.MC = 0; 556 return Result; 557 } 558 Lex.Lex(); 559 560 return Result; 561 } 562 563 /// ParseRangePiece - Parse a bit/value range. 564 /// RangePiece ::= INTVAL 565 /// RangePiece ::= INTVAL '-' INTVAL 566 /// RangePiece ::= INTVAL INTVAL 567 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) { 568 if (Lex.getCode() != tgtok::IntVal) { 569 TokError("expected integer or bitrange"); 570 return true; 571 } 572 int64_t Start = Lex.getCurIntVal(); 573 int64_t End; 574 575 if (Start < 0) 576 return TokError("invalid range, cannot be negative"); 577 578 switch (Lex.Lex()) { // eat first character. 579 default: 580 Ranges.push_back(Start); 581 return false; 582 case tgtok::minus: 583 if (Lex.Lex() != tgtok::IntVal) { 584 TokError("expected integer value as end of range"); 585 return true; 586 } 587 End = Lex.getCurIntVal(); 588 break; 589 case tgtok::IntVal: 590 End = -Lex.getCurIntVal(); 591 break; 592 } 593 if (End < 0) 594 return TokError("invalid range, cannot be negative"); 595 Lex.Lex(); 596 597 // Add to the range. 598 if (Start < End) { 599 for (; Start <= End; ++Start) 600 Ranges.push_back(Start); 601 } else { 602 for (; Start >= End; --Start) 603 Ranges.push_back(Start); 604 } 605 return false; 606 } 607 608 /// ParseRangeList - Parse a list of scalars and ranges into scalar values. 609 /// 610 /// RangeList ::= RangePiece (',' RangePiece)* 611 /// 612 std::vector<unsigned> TGParser::ParseRangeList() { 613 std::vector<unsigned> Result; 614 615 // Parse the first piece. 616 if (ParseRangePiece(Result)) 617 return std::vector<unsigned>(); 618 while (Lex.getCode() == tgtok::comma) { 619 Lex.Lex(); // Eat the comma. 620 621 // Parse the next range piece. 622 if (ParseRangePiece(Result)) 623 return std::vector<unsigned>(); 624 } 625 return Result; 626 } 627 628 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing. 629 /// OptionalRangeList ::= '<' RangeList '>' 630 /// OptionalRangeList ::= /*empty*/ 631 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) { 632 if (Lex.getCode() != tgtok::less) 633 return false; 634 635 SMLoc StartLoc = Lex.getLoc(); 636 Lex.Lex(); // eat the '<' 637 638 // Parse the range list. 639 Ranges = ParseRangeList(); 640 if (Ranges.empty()) return true; 641 642 if (Lex.getCode() != tgtok::greater) { 643 TokError("expected '>' at end of range list"); 644 return Error(StartLoc, "to match this '<'"); 645 } 646 Lex.Lex(); // eat the '>'. 647 return false; 648 } 649 650 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing. 651 /// OptionalBitList ::= '{' RangeList '}' 652 /// OptionalBitList ::= /*empty*/ 653 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) { 654 if (Lex.getCode() != tgtok::l_brace) 655 return false; 656 657 SMLoc StartLoc = Lex.getLoc(); 658 Lex.Lex(); // eat the '{' 659 660 // Parse the range list. 661 Ranges = ParseRangeList(); 662 if (Ranges.empty()) return true; 663 664 if (Lex.getCode() != tgtok::r_brace) { 665 TokError("expected '}' at end of bit list"); 666 return Error(StartLoc, "to match this '{'"); 667 } 668 Lex.Lex(); // eat the '}'. 669 return false; 670 } 671 672 673 /// ParseType - Parse and return a tblgen type. This returns null on error. 674 /// 675 /// Type ::= STRING // string type 676 /// Type ::= CODE // code type 677 /// Type ::= BIT // bit type 678 /// Type ::= BITS '<' INTVAL '>' // bits<x> type 679 /// Type ::= INT // int type 680 /// Type ::= LIST '<' Type '>' // list<x> type 681 /// Type ::= DAG // dag type 682 /// Type ::= ClassID // Record Type 683 /// 684 RecTy *TGParser::ParseType() { 685 switch (Lex.getCode()) { 686 default: TokError("Unknown token when expecting a type"); return 0; 687 case tgtok::String: Lex.Lex(); return StringRecTy::get(); 688 case tgtok::Code: Lex.Lex(); return StringRecTy::get(); 689 case tgtok::Bit: Lex.Lex(); return BitRecTy::get(); 690 case tgtok::Int: Lex.Lex(); return IntRecTy::get(); 691 case tgtok::Dag: Lex.Lex(); return DagRecTy::get(); 692 case tgtok::Id: 693 if (Record *R = ParseClassID()) return RecordRecTy::get(R); 694 return 0; 695 case tgtok::Bits: { 696 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 697 TokError("expected '<' after bits type"); 698 return 0; 699 } 700 if (Lex.Lex() != tgtok::IntVal) { // Eat '<' 701 TokError("expected integer in bits<n> type"); 702 return 0; 703 } 704 uint64_t Val = Lex.getCurIntVal(); 705 if (Lex.Lex() != tgtok::greater) { // Eat count. 706 TokError("expected '>' at end of bits<n> type"); 707 return 0; 708 } 709 Lex.Lex(); // Eat '>' 710 return BitsRecTy::get(Val); 711 } 712 case tgtok::List: { 713 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 714 TokError("expected '<' after list type"); 715 return 0; 716 } 717 Lex.Lex(); // Eat '<' 718 RecTy *SubType = ParseType(); 719 if (SubType == 0) return 0; 720 721 if (Lex.getCode() != tgtok::greater) { 722 TokError("expected '>' at end of list<ty> type"); 723 return 0; 724 } 725 Lex.Lex(); // Eat '>' 726 return ListRecTy::get(SubType); 727 } 728 } 729 } 730 731 /// ParseIDValue - Parse an ID as a value and decode what it means. 732 /// 733 /// IDValue ::= ID [def local value] 734 /// IDValue ::= ID [def template arg] 735 /// IDValue ::= ID [multiclass local value] 736 /// IDValue ::= ID [multiclass template argument] 737 /// IDValue ::= ID [def name] 738 /// 739 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) { 740 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue"); 741 std::string Name = Lex.getCurStrVal(); 742 SMLoc Loc = Lex.getLoc(); 743 Lex.Lex(); 744 return ParseIDValue(CurRec, Name, Loc); 745 } 746 747 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID 748 /// has already been read. 749 Init *TGParser::ParseIDValue(Record *CurRec, 750 const std::string &Name, SMLoc NameLoc, 751 IDParseMode Mode) { 752 if (CurRec) { 753 if (const RecordVal *RV = CurRec->getValue(Name)) 754 return VarInit::get(Name, RV->getType()); 755 756 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":"); 757 758 if (CurMultiClass) 759 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, 760 "::"); 761 762 if (CurRec->isTemplateArg(TemplateArgName)) { 763 const RecordVal *RV = CurRec->getValue(TemplateArgName); 764 assert(RV && "Template arg doesn't exist??"); 765 return VarInit::get(TemplateArgName, RV->getType()); 766 } 767 } 768 769 if (CurMultiClass) { 770 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, 771 "::"); 772 773 if (CurMultiClass->Rec.isTemplateArg(MCName)) { 774 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName); 775 assert(RV && "Template arg doesn't exist??"); 776 return VarInit::get(MCName, RV->getType()); 777 } 778 } 779 780 // If this is in a foreach loop, make sure it's not a loop iterator 781 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end(); 782 i != iend; 783 ++i) { 784 VarInit *IterVar = dynamic_cast<VarInit *>(i->IterVar); 785 if (IterVar && IterVar->getName() == Name) 786 return IterVar; 787 } 788 789 if (Mode == ParseNameMode) 790 return StringInit::get(Name); 791 792 if (Record *D = Records.getDef(Name)) 793 return DefInit::get(D); 794 795 if (Mode == ParseValueMode) { 796 Error(NameLoc, "Variable not defined: '" + Name + "'"); 797 return 0; 798 } 799 800 return StringInit::get(Name); 801 } 802 803 /// ParseOperation - Parse an operator. This returns null on error. 804 /// 805 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')' 806 /// 807 Init *TGParser::ParseOperation(Record *CurRec) { 808 switch (Lex.getCode()) { 809 default: 810 TokError("unknown operation"); 811 return 0; 812 case tgtok::XHead: 813 case tgtok::XTail: 814 case tgtok::XEmpty: 815 case tgtok::XCast: { // Value ::= !unop '(' Value ')' 816 UnOpInit::UnaryOp Code; 817 RecTy *Type = 0; 818 819 switch (Lex.getCode()) { 820 default: llvm_unreachable("Unhandled code!"); 821 case tgtok::XCast: 822 Lex.Lex(); // eat the operation 823 Code = UnOpInit::CAST; 824 825 Type = ParseOperatorType(); 826 827 if (Type == 0) { 828 TokError("did not get type for unary operator"); 829 return 0; 830 } 831 832 break; 833 case tgtok::XHead: 834 Lex.Lex(); // eat the operation 835 Code = UnOpInit::HEAD; 836 break; 837 case tgtok::XTail: 838 Lex.Lex(); // eat the operation 839 Code = UnOpInit::TAIL; 840 break; 841 case tgtok::XEmpty: 842 Lex.Lex(); // eat the operation 843 Code = UnOpInit::EMPTY; 844 Type = IntRecTy::get(); 845 break; 846 } 847 if (Lex.getCode() != tgtok::l_paren) { 848 TokError("expected '(' after unary operator"); 849 return 0; 850 } 851 Lex.Lex(); // eat the '(' 852 853 Init *LHS = ParseValue(CurRec); 854 if (LHS == 0) return 0; 855 856 if (Code == UnOpInit::HEAD 857 || Code == UnOpInit::TAIL 858 || Code == UnOpInit::EMPTY) { 859 ListInit *LHSl = dynamic_cast<ListInit*>(LHS); 860 StringInit *LHSs = dynamic_cast<StringInit*>(LHS); 861 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS); 862 if (LHSl == 0 && LHSs == 0 && LHSt == 0) { 863 TokError("expected list or string type argument in unary operator"); 864 return 0; 865 } 866 if (LHSt) { 867 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType()); 868 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType()); 869 if (LType == 0 && SType == 0) { 870 TokError("expected list or string type argumnet in unary operator"); 871 return 0; 872 } 873 } 874 875 if (Code == UnOpInit::HEAD 876 || Code == UnOpInit::TAIL) { 877 if (LHSl == 0 && LHSt == 0) { 878 TokError("expected list type argumnet in unary operator"); 879 return 0; 880 } 881 882 if (LHSl && LHSl->getSize() == 0) { 883 TokError("empty list argument in unary operator"); 884 return 0; 885 } 886 if (LHSl) { 887 Init *Item = LHSl->getElement(0); 888 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item); 889 if (Itemt == 0) { 890 TokError("untyped list element in unary operator"); 891 return 0; 892 } 893 if (Code == UnOpInit::HEAD) { 894 Type = Itemt->getType(); 895 } else { 896 Type = ListRecTy::get(Itemt->getType()); 897 } 898 } else { 899 assert(LHSt && "expected list type argument in unary operator"); 900 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType()); 901 if (LType == 0) { 902 TokError("expected list type argumnet in unary operator"); 903 return 0; 904 } 905 if (Code == UnOpInit::HEAD) { 906 Type = LType->getElementType(); 907 } else { 908 Type = LType; 909 } 910 } 911 } 912 } 913 914 if (Lex.getCode() != tgtok::r_paren) { 915 TokError("expected ')' in unary operator"); 916 return 0; 917 } 918 Lex.Lex(); // eat the ')' 919 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass); 920 } 921 922 case tgtok::XConcat: 923 case tgtok::XSRA: 924 case tgtok::XSRL: 925 case tgtok::XSHL: 926 case tgtok::XEq: 927 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')' 928 tgtok::TokKind OpTok = Lex.getCode(); 929 SMLoc OpLoc = Lex.getLoc(); 930 Lex.Lex(); // eat the operation 931 932 BinOpInit::BinaryOp Code; 933 RecTy *Type = 0; 934 935 switch (OpTok) { 936 default: llvm_unreachable("Unhandled code!"); 937 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break; 938 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break; 939 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break; 940 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break; 941 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break; 942 case tgtok::XStrConcat: 943 Code = BinOpInit::STRCONCAT; 944 Type = StringRecTy::get(); 945 break; 946 } 947 948 if (Lex.getCode() != tgtok::l_paren) { 949 TokError("expected '(' after binary operator"); 950 return 0; 951 } 952 Lex.Lex(); // eat the '(' 953 954 SmallVector<Init*, 2> InitList; 955 956 InitList.push_back(ParseValue(CurRec)); 957 if (InitList.back() == 0) return 0; 958 959 while (Lex.getCode() == tgtok::comma) { 960 Lex.Lex(); // eat the ',' 961 962 InitList.push_back(ParseValue(CurRec)); 963 if (InitList.back() == 0) return 0; 964 } 965 966 if (Lex.getCode() != tgtok::r_paren) { 967 TokError("expected ')' in operator"); 968 return 0; 969 } 970 Lex.Lex(); // eat the ')' 971 972 // We allow multiple operands to associative operators like !strconcat as 973 // shorthand for nesting them. 974 if (Code == BinOpInit::STRCONCAT) { 975 while (InitList.size() > 2) { 976 Init *RHS = InitList.pop_back_val(); 977 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type)) 978 ->Fold(CurRec, CurMultiClass); 979 InitList.back() = RHS; 980 } 981 } 982 983 if (InitList.size() == 2) 984 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 985 ->Fold(CurRec, CurMultiClass); 986 987 Error(OpLoc, "expected two operands to operator"); 988 return 0; 989 } 990 991 case tgtok::XIf: 992 case tgtok::XForEach: 993 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 994 TernOpInit::TernaryOp Code; 995 RecTy *Type = 0; 996 997 tgtok::TokKind LexCode = Lex.getCode(); 998 Lex.Lex(); // eat the operation 999 switch (LexCode) { 1000 default: llvm_unreachable("Unhandled code!"); 1001 case tgtok::XIf: 1002 Code = TernOpInit::IF; 1003 break; 1004 case tgtok::XForEach: 1005 Code = TernOpInit::FOREACH; 1006 break; 1007 case tgtok::XSubst: 1008 Code = TernOpInit::SUBST; 1009 break; 1010 } 1011 if (Lex.getCode() != tgtok::l_paren) { 1012 TokError("expected '(' after ternary operator"); 1013 return 0; 1014 } 1015 Lex.Lex(); // eat the '(' 1016 1017 Init *LHS = ParseValue(CurRec); 1018 if (LHS == 0) return 0; 1019 1020 if (Lex.getCode() != tgtok::comma) { 1021 TokError("expected ',' in ternary operator"); 1022 return 0; 1023 } 1024 Lex.Lex(); // eat the ',' 1025 1026 Init *MHS = ParseValue(CurRec); 1027 if (MHS == 0) return 0; 1028 1029 if (Lex.getCode() != tgtok::comma) { 1030 TokError("expected ',' in ternary operator"); 1031 return 0; 1032 } 1033 Lex.Lex(); // eat the ',' 1034 1035 Init *RHS = ParseValue(CurRec); 1036 if (RHS == 0) return 0; 1037 1038 if (Lex.getCode() != tgtok::r_paren) { 1039 TokError("expected ')' in binary operator"); 1040 return 0; 1041 } 1042 Lex.Lex(); // eat the ')' 1043 1044 switch (LexCode) { 1045 default: llvm_unreachable("Unhandled code!"); 1046 case tgtok::XIf: { 1047 // FIXME: The `!if' operator doesn't handle non-TypedInit well at 1048 // all. This can be made much more robust. 1049 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS); 1050 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS); 1051 1052 RecTy *MHSTy = 0; 1053 RecTy *RHSTy = 0; 1054 1055 if (MHSt == 0 && RHSt == 0) { 1056 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS); 1057 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS); 1058 1059 if (MHSbits && RHSbits && 1060 MHSbits->getNumBits() == RHSbits->getNumBits()) { 1061 Type = BitRecTy::get(); 1062 break; 1063 } else { 1064 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS); 1065 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS); 1066 1067 if (MHSbit && RHSbit) { 1068 Type = BitRecTy::get(); 1069 break; 1070 } 1071 } 1072 } else if (MHSt != 0 && RHSt != 0) { 1073 MHSTy = MHSt->getType(); 1074 RHSTy = RHSt->getType(); 1075 } 1076 1077 if (!MHSTy || !RHSTy) { 1078 TokError("could not get type for !if"); 1079 return 0; 1080 } 1081 1082 if (MHSTy->typeIsConvertibleTo(RHSTy)) { 1083 Type = RHSTy; 1084 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) { 1085 Type = MHSTy; 1086 } else { 1087 TokError("inconsistent types for !if"); 1088 return 0; 1089 } 1090 break; 1091 } 1092 case tgtok::XForEach: { 1093 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS); 1094 if (MHSt == 0) { 1095 TokError("could not get type for !foreach"); 1096 return 0; 1097 } 1098 Type = MHSt->getType(); 1099 break; 1100 } 1101 case tgtok::XSubst: { 1102 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS); 1103 if (RHSt == 0) { 1104 TokError("could not get type for !subst"); 1105 return 0; 1106 } 1107 Type = RHSt->getType(); 1108 break; 1109 } 1110 } 1111 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec, 1112 CurMultiClass); 1113 } 1114 } 1115 } 1116 1117 /// ParseOperatorType - Parse a type for an operator. This returns 1118 /// null on error. 1119 /// 1120 /// OperatorType ::= '<' Type '>' 1121 /// 1122 RecTy *TGParser::ParseOperatorType() { 1123 RecTy *Type = 0; 1124 1125 if (Lex.getCode() != tgtok::less) { 1126 TokError("expected type name for operator"); 1127 return 0; 1128 } 1129 Lex.Lex(); // eat the < 1130 1131 Type = ParseType(); 1132 1133 if (Type == 0) { 1134 TokError("expected type name for operator"); 1135 return 0; 1136 } 1137 1138 if (Lex.getCode() != tgtok::greater) { 1139 TokError("expected type name for operator"); 1140 return 0; 1141 } 1142 Lex.Lex(); // eat the > 1143 1144 return Type; 1145 } 1146 1147 1148 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1149 /// 1150 /// SimpleValue ::= IDValue 1151 /// SimpleValue ::= INTVAL 1152 /// SimpleValue ::= STRVAL+ 1153 /// SimpleValue ::= CODEFRAGMENT 1154 /// SimpleValue ::= '?' 1155 /// SimpleValue ::= '{' ValueList '}' 1156 /// SimpleValue ::= ID '<' ValueListNE '>' 1157 /// SimpleValue ::= '[' ValueList ']' 1158 /// SimpleValue ::= '(' IDValue DagArgList ')' 1159 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')' 1160 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1161 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1162 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1163 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1164 /// 1165 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1166 IDParseMode Mode) { 1167 Init *R = 0; 1168 switch (Lex.getCode()) { 1169 default: TokError("Unknown token when parsing a value"); break; 1170 case tgtok::paste: 1171 // This is a leading paste operation. This is deprecated but 1172 // still exists in some .td files. Ignore it. 1173 Lex.Lex(); // Skip '#'. 1174 return ParseSimpleValue(CurRec, ItemType, Mode); 1175 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break; 1176 case tgtok::StrVal: { 1177 std::string Val = Lex.getCurStrVal(); 1178 Lex.Lex(); 1179 1180 // Handle multiple consecutive concatenated strings. 1181 while (Lex.getCode() == tgtok::StrVal) { 1182 Val += Lex.getCurStrVal(); 1183 Lex.Lex(); 1184 } 1185 1186 R = StringInit::get(Val); 1187 break; 1188 } 1189 case tgtok::CodeFragment: 1190 R = StringInit::get(Lex.getCurStrVal()); 1191 Lex.Lex(); 1192 break; 1193 case tgtok::question: 1194 R = UnsetInit::get(); 1195 Lex.Lex(); 1196 break; 1197 case tgtok::Id: { 1198 SMLoc NameLoc = Lex.getLoc(); 1199 std::string Name = Lex.getCurStrVal(); 1200 if (Lex.Lex() != tgtok::less) // consume the Id. 1201 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue 1202 1203 // Value ::= ID '<' ValueListNE '>' 1204 if (Lex.Lex() == tgtok::greater) { 1205 TokError("expected non-empty value list"); 1206 return 0; 1207 } 1208 1209 // This is a CLASS<initvalslist> expression. This is supposed to synthesize 1210 // a new anonymous definition, deriving from CLASS<initvalslist> with no 1211 // body. 1212 Record *Class = Records.getClass(Name); 1213 if (!Class) { 1214 Error(NameLoc, "Expected a class name, got '" + Name + "'"); 1215 return 0; 1216 } 1217 1218 std::vector<Init*> ValueList = ParseValueList(CurRec, Class); 1219 if (ValueList.empty()) return 0; 1220 1221 if (Lex.getCode() != tgtok::greater) { 1222 TokError("expected '>' at end of value list"); 1223 return 0; 1224 } 1225 Lex.Lex(); // eat the '>' 1226 1227 // Create the new record, set it as CurRec temporarily. 1228 static unsigned AnonCounter = 0; 1229 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++), 1230 NameLoc, 1231 Records); 1232 SubClassReference SCRef; 1233 SCRef.RefLoc = NameLoc; 1234 SCRef.Rec = Class; 1235 SCRef.TemplateArgs = ValueList; 1236 // Add info about the subclass to NewRec. 1237 if (AddSubClass(NewRec, SCRef)) 1238 return 0; 1239 NewRec->resolveReferences(); 1240 Records.addDef(NewRec); 1241 1242 // The result of the expression is a reference to the new record. 1243 return DefInit::get(NewRec); 1244 } 1245 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1246 SMLoc BraceLoc = Lex.getLoc(); 1247 Lex.Lex(); // eat the '{' 1248 std::vector<Init*> Vals; 1249 1250 if (Lex.getCode() != tgtok::r_brace) { 1251 Vals = ParseValueList(CurRec); 1252 if (Vals.empty()) return 0; 1253 } 1254 if (Lex.getCode() != tgtok::r_brace) { 1255 TokError("expected '}' at end of bit list value"); 1256 return 0; 1257 } 1258 Lex.Lex(); // eat the '}' 1259 1260 SmallVector<Init *, 16> NewBits(Vals.size()); 1261 1262 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1263 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get()); 1264 if (Bit == 0) { 1265 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+ 1266 ") is not convertable to a bit"); 1267 return 0; 1268 } 1269 NewBits[Vals.size()-i-1] = Bit; 1270 } 1271 return BitsInit::get(NewBits); 1272 } 1273 case tgtok::l_square: { // Value ::= '[' ValueList ']' 1274 Lex.Lex(); // eat the '[' 1275 std::vector<Init*> Vals; 1276 1277 RecTy *DeducedEltTy = 0; 1278 ListRecTy *GivenListTy = 0; 1279 1280 if (ItemType != 0) { 1281 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType); 1282 if (ListType == 0) { 1283 std::stringstream s; 1284 s << "Type mismatch for list, expected list type, got " 1285 << ItemType->getAsString(); 1286 TokError(s.str()); 1287 return 0; 1288 } 1289 GivenListTy = ListType; 1290 } 1291 1292 if (Lex.getCode() != tgtok::r_square) { 1293 Vals = ParseValueList(CurRec, 0, 1294 GivenListTy ? GivenListTy->getElementType() : 0); 1295 if (Vals.empty()) return 0; 1296 } 1297 if (Lex.getCode() != tgtok::r_square) { 1298 TokError("expected ']' at end of list value"); 1299 return 0; 1300 } 1301 Lex.Lex(); // eat the ']' 1302 1303 RecTy *GivenEltTy = 0; 1304 if (Lex.getCode() == tgtok::less) { 1305 // Optional list element type 1306 Lex.Lex(); // eat the '<' 1307 1308 GivenEltTy = ParseType(); 1309 if (GivenEltTy == 0) { 1310 // Couldn't parse element type 1311 return 0; 1312 } 1313 1314 if (Lex.getCode() != tgtok::greater) { 1315 TokError("expected '>' at end of list element type"); 1316 return 0; 1317 } 1318 Lex.Lex(); // eat the '>' 1319 } 1320 1321 // Check elements 1322 RecTy *EltTy = 0; 1323 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end(); 1324 i != ie; 1325 ++i) { 1326 TypedInit *TArg = dynamic_cast<TypedInit*>(*i); 1327 if (TArg == 0) { 1328 TokError("Untyped list element"); 1329 return 0; 1330 } 1331 if (EltTy != 0) { 1332 EltTy = resolveTypes(EltTy, TArg->getType()); 1333 if (EltTy == 0) { 1334 TokError("Incompatible types in list elements"); 1335 return 0; 1336 } 1337 } else { 1338 EltTy = TArg->getType(); 1339 } 1340 } 1341 1342 if (GivenEltTy != 0) { 1343 if (EltTy != 0) { 1344 // Verify consistency 1345 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) { 1346 TokError("Incompatible types in list elements"); 1347 return 0; 1348 } 1349 } 1350 EltTy = GivenEltTy; 1351 } 1352 1353 if (EltTy == 0) { 1354 if (ItemType == 0) { 1355 TokError("No type for list"); 1356 return 0; 1357 } 1358 DeducedEltTy = GivenListTy->getElementType(); 1359 } else { 1360 // Make sure the deduced type is compatible with the given type 1361 if (GivenListTy) { 1362 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 1363 TokError("Element type mismatch for list"); 1364 return 0; 1365 } 1366 } 1367 DeducedEltTy = EltTy; 1368 } 1369 1370 return ListInit::get(Vals, DeducedEltTy); 1371 } 1372 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')' 1373 Lex.Lex(); // eat the '(' 1374 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) { 1375 TokError("expected identifier in dag init"); 1376 return 0; 1377 } 1378 1379 Init *Operator = ParseValue(CurRec); 1380 if (Operator == 0) return 0; 1381 1382 // If the operator name is present, parse it. 1383 std::string OperatorName; 1384 if (Lex.getCode() == tgtok::colon) { 1385 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 1386 TokError("expected variable name in dag operator"); 1387 return 0; 1388 } 1389 OperatorName = Lex.getCurStrVal(); 1390 Lex.Lex(); // eat the VarName. 1391 } 1392 1393 std::vector<std::pair<llvm::Init*, std::string> > DagArgs; 1394 if (Lex.getCode() != tgtok::r_paren) { 1395 DagArgs = ParseDagArgList(CurRec); 1396 if (DagArgs.empty()) return 0; 1397 } 1398 1399 if (Lex.getCode() != tgtok::r_paren) { 1400 TokError("expected ')' in dag init"); 1401 return 0; 1402 } 1403 Lex.Lex(); // eat the ')' 1404 1405 return DagInit::get(Operator, OperatorName, DagArgs); 1406 } 1407 1408 case tgtok::XHead: 1409 case tgtok::XTail: 1410 case tgtok::XEmpty: 1411 case tgtok::XCast: // Value ::= !unop '(' Value ')' 1412 case tgtok::XConcat: 1413 case tgtok::XSRA: 1414 case tgtok::XSRL: 1415 case tgtok::XSHL: 1416 case tgtok::XEq: 1417 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')' 1418 case tgtok::XIf: 1419 case tgtok::XForEach: 1420 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1421 return ParseOperation(CurRec); 1422 } 1423 } 1424 1425 return R; 1426 } 1427 1428 /// ParseValue - Parse a tblgen value. This returns null on error. 1429 /// 1430 /// Value ::= SimpleValue ValueSuffix* 1431 /// ValueSuffix ::= '{' BitList '}' 1432 /// ValueSuffix ::= '[' BitList ']' 1433 /// ValueSuffix ::= '.' ID 1434 /// 1435 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) { 1436 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode); 1437 if (Result == 0) return 0; 1438 1439 // Parse the suffixes now if present. 1440 while (1) { 1441 switch (Lex.getCode()) { 1442 default: return Result; 1443 case tgtok::l_brace: { 1444 if (Mode == ParseNameMode || Mode == ParseForeachMode) 1445 // This is the beginning of the object body. 1446 return Result; 1447 1448 SMLoc CurlyLoc = Lex.getLoc(); 1449 Lex.Lex(); // eat the '{' 1450 std::vector<unsigned> Ranges = ParseRangeList(); 1451 if (Ranges.empty()) return 0; 1452 1453 // Reverse the bitlist. 1454 std::reverse(Ranges.begin(), Ranges.end()); 1455 Result = Result->convertInitializerBitRange(Ranges); 1456 if (Result == 0) { 1457 Error(CurlyLoc, "Invalid bit range for value"); 1458 return 0; 1459 } 1460 1461 // Eat the '}'. 1462 if (Lex.getCode() != tgtok::r_brace) { 1463 TokError("expected '}' at end of bit range list"); 1464 return 0; 1465 } 1466 Lex.Lex(); 1467 break; 1468 } 1469 case tgtok::l_square: { 1470 SMLoc SquareLoc = Lex.getLoc(); 1471 Lex.Lex(); // eat the '[' 1472 std::vector<unsigned> Ranges = ParseRangeList(); 1473 if (Ranges.empty()) return 0; 1474 1475 Result = Result->convertInitListSlice(Ranges); 1476 if (Result == 0) { 1477 Error(SquareLoc, "Invalid range for list slice"); 1478 return 0; 1479 } 1480 1481 // Eat the ']'. 1482 if (Lex.getCode() != tgtok::r_square) { 1483 TokError("expected ']' at end of list slice"); 1484 return 0; 1485 } 1486 Lex.Lex(); 1487 break; 1488 } 1489 case tgtok::period: 1490 if (Lex.Lex() != tgtok::Id) { // eat the . 1491 TokError("expected field identifier after '.'"); 1492 return 0; 1493 } 1494 if (!Result->getFieldType(Lex.getCurStrVal())) { 1495 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 1496 Result->getAsString() + "'"); 1497 return 0; 1498 } 1499 Result = FieldInit::get(Result, Lex.getCurStrVal()); 1500 Lex.Lex(); // eat field name 1501 break; 1502 1503 case tgtok::paste: 1504 SMLoc PasteLoc = Lex.getLoc(); 1505 1506 // Create a !strconcat() operation, first casting each operand to 1507 // a string if necessary. 1508 1509 TypedInit *LHS = dynamic_cast<TypedInit *>(Result); 1510 if (!LHS) { 1511 Error(PasteLoc, "LHS of paste is not typed!"); 1512 return 0; 1513 } 1514 1515 if (LHS->getType() != StringRecTy::get()) { 1516 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()); 1517 } 1518 1519 TypedInit *RHS = 0; 1520 1521 Lex.Lex(); // Eat the '#'. 1522 switch (Lex.getCode()) { 1523 case tgtok::colon: 1524 case tgtok::semi: 1525 case tgtok::l_brace: 1526 // These are all of the tokens that can begin an object body. 1527 // Some of these can also begin values but we disallow those cases 1528 // because they are unlikely to be useful. 1529 1530 // Trailing paste, concat with an empty string. 1531 RHS = StringInit::get(""); 1532 break; 1533 1534 default: 1535 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode); 1536 RHS = dynamic_cast<TypedInit *>(RHSResult); 1537 if (!RHS) { 1538 Error(PasteLoc, "RHS of paste is not typed!"); 1539 return 0; 1540 } 1541 1542 if (RHS->getType() != StringRecTy::get()) { 1543 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()); 1544 } 1545 1546 break; 1547 } 1548 1549 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS, 1550 StringRecTy::get())->Fold(CurRec, CurMultiClass); 1551 break; 1552 } 1553 } 1554 } 1555 1556 /// ParseDagArgList - Parse the argument list for a dag literal expression. 1557 /// 1558 /// ParseDagArgList ::= Value (':' VARNAME)? 1559 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)? 1560 std::vector<std::pair<llvm::Init*, std::string> > 1561 TGParser::ParseDagArgList(Record *CurRec) { 1562 std::vector<std::pair<llvm::Init*, std::string> > Result; 1563 1564 while (1) { 1565 Init *Val = ParseValue(CurRec); 1566 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >(); 1567 1568 // If the variable name is present, add it. 1569 std::string VarName; 1570 if (Lex.getCode() == tgtok::colon) { 1571 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 1572 TokError("expected variable name in dag literal"); 1573 return std::vector<std::pair<llvm::Init*, std::string> >(); 1574 } 1575 VarName = Lex.getCurStrVal(); 1576 Lex.Lex(); // eat the VarName. 1577 } 1578 1579 Result.push_back(std::make_pair(Val, VarName)); 1580 1581 if (Lex.getCode() != tgtok::comma) break; 1582 Lex.Lex(); // eat the ',' 1583 } 1584 1585 return Result; 1586 } 1587 1588 1589 /// ParseValueList - Parse a comma separated list of values, returning them as a 1590 /// vector. Note that this always expects to be able to parse at least one 1591 /// value. It returns an empty list if this is not possible. 1592 /// 1593 /// ValueList ::= Value (',' Value) 1594 /// 1595 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec, 1596 RecTy *EltTy) { 1597 std::vector<Init*> Result; 1598 RecTy *ItemType = EltTy; 1599 unsigned int ArgN = 0; 1600 if (ArgsRec != 0 && EltTy == 0) { 1601 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs(); 1602 if (!TArgs.size()) { 1603 TokError("template argument provided to non-template class"); 1604 return std::vector<Init*>(); 1605 } 1606 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 1607 if (!RV) { 1608 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN] 1609 << ")\n"; 1610 } 1611 assert(RV && "Template argument record not found??"); 1612 ItemType = RV->getType(); 1613 ++ArgN; 1614 } 1615 Result.push_back(ParseValue(CurRec, ItemType)); 1616 if (Result.back() == 0) return std::vector<Init*>(); 1617 1618 while (Lex.getCode() == tgtok::comma) { 1619 Lex.Lex(); // Eat the comma 1620 1621 if (ArgsRec != 0 && EltTy == 0) { 1622 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs(); 1623 if (ArgN >= TArgs.size()) { 1624 TokError("too many template arguments"); 1625 return std::vector<Init*>(); 1626 } 1627 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 1628 assert(RV && "Template argument record not found??"); 1629 ItemType = RV->getType(); 1630 ++ArgN; 1631 } 1632 Result.push_back(ParseValue(CurRec, ItemType)); 1633 if (Result.back() == 0) return std::vector<Init*>(); 1634 } 1635 1636 return Result; 1637 } 1638 1639 1640 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an 1641 /// empty string on error. This can happen in a number of different context's, 1642 /// including within a def or in the template args for a def (which which case 1643 /// CurRec will be non-null) and within the template args for a multiclass (in 1644 /// which case CurRec will be null, but CurMultiClass will be set). This can 1645 /// also happen within a def that is within a multiclass, which will set both 1646 /// CurRec and CurMultiClass. 1647 /// 1648 /// Declaration ::= FIELD? Type ID ('=' Value)? 1649 /// 1650 Init *TGParser::ParseDeclaration(Record *CurRec, 1651 bool ParsingTemplateArgs) { 1652 // Read the field prefix if present. 1653 bool HasField = Lex.getCode() == tgtok::Field; 1654 if (HasField) Lex.Lex(); 1655 1656 RecTy *Type = ParseType(); 1657 if (Type == 0) return 0; 1658 1659 if (Lex.getCode() != tgtok::Id) { 1660 TokError("Expected identifier in declaration"); 1661 return 0; 1662 } 1663 1664 SMLoc IdLoc = Lex.getLoc(); 1665 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 1666 Lex.Lex(); 1667 1668 if (ParsingTemplateArgs) { 1669 if (CurRec) { 1670 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 1671 } else { 1672 assert(CurMultiClass); 1673 } 1674 if (CurMultiClass) 1675 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, 1676 "::"); 1677 } 1678 1679 // Add the value. 1680 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField))) 1681 return 0; 1682 1683 // If a value is present, parse it. 1684 if (Lex.getCode() == tgtok::equal) { 1685 Lex.Lex(); 1686 SMLoc ValLoc = Lex.getLoc(); 1687 Init *Val = ParseValue(CurRec, Type); 1688 if (Val == 0 || 1689 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val)) 1690 return 0; 1691 } 1692 1693 return DeclName; 1694 } 1695 1696 /// ParseForeachDeclaration - Read a foreach declaration, returning 1697 /// the name of the declared object or a NULL Init on error. Return 1698 /// the name of the parsed initializer list through ForeachListName. 1699 /// 1700 /// ForeachDeclaration ::= ID '=' '[' ValueList ']' 1701 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 1702 /// ForeachDeclaration ::= ID '=' RangePiece 1703 /// 1704 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) { 1705 if (Lex.getCode() != tgtok::Id) { 1706 TokError("Expected identifier in foreach declaration"); 1707 return 0; 1708 } 1709 1710 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 1711 Lex.Lex(); 1712 1713 // If a value is present, parse it. 1714 if (Lex.getCode() != tgtok::equal) { 1715 TokError("Expected '=' in foreach declaration"); 1716 return 0; 1717 } 1718 Lex.Lex(); // Eat the '=' 1719 1720 RecTy *IterType = 0; 1721 std::vector<unsigned> Ranges; 1722 1723 switch (Lex.getCode()) { 1724 default: TokError("Unknown token when expecting a range list"); return 0; 1725 case tgtok::l_square: { // '[' ValueList ']' 1726 Init *List = ParseSimpleValue(0, 0, ParseForeachMode); 1727 ForeachListValue = dynamic_cast<ListInit*>(List); 1728 if (ForeachListValue == 0) { 1729 TokError("Expected a Value list"); 1730 return 0; 1731 } 1732 RecTy *ValueType = ForeachListValue->getType(); 1733 ListRecTy *ListType = dynamic_cast<ListRecTy *>(ValueType); 1734 if (ListType == 0) { 1735 TokError("Value list is not of list type"); 1736 return 0; 1737 } 1738 IterType = ListType->getElementType(); 1739 break; 1740 } 1741 1742 case tgtok::IntVal: { // RangePiece. 1743 if (ParseRangePiece(Ranges)) 1744 return 0; 1745 break; 1746 } 1747 1748 case tgtok::l_brace: { // '{' RangeList '}' 1749 Lex.Lex(); // eat the '{' 1750 Ranges = ParseRangeList(); 1751 if (Lex.getCode() != tgtok::r_brace) { 1752 TokError("expected '}' at end of bit range list"); 1753 return 0; 1754 } 1755 Lex.Lex(); 1756 break; 1757 } 1758 } 1759 1760 if (!Ranges.empty()) { 1761 assert(!IterType && "Type already initialized?"); 1762 IterType = IntRecTy::get(); 1763 std::vector<Init*> Values; 1764 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) 1765 Values.push_back(IntInit::get(Ranges[i])); 1766 ForeachListValue = ListInit::get(Values, IterType); 1767 } 1768 1769 if (!IterType) 1770 return 0; 1771 1772 return VarInit::get(DeclName, IterType); 1773 } 1774 1775 /// ParseTemplateArgList - Read a template argument list, which is a non-empty 1776 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are 1777 /// template args for a def, which may or may not be in a multiclass. If null, 1778 /// these are the template args for a multiclass. 1779 /// 1780 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>' 1781 /// 1782 bool TGParser::ParseTemplateArgList(Record *CurRec) { 1783 assert(Lex.getCode() == tgtok::less && "Not a template arg list!"); 1784 Lex.Lex(); // eat the '<' 1785 1786 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec; 1787 1788 // Read the first declaration. 1789 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 1790 if (TemplArg == 0) 1791 return true; 1792 1793 TheRecToAddTo->addTemplateArg(TemplArg); 1794 1795 while (Lex.getCode() == tgtok::comma) { 1796 Lex.Lex(); // eat the ',' 1797 1798 // Read the following declarations. 1799 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 1800 if (TemplArg == 0) 1801 return true; 1802 TheRecToAddTo->addTemplateArg(TemplArg); 1803 } 1804 1805 if (Lex.getCode() != tgtok::greater) 1806 return TokError("expected '>' at end of template argument list"); 1807 Lex.Lex(); // eat the '>'. 1808 return false; 1809 } 1810 1811 1812 /// ParseBodyItem - Parse a single item at within the body of a def or class. 1813 /// 1814 /// BodyItem ::= Declaration ';' 1815 /// BodyItem ::= LET ID OptionalBitList '=' Value ';' 1816 bool TGParser::ParseBodyItem(Record *CurRec) { 1817 if (Lex.getCode() != tgtok::Let) { 1818 if (ParseDeclaration(CurRec, false) == 0) 1819 return true; 1820 1821 if (Lex.getCode() != tgtok::semi) 1822 return TokError("expected ';' after declaration"); 1823 Lex.Lex(); 1824 return false; 1825 } 1826 1827 // LET ID OptionalRangeList '=' Value ';' 1828 if (Lex.Lex() != tgtok::Id) 1829 return TokError("expected field identifier after let"); 1830 1831 SMLoc IdLoc = Lex.getLoc(); 1832 std::string FieldName = Lex.getCurStrVal(); 1833 Lex.Lex(); // eat the field name. 1834 1835 std::vector<unsigned> BitList; 1836 if (ParseOptionalBitList(BitList)) 1837 return true; 1838 std::reverse(BitList.begin(), BitList.end()); 1839 1840 if (Lex.getCode() != tgtok::equal) 1841 return TokError("expected '=' in let expression"); 1842 Lex.Lex(); // eat the '='. 1843 1844 RecordVal *Field = CurRec->getValue(FieldName); 1845 if (Field == 0) 1846 return TokError("Value '" + FieldName + "' unknown!"); 1847 1848 RecTy *Type = Field->getType(); 1849 1850 Init *Val = ParseValue(CurRec, Type); 1851 if (Val == 0) return true; 1852 1853 if (Lex.getCode() != tgtok::semi) 1854 return TokError("expected ';' after let expression"); 1855 Lex.Lex(); 1856 1857 return SetValue(CurRec, IdLoc, FieldName, BitList, Val); 1858 } 1859 1860 /// ParseBody - Read the body of a class or def. Return true on error, false on 1861 /// success. 1862 /// 1863 /// Body ::= ';' 1864 /// Body ::= '{' BodyList '}' 1865 /// BodyList BodyItem* 1866 /// 1867 bool TGParser::ParseBody(Record *CurRec) { 1868 // If this is a null definition, just eat the semi and return. 1869 if (Lex.getCode() == tgtok::semi) { 1870 Lex.Lex(); 1871 return false; 1872 } 1873 1874 if (Lex.getCode() != tgtok::l_brace) 1875 return TokError("Expected ';' or '{' to start body"); 1876 // Eat the '{'. 1877 Lex.Lex(); 1878 1879 while (Lex.getCode() != tgtok::r_brace) 1880 if (ParseBodyItem(CurRec)) 1881 return true; 1882 1883 // Eat the '}'. 1884 Lex.Lex(); 1885 return false; 1886 } 1887 1888 /// ParseObjectBody - Parse the body of a def or class. This consists of an 1889 /// optional ClassList followed by a Body. CurRec is the current def or class 1890 /// that is being parsed. 1891 /// 1892 /// ObjectBody ::= BaseClassList Body 1893 /// BaseClassList ::= /*empty*/ 1894 /// BaseClassList ::= ':' BaseClassListNE 1895 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)* 1896 /// 1897 bool TGParser::ParseObjectBody(Record *CurRec) { 1898 // If there is a baseclass list, read it. 1899 if (Lex.getCode() == tgtok::colon) { 1900 Lex.Lex(); 1901 1902 // Read all of the subclasses. 1903 SubClassReference SubClass = ParseSubClassReference(CurRec, false); 1904 while (1) { 1905 // Check for error. 1906 if (SubClass.Rec == 0) return true; 1907 1908 // Add it. 1909 if (AddSubClass(CurRec, SubClass)) 1910 return true; 1911 1912 if (Lex.getCode() != tgtok::comma) break; 1913 Lex.Lex(); // eat ','. 1914 SubClass = ParseSubClassReference(CurRec, false); 1915 } 1916 } 1917 1918 // Process any variables on the let stack. 1919 for (unsigned i = 0, e = LetStack.size(); i != e; ++i) 1920 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j) 1921 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name, 1922 LetStack[i][j].Bits, LetStack[i][j].Value)) 1923 return true; 1924 1925 return ParseBody(CurRec); 1926 } 1927 1928 /// ParseDef - Parse and return a top level or multiclass def, return the record 1929 /// corresponding to it. This returns null on error. 1930 /// 1931 /// DefInst ::= DEF ObjectName ObjectBody 1932 /// 1933 bool TGParser::ParseDef(MultiClass *CurMultiClass) { 1934 SMLoc DefLoc = Lex.getLoc(); 1935 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 1936 Lex.Lex(); // Eat the 'def' token. 1937 1938 // Parse ObjectName and make a record for it. 1939 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records); 1940 1941 if (!CurMultiClass && Loops.empty()) { 1942 // Top-level def definition. 1943 1944 // Ensure redefinition doesn't happen. 1945 if (Records.getDef(CurRec->getNameInitAsString())) { 1946 Error(DefLoc, "def '" + CurRec->getNameInitAsString() 1947 + "' already defined"); 1948 return true; 1949 } 1950 Records.addDef(CurRec); 1951 } else if (CurMultiClass) { 1952 // Otherwise, a def inside a multiclass, add it to the multiclass. 1953 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i) 1954 if (CurMultiClass->DefPrototypes[i]->getNameInit() 1955 == CurRec->getNameInit()) { 1956 Error(DefLoc, "def '" + CurRec->getNameInitAsString() + 1957 "' already defined in this multiclass!"); 1958 return true; 1959 } 1960 CurMultiClass->DefPrototypes.push_back(CurRec); 1961 } 1962 1963 if (ParseObjectBody(CurRec)) 1964 return true; 1965 1966 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs. 1967 // See Record::setName(). This resolve step will see any new name 1968 // for the def that might have been created when resolving 1969 // inheritance, values and arguments above. 1970 CurRec->resolveReferences(); 1971 1972 // If ObjectBody has template arguments, it's an error. 1973 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?"); 1974 1975 if (CurMultiClass) { 1976 // Copy the template arguments for the multiclass into the def. 1977 const std::vector<Init *> &TArgs = 1978 CurMultiClass->Rec.getTemplateArgs(); 1979 1980 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 1981 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]); 1982 assert(RV && "Template arg doesn't exist?"); 1983 CurRec->addValue(*RV); 1984 } 1985 } 1986 1987 if (ProcessForeachDefs(CurRec, DefLoc)) { 1988 Error(DefLoc, 1989 "Could not process loops for def" + CurRec->getNameInitAsString()); 1990 return true; 1991 } 1992 1993 return false; 1994 } 1995 1996 /// ParseForeach - Parse a for statement. Return the record corresponding 1997 /// to it. This returns true on error. 1998 /// 1999 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2000 /// Foreach ::= FOREACH Declaration IN Object 2001 /// 2002 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2003 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2004 Lex.Lex(); // Eat the 'for' token. 2005 2006 // Make a temporary object to record items associated with the for 2007 // loop. 2008 ListInit *ListValue = 0; 2009 VarInit *IterName = ParseForeachDeclaration(ListValue); 2010 if (IterName == 0) 2011 return TokError("expected declaration in for"); 2012 2013 if (Lex.getCode() != tgtok::In) 2014 return TokError("Unknown tok"); 2015 Lex.Lex(); // Eat the in 2016 2017 // Create a loop object and remember it. 2018 Loops.push_back(ForeachLoop(IterName, ListValue)); 2019 2020 if (Lex.getCode() != tgtok::l_brace) { 2021 // FOREACH Declaration IN Object 2022 if (ParseObject(CurMultiClass)) 2023 return true; 2024 } 2025 else { 2026 SMLoc BraceLoc = Lex.getLoc(); 2027 // Otherwise, this is a group foreach. 2028 Lex.Lex(); // eat the '{'. 2029 2030 // Parse the object list. 2031 if (ParseObjectList(CurMultiClass)) 2032 return true; 2033 2034 if (Lex.getCode() != tgtok::r_brace) { 2035 TokError("expected '}' at end of foreach command"); 2036 return Error(BraceLoc, "to match this '{'"); 2037 } 2038 Lex.Lex(); // Eat the } 2039 } 2040 2041 // We've processed everything in this loop. 2042 Loops.pop_back(); 2043 2044 return false; 2045 } 2046 2047 /// ParseClass - Parse a tblgen class definition. 2048 /// 2049 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2050 /// 2051 bool TGParser::ParseClass() { 2052 assert(Lex.getCode() == tgtok::Class && "Unexpected token!"); 2053 Lex.Lex(); 2054 2055 if (Lex.getCode() != tgtok::Id) 2056 return TokError("expected class name after 'class' keyword"); 2057 2058 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 2059 if (CurRec) { 2060 // If the body was previously defined, this is an error. 2061 if (CurRec->getValues().size() > 1 || // Account for NAME. 2062 !CurRec->getSuperClasses().empty() || 2063 !CurRec->getTemplateArgs().empty()) 2064 return TokError("Class '" + CurRec->getNameInitAsString() 2065 + "' already defined"); 2066 } else { 2067 // If this is the first reference to this class, create and add it. 2068 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records); 2069 Records.addClass(CurRec); 2070 } 2071 Lex.Lex(); // eat the name. 2072 2073 // If there are template args, parse them. 2074 if (Lex.getCode() == tgtok::less) 2075 if (ParseTemplateArgList(CurRec)) 2076 return true; 2077 2078 // Finally, parse the object body. 2079 return ParseObjectBody(CurRec); 2080 } 2081 2082 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 2083 /// of LetRecords. 2084 /// 2085 /// LetList ::= LetItem (',' LetItem)* 2086 /// LetItem ::= ID OptionalRangeList '=' Value 2087 /// 2088 std::vector<LetRecord> TGParser::ParseLetList() { 2089 std::vector<LetRecord> Result; 2090 2091 while (1) { 2092 if (Lex.getCode() != tgtok::Id) { 2093 TokError("expected identifier in let definition"); 2094 return std::vector<LetRecord>(); 2095 } 2096 std::string Name = Lex.getCurStrVal(); 2097 SMLoc NameLoc = Lex.getLoc(); 2098 Lex.Lex(); // Eat the identifier. 2099 2100 // Check for an optional RangeList. 2101 std::vector<unsigned> Bits; 2102 if (ParseOptionalRangeList(Bits)) 2103 return std::vector<LetRecord>(); 2104 std::reverse(Bits.begin(), Bits.end()); 2105 2106 if (Lex.getCode() != tgtok::equal) { 2107 TokError("expected '=' in let expression"); 2108 return std::vector<LetRecord>(); 2109 } 2110 Lex.Lex(); // eat the '='. 2111 2112 Init *Val = ParseValue(0); 2113 if (Val == 0) return std::vector<LetRecord>(); 2114 2115 // Now that we have everything, add the record. 2116 Result.push_back(LetRecord(Name, Bits, Val, NameLoc)); 2117 2118 if (Lex.getCode() != tgtok::comma) 2119 return Result; 2120 Lex.Lex(); // eat the comma. 2121 } 2122 } 2123 2124 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of 2125 /// different related productions. This works inside multiclasses too. 2126 /// 2127 /// Object ::= LET LetList IN '{' ObjectList '}' 2128 /// Object ::= LET LetList IN Object 2129 /// 2130 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) { 2131 assert(Lex.getCode() == tgtok::Let && "Unexpected token"); 2132 Lex.Lex(); 2133 2134 // Add this entry to the let stack. 2135 std::vector<LetRecord> LetInfo = ParseLetList(); 2136 if (LetInfo.empty()) return true; 2137 LetStack.push_back(LetInfo); 2138 2139 if (Lex.getCode() != tgtok::In) 2140 return TokError("expected 'in' at end of top-level 'let'"); 2141 Lex.Lex(); 2142 2143 // If this is a scalar let, just handle it now 2144 if (Lex.getCode() != tgtok::l_brace) { 2145 // LET LetList IN Object 2146 if (ParseObject(CurMultiClass)) 2147 return true; 2148 } else { // Object ::= LETCommand '{' ObjectList '}' 2149 SMLoc BraceLoc = Lex.getLoc(); 2150 // Otherwise, this is a group let. 2151 Lex.Lex(); // eat the '{'. 2152 2153 // Parse the object list. 2154 if (ParseObjectList(CurMultiClass)) 2155 return true; 2156 2157 if (Lex.getCode() != tgtok::r_brace) { 2158 TokError("expected '}' at end of top level let command"); 2159 return Error(BraceLoc, "to match this '{'"); 2160 } 2161 Lex.Lex(); 2162 } 2163 2164 // Outside this let scope, this let block is not active. 2165 LetStack.pop_back(); 2166 return false; 2167 } 2168 2169 /// ParseMultiClass - Parse a multiclass definition. 2170 /// 2171 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? 2172 /// ':' BaseMultiClassList '{' MultiClassDef+ '}' 2173 /// 2174 bool TGParser::ParseMultiClass() { 2175 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token"); 2176 Lex.Lex(); // Eat the multiclass token. 2177 2178 if (Lex.getCode() != tgtok::Id) 2179 return TokError("expected identifier after multiclass for name"); 2180 std::string Name = Lex.getCurStrVal(); 2181 2182 if (MultiClasses.count(Name)) 2183 return TokError("multiclass '" + Name + "' already defined"); 2184 2185 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 2186 Lex.getLoc(), Records); 2187 Lex.Lex(); // Eat the identifier. 2188 2189 // If there are template args, parse them. 2190 if (Lex.getCode() == tgtok::less) 2191 if (ParseTemplateArgList(0)) 2192 return true; 2193 2194 bool inherits = false; 2195 2196 // If there are submulticlasses, parse them. 2197 if (Lex.getCode() == tgtok::colon) { 2198 inherits = true; 2199 2200 Lex.Lex(); 2201 2202 // Read all of the submulticlasses. 2203 SubMultiClassReference SubMultiClass = 2204 ParseSubMultiClassReference(CurMultiClass); 2205 while (1) { 2206 // Check for error. 2207 if (SubMultiClass.MC == 0) return true; 2208 2209 // Add it. 2210 if (AddSubMultiClass(CurMultiClass, SubMultiClass)) 2211 return true; 2212 2213 if (Lex.getCode() != tgtok::comma) break; 2214 Lex.Lex(); // eat ','. 2215 SubMultiClass = ParseSubMultiClassReference(CurMultiClass); 2216 } 2217 } 2218 2219 if (Lex.getCode() != tgtok::l_brace) { 2220 if (!inherits) 2221 return TokError("expected '{' in multiclass definition"); 2222 else if (Lex.getCode() != tgtok::semi) 2223 return TokError("expected ';' in multiclass definition"); 2224 else 2225 Lex.Lex(); // eat the ';'. 2226 } else { 2227 if (Lex.Lex() == tgtok::r_brace) // eat the '{'. 2228 return TokError("multiclass must contain at least one def"); 2229 2230 while (Lex.getCode() != tgtok::r_brace) { 2231 switch (Lex.getCode()) { 2232 default: 2233 return TokError("expected 'let', 'def' or 'defm' in multiclass body"); 2234 case tgtok::Let: 2235 case tgtok::Def: 2236 case tgtok::Defm: 2237 case tgtok::Foreach: 2238 if (ParseObject(CurMultiClass)) 2239 return true; 2240 break; 2241 } 2242 } 2243 Lex.Lex(); // eat the '}'. 2244 } 2245 2246 CurMultiClass = 0; 2247 return false; 2248 } 2249 2250 Record *TGParser:: 2251 InstantiateMulticlassDef(MultiClass &MC, 2252 Record *DefProto, 2253 Init *DefmPrefix, 2254 SMLoc DefmPrefixLoc) { 2255 // We need to preserve DefProto so it can be reused for later 2256 // instantiations, so create a new Record to inherit from it. 2257 2258 // Add in the defm name. If the defm prefix is empty, give each 2259 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the 2260 // name, substitute the prefix for #NAME#. Otherwise, use the defm name 2261 // as a prefix. 2262 2263 if (DefmPrefix == 0) 2264 DefmPrefix = StringInit::get(GetNewAnonymousName()); 2265 2266 Init *DefName = DefProto->getNameInit(); 2267 2268 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName); 2269 2270 if (DefNameString != 0) { 2271 // We have a fully expanded string so there are no operators to 2272 // resolve. We should concatenate the given prefix and name. 2273 DefName = 2274 BinOpInit::get(BinOpInit::STRCONCAT, 2275 UnOpInit::get(UnOpInit::CAST, DefmPrefix, 2276 StringRecTy::get())->Fold(DefProto, &MC), 2277 DefName, StringRecTy::get())->Fold(DefProto, &MC); 2278 } 2279 2280 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records); 2281 2282 SubClassReference Ref; 2283 Ref.RefLoc = DefmPrefixLoc; 2284 Ref.Rec = DefProto; 2285 AddSubClass(CurRec, Ref); 2286 2287 // Set the value for NAME. We don't resolve references to it 'til later, 2288 // though, so that uses in nested multiclass names don't get 2289 // confused. 2290 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(), 2291 DefmPrefix)) { 2292 Error(DefmPrefixLoc, "Could not resolve " 2293 + CurRec->getNameInitAsString() + ":NAME to '" 2294 + DefmPrefix->getAsUnquotedString() + "'"); 2295 return 0; 2296 } 2297 2298 // If the DefNameString didn't resolve, we probably have a reference to 2299 // NAME and need to replace it. We need to do at least this much greedily, 2300 // otherwise nested multiclasses will end up with incorrect NAME expansions. 2301 if (DefNameString == 0) { 2302 RecordVal *DefNameRV = CurRec->getValue("NAME"); 2303 CurRec->resolveReferencesTo(DefNameRV); 2304 } 2305 2306 if (!CurMultiClass) { 2307 // Now that we're at the top level, resolve all NAME references 2308 // in the resultant defs that weren't in the def names themselves. 2309 RecordVal *DefNameRV = CurRec->getValue("NAME"); 2310 CurRec->resolveReferencesTo(DefNameRV); 2311 2312 // Now that NAME references are resolved and we're at the top level of 2313 // any multiclass expansions, add the record to the RecordKeeper. If we are 2314 // currently in a multiclass, it means this defm appears inside a 2315 // multiclass and its name won't be fully resolvable until we see 2316 // the top-level defm. Therefore, we don't add this to the 2317 // RecordKeeper at this point. If we did we could get duplicate 2318 // defs as more than one probably refers to NAME or some other 2319 // common internal placeholder. 2320 2321 // Ensure redefinition doesn't happen. 2322 if (Records.getDef(CurRec->getNameInitAsString())) { 2323 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() + 2324 "' already defined, instantiating defm with subdef '" + 2325 DefProto->getNameInitAsString() + "'"); 2326 return 0; 2327 } 2328 2329 Records.addDef(CurRec); 2330 } 2331 2332 return CurRec; 2333 } 2334 2335 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC, 2336 Record *CurRec, 2337 SMLoc DefmPrefixLoc, 2338 SMLoc SubClassLoc, 2339 const std::vector<Init *> &TArgs, 2340 std::vector<Init *> &TemplateVals, 2341 bool DeleteArgs) { 2342 // Loop over all of the template arguments, setting them to the specified 2343 // value or leaving them as the default if necessary. 2344 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 2345 // Check if a value is specified for this temp-arg. 2346 if (i < TemplateVals.size()) { 2347 // Set it now. 2348 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(), 2349 TemplateVals[i])) 2350 return true; 2351 2352 // Resolve it next. 2353 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i])); 2354 2355 if (DeleteArgs) 2356 // Now remove it. 2357 CurRec->removeValue(TArgs[i]); 2358 2359 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 2360 return Error(SubClassLoc, "value not specified for template argument #"+ 2361 utostr(i) + " (" + TArgs[i]->getAsUnquotedString() 2362 + ") of multiclassclass '" + MC.Rec.getNameInitAsString() 2363 + "'"); 2364 } 2365 } 2366 return false; 2367 } 2368 2369 bool TGParser::ResolveMulticlassDef(MultiClass &MC, 2370 Record *CurRec, 2371 Record *DefProto, 2372 SMLoc DefmPrefixLoc) { 2373 // If the mdef is inside a 'let' expression, add to each def. 2374 for (unsigned i = 0, e = LetStack.size(); i != e; ++i) 2375 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j) 2376 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name, 2377 LetStack[i][j].Bits, LetStack[i][j].Value)) 2378 return Error(DefmPrefixLoc, "when instantiating this defm"); 2379 2380 // Don't create a top level definition for defm inside multiclasses, 2381 // instead, only update the prototypes and bind the template args 2382 // with the new created definition. 2383 if (CurMultiClass) { 2384 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); 2385 i != e; ++i) 2386 if (CurMultiClass->DefPrototypes[i]->getNameInit() 2387 == CurRec->getNameInit()) 2388 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() + 2389 "' already defined in this multiclass!"); 2390 CurMultiClass->DefPrototypes.push_back(CurRec); 2391 2392 // Copy the template arguments for the multiclass into the new def. 2393 const std::vector<Init *> &TA = 2394 CurMultiClass->Rec.getTemplateArgs(); 2395 2396 for (unsigned i = 0, e = TA.size(); i != e; ++i) { 2397 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]); 2398 assert(RV && "Template arg doesn't exist?"); 2399 CurRec->addValue(*RV); 2400 } 2401 } 2402 2403 return false; 2404 } 2405 2406 /// ParseDefm - Parse the instantiation of a multiclass. 2407 /// 2408 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 2409 /// 2410 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 2411 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 2412 2413 Init *DefmPrefix = 0; 2414 2415 if (Lex.Lex() == tgtok::Id) { // eat the defm. 2416 DefmPrefix = ParseObjectName(CurMultiClass); 2417 } 2418 2419 SMLoc DefmPrefixLoc = Lex.getLoc(); 2420 if (Lex.getCode() != tgtok::colon) 2421 return TokError("expected ':' after defm identifier"); 2422 2423 // Keep track of the new generated record definitions. 2424 std::vector<Record*> NewRecDefs; 2425 2426 // This record also inherits from a regular class (non-multiclass)? 2427 bool InheritFromClass = false; 2428 2429 // eat the colon. 2430 Lex.Lex(); 2431 2432 SMLoc SubClassLoc = Lex.getLoc(); 2433 SubClassReference Ref = ParseSubClassReference(0, true); 2434 2435 while (1) { 2436 if (Ref.Rec == 0) return true; 2437 2438 // To instantiate a multiclass, we need to first get the multiclass, then 2439 // instantiate each def contained in the multiclass with the SubClassRef 2440 // template parameters. 2441 MultiClass *MC = MultiClasses[Ref.Rec->getName()]; 2442 assert(MC && "Didn't lookup multiclass correctly?"); 2443 std::vector<Init*> &TemplateVals = Ref.TemplateArgs; 2444 2445 // Verify that the correct number of template arguments were specified. 2446 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs(); 2447 if (TArgs.size() < TemplateVals.size()) 2448 return Error(SubClassLoc, 2449 "more template args specified than multiclass expects"); 2450 2451 // Loop over all the def's in the multiclass, instantiating each one. 2452 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) { 2453 Record *DefProto = MC->DefPrototypes[i]; 2454 2455 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc); 2456 if (!CurRec) 2457 return true; 2458 2459 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc, 2460 TArgs, TemplateVals, true/*Delete args*/)) 2461 return Error(SubClassLoc, "could not instantiate def"); 2462 2463 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc)) 2464 return Error(SubClassLoc, "could not instantiate def"); 2465 2466 NewRecDefs.push_back(CurRec); 2467 } 2468 2469 2470 if (Lex.getCode() != tgtok::comma) break; 2471 Lex.Lex(); // eat ','. 2472 2473 SubClassLoc = Lex.getLoc(); 2474 2475 // A defm can inherit from regular classes (non-multiclass) as 2476 // long as they come in the end of the inheritance list. 2477 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0); 2478 2479 if (InheritFromClass) 2480 break; 2481 2482 Ref = ParseSubClassReference(0, true); 2483 } 2484 2485 if (InheritFromClass) { 2486 // Process all the classes to inherit as if they were part of a 2487 // regular 'def' and inherit all record values. 2488 SubClassReference SubClass = ParseSubClassReference(0, false); 2489 while (1) { 2490 // Check for error. 2491 if (SubClass.Rec == 0) return true; 2492 2493 // Get the expanded definition prototypes and teach them about 2494 // the record values the current class to inherit has 2495 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) { 2496 Record *CurRec = NewRecDefs[i]; 2497 2498 // Add it. 2499 if (AddSubClass(CurRec, SubClass)) 2500 return true; 2501 2502 // Process any variables on the let stack. 2503 for (unsigned i = 0, e = LetStack.size(); i != e; ++i) 2504 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j) 2505 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name, 2506 LetStack[i][j].Bits, LetStack[i][j].Value)) 2507 return true; 2508 } 2509 2510 if (Lex.getCode() != tgtok::comma) break; 2511 Lex.Lex(); // eat ','. 2512 SubClass = ParseSubClassReference(0, false); 2513 } 2514 } 2515 2516 if (!CurMultiClass) 2517 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) 2518 // See Record::setName(). This resolve step will see any new 2519 // name for the def that might have been created when resolving 2520 // inheritance, values and arguments above. 2521 NewRecDefs[i]->resolveReferences(); 2522 2523 if (Lex.getCode() != tgtok::semi) 2524 return TokError("expected ';' at end of defm"); 2525 Lex.Lex(); 2526 2527 return false; 2528 } 2529 2530 /// ParseObject 2531 /// Object ::= ClassInst 2532 /// Object ::= DefInst 2533 /// Object ::= MultiClassInst 2534 /// Object ::= DefMInst 2535 /// Object ::= LETCommand '{' ObjectList '}' 2536 /// Object ::= LETCommand Object 2537 bool TGParser::ParseObject(MultiClass *MC) { 2538 switch (Lex.getCode()) { 2539 default: 2540 return TokError("Expected class, def, defm, multiclass or let definition"); 2541 case tgtok::Let: return ParseTopLevelLet(MC); 2542 case tgtok::Def: return ParseDef(MC); 2543 case tgtok::Foreach: return ParseForeach(MC); 2544 case tgtok::Defm: return ParseDefm(MC); 2545 case tgtok::Class: return ParseClass(); 2546 case tgtok::MultiClass: return ParseMultiClass(); 2547 } 2548 } 2549 2550 /// ParseObjectList 2551 /// ObjectList :== Object* 2552 bool TGParser::ParseObjectList(MultiClass *MC) { 2553 while (isObjectStart(Lex.getCode())) { 2554 if (ParseObject(MC)) 2555 return true; 2556 } 2557 return false; 2558 } 2559 2560 bool TGParser::ParseFile() { 2561 Lex.Lex(); // Prime the lexer. 2562 if (ParseObjectList()) return true; 2563 2564 // If we have unread input at the end of the file, report it. 2565 if (Lex.getCode() == tgtok::Eof) 2566 return false; 2567 2568 return TokError("Unexpected input at top level"); 2569 } 2570 2571