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