1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Implement the Parser for TableGen. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TGParser.h" 14 #include "llvm/ADT/None.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/Twine.h" 19 #include "llvm/Config/llvm-config.h" 20 #include "llvm/Support/Casting.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "llvm/Support/SourceMgr.h" 25 #include <algorithm> 26 #include <cassert> 27 #include <cstdint> 28 29 using namespace llvm; 30 31 //===----------------------------------------------------------------------===// 32 // Support Code for the Semantic Actions. 33 //===----------------------------------------------------------------------===// 34 35 namespace llvm { 36 37 struct SubClassReference { 38 SMRange RefRange; 39 Record *Rec; 40 SmallVector<Init*, 4> TemplateArgs; 41 42 SubClassReference() : Rec(nullptr) {} 43 44 bool isInvalid() const { return Rec == nullptr; } 45 }; 46 47 struct SubMultiClassReference { 48 SMRange RefRange; 49 MultiClass *MC; 50 SmallVector<Init*, 4> TemplateArgs; 51 52 SubMultiClassReference() : MC(nullptr) {} 53 54 bool isInvalid() const { return MC == nullptr; } 55 void dump() const; 56 }; 57 58 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 59 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const { 60 errs() << "Multiclass:\n"; 61 62 MC->dump(); 63 64 errs() << "Template args:\n"; 65 for (Init *TA : TemplateArgs) 66 TA->dump(); 67 } 68 #endif 69 70 } // end namespace llvm 71 72 static bool checkBitsConcrete(Record &R, const RecordVal &RV) { 73 BitsInit *BV = cast<BitsInit>(RV.getValue()); 74 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) { 75 Init *Bit = BV->getBit(i); 76 bool IsReference = false; 77 if (auto VBI = dyn_cast<VarBitInit>(Bit)) { 78 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) { 79 if (R.getValue(VI->getName())) 80 IsReference = true; 81 } 82 } else if (isa<VarInit>(Bit)) { 83 IsReference = true; 84 } 85 if (!(IsReference || Bit->isConcrete())) 86 return false; 87 } 88 return true; 89 } 90 91 static void checkConcrete(Record &R) { 92 for (const RecordVal &RV : R.getValues()) { 93 // HACK: Disable this check for variables declared with 'field'. This is 94 // done merely because existing targets have legitimate cases of 95 // non-concrete variables in helper defs. Ideally, we'd introduce a 96 // 'maybe' or 'optional' modifier instead of this. 97 if (RV.getPrefix()) 98 continue; 99 100 if (Init *V = RV.getValue()) { 101 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete(); 102 if (!Ok) { 103 PrintError(R.getLoc(), 104 Twine("Initializer of '") + RV.getNameInitAsString() + 105 "' in '" + R.getNameInitAsString() + 106 "' could not be fully resolved: " + 107 RV.getValue()->getAsString()); 108 } 109 } 110 } 111 } 112 113 /// Return an Init with a qualifier prefix referring 114 /// to CurRec's name. 115 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass, 116 Init *Name, StringRef Scoper) { 117 Init *NewName = 118 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper)); 119 NewName = BinOpInit::getStrConcat(NewName, Name); 120 if (CurMultiClass && Scoper != "::") { 121 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(), 122 StringInit::get("::")); 123 NewName = BinOpInit::getStrConcat(Prefix, NewName); 124 } 125 126 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName)) 127 NewName = BinOp->Fold(&CurRec); 128 return NewName; 129 } 130 131 /// Return the qualified version of the implicit 'NAME' template argument. 132 static Init *QualifiedNameOfImplicitName(Record &Rec, 133 MultiClass *MC = nullptr) { 134 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":"); 135 } 136 137 static Init *QualifiedNameOfImplicitName(MultiClass *MC) { 138 return QualifiedNameOfImplicitName(MC->Rec, MC); 139 } 140 141 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) { 142 if (!CurRec) 143 CurRec = &CurMultiClass->Rec; 144 145 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) { 146 // The value already exists in the class, treat this as a set. 147 if (ERV->setValue(RV.getValue())) 148 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" + 149 RV.getType()->getAsString() + "' is incompatible with " + 150 "previous definition of type '" + 151 ERV->getType()->getAsString() + "'"); 152 } else { 153 CurRec->addValue(RV); 154 } 155 return false; 156 } 157 158 /// SetValue - 159 /// Return true on error, false on success. 160 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName, 161 ArrayRef<unsigned> BitList, Init *V, 162 bool AllowSelfAssignment) { 163 if (!V) return false; 164 165 if (!CurRec) CurRec = &CurMultiClass->Rec; 166 167 RecordVal *RV = CurRec->getValue(ValName); 168 if (!RV) 169 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 170 "' unknown!"); 171 172 // Do not allow assignments like 'X = X'. This will just cause infinite loops 173 // in the resolution machinery. 174 if (BitList.empty()) 175 if (VarInit *VI = dyn_cast<VarInit>(V)) 176 if (VI->getNameInit() == ValName && !AllowSelfAssignment) 177 return Error(Loc, "Recursion / self-assignment forbidden"); 178 179 // If we are assigning to a subset of the bits in the value... then we must be 180 // assigning to a field of BitsRecTy, which must have a BitsInit 181 // initializer. 182 // 183 if (!BitList.empty()) { 184 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue()); 185 if (!CurVal) 186 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + 187 "' is not a bits type"); 188 189 // Convert the incoming value to a bits type of the appropriate size... 190 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size())); 191 if (!BI) 192 return Error(Loc, "Initializer is not compatible with bit range"); 193 194 SmallVector<Init *, 16> NewBits(CurVal->getNumBits()); 195 196 // Loop over bits, assigning values as appropriate. 197 for (unsigned i = 0, e = BitList.size(); i != e; ++i) { 198 unsigned Bit = BitList[i]; 199 if (NewBits[Bit]) 200 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" + 201 ValName->getAsUnquotedString() + "' more than once"); 202 NewBits[Bit] = BI->getBit(i); 203 } 204 205 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i) 206 if (!NewBits[i]) 207 NewBits[i] = CurVal->getBit(i); 208 209 V = BitsInit::get(NewBits); 210 } 211 212 if (RV->setValue(V, Loc)) { 213 std::string InitType; 214 if (BitsInit *BI = dyn_cast<BitsInit>(V)) 215 InitType = (Twine("' of type bit initializer with length ") + 216 Twine(BI->getNumBits())).str(); 217 else if (TypedInit *TI = dyn_cast<TypedInit>(V)) 218 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str(); 219 return Error(Loc, "Field '" + ValName->getAsUnquotedString() + 220 "' of type '" + RV->getType()->getAsString() + 221 "' is incompatible with value '" + 222 V->getAsString() + InitType + "'"); 223 } 224 return false; 225 } 226 227 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template 228 /// args as SubClass's template arguments. 229 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) { 230 Record *SC = SubClass.Rec; 231 // Add all of the values in the subclass into the current class. 232 for (const RecordVal &Val : SC->getValues()) 233 if (AddValue(CurRec, SubClass.RefRange.Start, Val)) 234 return true; 235 236 ArrayRef<Init *> TArgs = SC->getTemplateArgs(); 237 238 // Ensure that an appropriate number of template arguments are specified. 239 if (TArgs.size() < SubClass.TemplateArgs.size()) 240 return Error(SubClass.RefRange.Start, 241 "More template args specified than expected"); 242 243 // Loop over all of the template arguments, setting them to the specified 244 // value or leaving them as the default if necessary. 245 MapResolver R(CurRec); 246 247 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 248 if (i < SubClass.TemplateArgs.size()) { 249 // If a value is specified for this template arg, set it now. 250 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i], 251 None, SubClass.TemplateArgs[i])) 252 return true; 253 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) { 254 return Error(SubClass.RefRange.Start, 255 "Value not specified for template argument #" + 256 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 257 ") of subclass '" + SC->getNameInitAsString() + "'!"); 258 } 259 260 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue()); 261 262 CurRec->removeValue(TArgs[i]); 263 } 264 265 Init *Name; 266 if (CurRec->isClass()) 267 Name = 268 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get()); 269 else 270 Name = CurRec->getNameInit(); 271 R.set(QualifiedNameOfImplicitName(*SC), Name); 272 273 CurRec->resolveReferences(R); 274 275 // Since everything went well, we can now set the "superclass" list for the 276 // current record. 277 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses(); 278 for (const auto &SCPair : SCs) { 279 if (CurRec->isSubClassOf(SCPair.first)) 280 return Error(SubClass.RefRange.Start, 281 "Already subclass of '" + SCPair.first->getName() + "'!\n"); 282 CurRec->addSuperClass(SCPair.first, SCPair.second); 283 } 284 285 if (CurRec->isSubClassOf(SC)) 286 return Error(SubClass.RefRange.Start, 287 "Already subclass of '" + SC->getName() + "'!\n"); 288 CurRec->addSuperClass(SC, SubClass.RefRange); 289 return false; 290 } 291 292 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) { 293 if (Entry.Rec) 294 return AddSubClass(Entry.Rec.get(), SubClass); 295 296 for (auto &E : Entry.Loop->Entries) { 297 if (AddSubClass(E, SubClass)) 298 return true; 299 } 300 301 return false; 302 } 303 304 /// AddSubMultiClass - Add SubMultiClass as a subclass to 305 /// CurMC, resolving its template args as SubMultiClass's 306 /// template arguments. 307 bool TGParser::AddSubMultiClass(MultiClass *CurMC, 308 SubMultiClassReference &SubMultiClass) { 309 MultiClass *SMC = SubMultiClass.MC; 310 311 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs(); 312 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size()) 313 return Error(SubMultiClass.RefRange.Start, 314 "More template args specified than expected"); 315 316 // Prepare the mapping of template argument name to value, filling in default 317 // values if necessary. 318 SubstStack TemplateArgs; 319 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) { 320 if (i < SubMultiClass.TemplateArgs.size()) { 321 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]); 322 } else { 323 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue(); 324 if (!Default->isComplete()) { 325 return Error(SubMultiClass.RefRange.Start, 326 "value not specified for template argument #" + Twine(i) + 327 " (" + SMCTArgs[i]->getAsUnquotedString() + 328 ") of multiclass '" + SMC->Rec.getNameInitAsString() + 329 "'"); 330 } 331 TemplateArgs.emplace_back(SMCTArgs[i], Default); 332 } 333 } 334 335 TemplateArgs.emplace_back( 336 QualifiedNameOfImplicitName(SMC), 337 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get())); 338 339 // Add all of the defs in the subclass into the current multiclass. 340 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries); 341 } 342 343 /// Add a record or foreach loop to the current context (global record keeper, 344 /// current inner-most foreach loop, or multiclass). 345 bool TGParser::addEntry(RecordsEntry E) { 346 assert(!E.Rec || !E.Loop); 347 348 if (!Loops.empty()) { 349 Loops.back()->Entries.push_back(std::move(E)); 350 return false; 351 } 352 353 if (E.Loop) { 354 SubstStack Stack; 355 return resolve(*E.Loop, Stack, CurMultiClass == nullptr, 356 CurMultiClass ? &CurMultiClass->Entries : nullptr); 357 } 358 359 if (CurMultiClass) { 360 CurMultiClass->Entries.push_back(std::move(E)); 361 return false; 362 } 363 364 return addDefOne(std::move(E.Rec)); 365 } 366 367 /// Resolve the entries in \p Loop, going over inner loops recursively 368 /// and making the given subsitutions of (name, value) pairs. 369 /// 370 /// The resulting records are stored in \p Dest if non-null. Otherwise, they 371 /// are added to the global record keeper. 372 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs, 373 bool Final, std::vector<RecordsEntry> *Dest, 374 SMLoc *Loc) { 375 MapResolver R; 376 for (const auto &S : Substs) 377 R.set(S.first, S.second); 378 Init *List = Loop.ListValue->resolveReferences(R); 379 auto LI = dyn_cast<ListInit>(List); 380 if (!LI) { 381 if (!Final) { 382 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar, 383 List)); 384 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries, 385 Loc); 386 } 387 388 PrintError(Loop.Loc, Twine("attempting to loop over '") + 389 List->getAsString() + "', expected a list"); 390 return true; 391 } 392 393 bool Error = false; 394 for (auto Elt : *LI) { 395 if (Loop.IterVar) 396 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt); 397 Error = resolve(Loop.Entries, Substs, Final, Dest); 398 if (Loop.IterVar) 399 Substs.pop_back(); 400 if (Error) 401 break; 402 } 403 return Error; 404 } 405 406 /// Resolve the entries in \p Source, going over loops recursively and 407 /// making the given substitutions of (name, value) pairs. 408 /// 409 /// The resulting records are stored in \p Dest if non-null. Otherwise, they 410 /// are added to the global record keeper. 411 bool TGParser::resolve(const std::vector<RecordsEntry> &Source, 412 SubstStack &Substs, bool Final, 413 std::vector<RecordsEntry> *Dest, SMLoc *Loc) { 414 bool Error = false; 415 for (auto &E : Source) { 416 if (E.Loop) { 417 Error = resolve(*E.Loop, Substs, Final, Dest); 418 } else { 419 auto Rec = std::make_unique<Record>(*E.Rec); 420 if (Loc) 421 Rec->appendLoc(*Loc); 422 423 MapResolver R(Rec.get()); 424 for (const auto &S : Substs) 425 R.set(S.first, S.second); 426 Rec->resolveReferences(R); 427 428 if (Dest) 429 Dest->push_back(std::move(Rec)); 430 else 431 Error = addDefOne(std::move(Rec)); 432 } 433 if (Error) 434 break; 435 } 436 return Error; 437 } 438 439 /// Resolve the record fully and add it to the record keeper. 440 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) { 441 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) { 442 if (!Rec->isAnonymous()) { 443 PrintError(Rec->getLoc(), 444 "def already exists: " + Rec->getNameInitAsString()); 445 PrintNote(Prev->getLoc(), "location of previous definition"); 446 return true; 447 } 448 Rec->setName(Records.getNewAnonymousName()); 449 } 450 451 Rec->resolveReferences(); 452 checkConcrete(*Rec); 453 454 if (!isa<StringInit>(Rec->getNameInit())) { 455 PrintError(Rec->getLoc(), Twine("record name '") + 456 Rec->getNameInit()->getAsString() + 457 "' could not be fully resolved"); 458 return true; 459 } 460 461 // If ObjectBody has template arguments, it's an error. 462 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?"); 463 464 for (DefsetRecord *Defset : Defsets) { 465 DefInit *I = Rec->getDefInit(); 466 if (!I->getType()->typeIsA(Defset->EltTy)) { 467 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") + 468 I->getType()->getAsString() + 469 "' to defset"); 470 PrintNote(Defset->Loc, "location of defset declaration"); 471 return true; 472 } 473 Defset->Elements.push_back(I); 474 } 475 476 Records.addDef(std::move(Rec)); 477 return false; 478 } 479 480 //===----------------------------------------------------------------------===// 481 // Parser Code 482 //===----------------------------------------------------------------------===// 483 484 /// isObjectStart - Return true if this is a valid first token for an Object. 485 static bool isObjectStart(tgtok::TokKind K) { 486 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm || 487 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach || 488 K == tgtok::Defset || K == tgtok::Defvar || K == tgtok::If; 489 } 490 491 bool TGParser::consume(tgtok::TokKind K) { 492 if (Lex.getCode() == K) { 493 Lex.Lex(); 494 return true; 495 } 496 return false; 497 } 498 499 /// ParseObjectName - If a valid object name is specified, return it. If no 500 /// name is specified, return the unset initializer. Return nullptr on parse 501 /// error. 502 /// ObjectName ::= Value [ '#' Value ]* 503 /// ObjectName ::= /*empty*/ 504 /// 505 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) { 506 switch (Lex.getCode()) { 507 case tgtok::colon: 508 case tgtok::semi: 509 case tgtok::l_brace: 510 // These are all of the tokens that can begin an object body. 511 // Some of these can also begin values but we disallow those cases 512 // because they are unlikely to be useful. 513 return UnsetInit::get(); 514 default: 515 break; 516 } 517 518 Record *CurRec = nullptr; 519 if (CurMultiClass) 520 CurRec = &CurMultiClass->Rec; 521 522 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode); 523 if (!Name) 524 return nullptr; 525 526 if (CurMultiClass) { 527 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass); 528 HasReferenceResolver R(NameStr); 529 Name->resolveReferences(R); 530 if (!R.found()) 531 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()), 532 Name); 533 } 534 535 return Name; 536 } 537 538 /// ParseClassID - Parse and resolve a reference to a class name. This returns 539 /// null on error. 540 /// 541 /// ClassID ::= ID 542 /// 543 Record *TGParser::ParseClassID() { 544 if (Lex.getCode() != tgtok::Id) { 545 TokError("expected name for ClassID"); 546 return nullptr; 547 } 548 549 Record *Result = Records.getClass(Lex.getCurStrVal()); 550 if (!Result) { 551 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'"); 552 if (MultiClasses[Lex.getCurStrVal()].get()) 553 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" + 554 Lex.getCurStrVal() + "'"); 555 else 556 TokError(Msg); 557 } 558 559 Lex.Lex(); 560 return Result; 561 } 562 563 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name. 564 /// This returns null on error. 565 /// 566 /// MultiClassID ::= ID 567 /// 568 MultiClass *TGParser::ParseMultiClassID() { 569 if (Lex.getCode() != tgtok::Id) { 570 TokError("expected name for MultiClassID"); 571 return nullptr; 572 } 573 574 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get(); 575 if (!Result) 576 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'"); 577 578 Lex.Lex(); 579 return Result; 580 } 581 582 /// ParseSubClassReference - Parse a reference to a subclass or to a templated 583 /// subclass. This returns a SubClassRefTy with a null Record* on error. 584 /// 585 /// SubClassRef ::= ClassID 586 /// SubClassRef ::= ClassID '<' ValueList '>' 587 /// 588 SubClassReference TGParser:: 589 ParseSubClassReference(Record *CurRec, bool isDefm) { 590 SubClassReference Result; 591 Result.RefRange.Start = Lex.getLoc(); 592 593 if (isDefm) { 594 if (MultiClass *MC = ParseMultiClassID()) 595 Result.Rec = &MC->Rec; 596 } else { 597 Result.Rec = ParseClassID(); 598 } 599 if (!Result.Rec) return Result; 600 601 // If there is no template arg list, we're done. 602 if (!consume(tgtok::less)) { 603 Result.RefRange.End = Lex.getLoc(); 604 return Result; 605 } 606 607 if (Lex.getCode() == tgtok::greater) { 608 TokError("subclass reference requires a non-empty list of template values"); 609 Result.Rec = nullptr; 610 return Result; 611 } 612 613 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec); 614 if (Result.TemplateArgs.empty()) { 615 Result.Rec = nullptr; // Error parsing value list. 616 return Result; 617 } 618 619 if (!consume(tgtok::greater)) { 620 TokError("expected '>' in template value list"); 621 Result.Rec = nullptr; 622 return Result; 623 } 624 Result.RefRange.End = Lex.getLoc(); 625 626 return Result; 627 } 628 629 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a 630 /// templated submulticlass. This returns a SubMultiClassRefTy with a null 631 /// Record* on error. 632 /// 633 /// SubMultiClassRef ::= MultiClassID 634 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>' 635 /// 636 SubMultiClassReference TGParser:: 637 ParseSubMultiClassReference(MultiClass *CurMC) { 638 SubMultiClassReference Result; 639 Result.RefRange.Start = Lex.getLoc(); 640 641 Result.MC = ParseMultiClassID(); 642 if (!Result.MC) return Result; 643 644 // If there is no template arg list, we're done. 645 if (!consume(tgtok::less)) { 646 Result.RefRange.End = Lex.getLoc(); 647 return Result; 648 } 649 650 if (Lex.getCode() == tgtok::greater) { 651 TokError("subclass reference requires a non-empty list of template values"); 652 Result.MC = nullptr; 653 return Result; 654 } 655 656 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec); 657 if (Result.TemplateArgs.empty()) { 658 Result.MC = nullptr; // Error parsing value list. 659 return Result; 660 } 661 662 if (!consume(tgtok::greater)) { 663 TokError("expected '>' in template value list"); 664 Result.MC = nullptr; 665 return Result; 666 } 667 Result.RefRange.End = Lex.getLoc(); 668 669 return Result; 670 } 671 672 /// ParseRangePiece - Parse a bit/value range. 673 /// RangePiece ::= INTVAL 674 /// RangePiece ::= INTVAL '...' INTVAL 675 /// RangePiece ::= INTVAL '-' INTVAL 676 /// RangePiece ::= INTVAL INTVAL 677 // The last two forms are deprecated. 678 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges, 679 TypedInit *FirstItem) { 680 Init *CurVal = FirstItem; 681 if (!CurVal) 682 CurVal = ParseValue(nullptr); 683 684 IntInit *II = dyn_cast_or_null<IntInit>(CurVal); 685 if (!II) 686 return TokError("expected integer or bitrange"); 687 688 int64_t Start = II->getValue(); 689 int64_t End; 690 691 if (Start < 0) 692 return TokError("invalid range, cannot be negative"); 693 694 switch (Lex.getCode()) { 695 default: 696 Ranges.push_back(Start); 697 return false; 698 699 case tgtok::dotdotdot: 700 case tgtok::minus: { 701 Lex.Lex(); // eat 702 703 Init *I_End = ParseValue(nullptr); 704 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End); 705 if (!II_End) { 706 TokError("expected integer value as end of range"); 707 return true; 708 } 709 710 End = II_End->getValue(); 711 break; 712 } 713 case tgtok::IntVal: { 714 End = -Lex.getCurIntVal(); 715 Lex.Lex(); 716 break; 717 } 718 } 719 if (End < 0) 720 return TokError("invalid range, cannot be negative"); 721 722 // Add to the range. 723 if (Start < End) 724 for (; Start <= End; ++Start) 725 Ranges.push_back(Start); 726 else 727 for (; Start >= End; --Start) 728 Ranges.push_back(Start); 729 return false; 730 } 731 732 /// ParseRangeList - Parse a list of scalars and ranges into scalar values. 733 /// 734 /// RangeList ::= RangePiece (',' RangePiece)* 735 /// 736 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) { 737 // Parse the first piece. 738 if (ParseRangePiece(Result)) { 739 Result.clear(); 740 return; 741 } 742 while (consume(tgtok::comma)) 743 // Parse the next range piece. 744 if (ParseRangePiece(Result)) { 745 Result.clear(); 746 return; 747 } 748 } 749 750 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing. 751 /// OptionalRangeList ::= '<' RangeList '>' 752 /// OptionalRangeList ::= /*empty*/ 753 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) { 754 SMLoc StartLoc = Lex.getLoc(); 755 if (!consume(tgtok::less)) 756 return false; 757 758 // Parse the range list. 759 ParseRangeList(Ranges); 760 if (Ranges.empty()) return true; 761 762 if (!consume(tgtok::greater)) { 763 TokError("expected '>' at end of range list"); 764 return Error(StartLoc, "to match this '<'"); 765 } 766 return false; 767 } 768 769 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing. 770 /// OptionalBitList ::= '{' RangeList '}' 771 /// OptionalBitList ::= /*empty*/ 772 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) { 773 SMLoc StartLoc = Lex.getLoc(); 774 if (!consume(tgtok::l_brace)) 775 return false; 776 777 // Parse the range list. 778 ParseRangeList(Ranges); 779 if (Ranges.empty()) return true; 780 781 if (!consume(tgtok::r_brace)) { 782 TokError("expected '}' at end of bit list"); 783 return Error(StartLoc, "to match this '{'"); 784 } 785 return false; 786 } 787 788 /// ParseType - Parse and return a tblgen type. This returns null on error. 789 /// 790 /// Type ::= STRING // string type 791 /// Type ::= CODE // code type 792 /// Type ::= BIT // bit type 793 /// Type ::= BITS '<' INTVAL '>' // bits<x> type 794 /// Type ::= INT // int type 795 /// Type ::= LIST '<' Type '>' // list<x> type 796 /// Type ::= DAG // dag type 797 /// Type ::= ClassID // Record Type 798 /// 799 RecTy *TGParser::ParseType() { 800 switch (Lex.getCode()) { 801 default: TokError("Unknown token when expecting a type"); return nullptr; 802 case tgtok::String: Lex.Lex(); return StringRecTy::get(); 803 case tgtok::Code: Lex.Lex(); return CodeRecTy::get(); 804 case tgtok::Bit: Lex.Lex(); return BitRecTy::get(); 805 case tgtok::Int: Lex.Lex(); return IntRecTy::get(); 806 case tgtok::Dag: Lex.Lex(); return DagRecTy::get(); 807 case tgtok::Id: 808 if (Record *R = ParseClassID()) return RecordRecTy::get(R); 809 TokError("unknown class name"); 810 return nullptr; 811 case tgtok::Bits: { 812 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 813 TokError("expected '<' after bits type"); 814 return nullptr; 815 } 816 if (Lex.Lex() != tgtok::IntVal) { // Eat '<' 817 TokError("expected integer in bits<n> type"); 818 return nullptr; 819 } 820 uint64_t Val = Lex.getCurIntVal(); 821 if (Lex.Lex() != tgtok::greater) { // Eat count. 822 TokError("expected '>' at end of bits<n> type"); 823 return nullptr; 824 } 825 Lex.Lex(); // Eat '>' 826 return BitsRecTy::get(Val); 827 } 828 case tgtok::List: { 829 if (Lex.Lex() != tgtok::less) { // Eat 'bits' 830 TokError("expected '<' after list type"); 831 return nullptr; 832 } 833 Lex.Lex(); // Eat '<' 834 RecTy *SubType = ParseType(); 835 if (!SubType) return nullptr; 836 837 if (!consume(tgtok::greater)) { 838 TokError("expected '>' at end of list<ty> type"); 839 return nullptr; 840 } 841 return ListRecTy::get(SubType); 842 } 843 } 844 } 845 846 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID 847 /// has already been read. 848 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc, 849 IDParseMode Mode) { 850 if (CurRec) { 851 if (const RecordVal *RV = CurRec->getValue(Name)) 852 return VarInit::get(Name, RV->getType()); 853 } 854 855 if ((CurRec && CurRec->isClass()) || CurMultiClass) { 856 Init *TemplateArgName; 857 if (CurMultiClass) { 858 TemplateArgName = 859 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::"); 860 } else 861 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":"); 862 863 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec; 864 if (TemplateRec->isTemplateArg(TemplateArgName)) { 865 const RecordVal *RV = TemplateRec->getValue(TemplateArgName); 866 assert(RV && "Template arg doesn't exist??"); 867 return VarInit::get(TemplateArgName, RV->getType()); 868 } else if (Name->getValue() == "NAME") { 869 return VarInit::get(TemplateArgName, StringRecTy::get()); 870 } 871 } 872 873 if (CurLocalScope) 874 if (Init *I = CurLocalScope->getVar(Name->getValue())) 875 return I; 876 877 // If this is in a foreach loop, make sure it's not a loop iterator 878 for (const auto &L : Loops) { 879 if (L->IterVar) { 880 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar); 881 if (IterVar && IterVar->getNameInit() == Name) 882 return IterVar; 883 } 884 } 885 886 if (Mode == ParseNameMode) 887 return Name; 888 889 if (Init *I = Records.getGlobal(Name->getValue())) 890 return I; 891 892 // Allow self-references of concrete defs, but delay the lookup so that we 893 // get the correct type. 894 if (CurRec && !CurRec->isClass() && !CurMultiClass && 895 CurRec->getNameInit() == Name) 896 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType()); 897 898 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'"); 899 return nullptr; 900 } 901 902 /// ParseOperation - Parse an operator. This returns null on error. 903 /// 904 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')' 905 /// 906 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) { 907 switch (Lex.getCode()) { 908 default: 909 TokError("unknown operation"); 910 return nullptr; 911 case tgtok::XNOT: 912 case tgtok::XHead: 913 case tgtok::XTail: 914 case tgtok::XSize: 915 case tgtok::XEmpty: 916 case tgtok::XCast: 917 case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')' 918 UnOpInit::UnaryOp Code; 919 RecTy *Type = nullptr; 920 921 switch (Lex.getCode()) { 922 default: llvm_unreachable("Unhandled code!"); 923 case tgtok::XCast: 924 Lex.Lex(); // eat the operation 925 Code = UnOpInit::CAST; 926 927 Type = ParseOperatorType(); 928 929 if (!Type) { 930 TokError("did not get type for unary operator"); 931 return nullptr; 932 } 933 934 break; 935 case tgtok::XNOT: 936 Lex.Lex(); // eat the operation 937 Code = UnOpInit::NOT; 938 Type = IntRecTy::get(); 939 break; 940 case tgtok::XHead: 941 Lex.Lex(); // eat the operation 942 Code = UnOpInit::HEAD; 943 break; 944 case tgtok::XTail: 945 Lex.Lex(); // eat the operation 946 Code = UnOpInit::TAIL; 947 break; 948 case tgtok::XSize: 949 Lex.Lex(); 950 Code = UnOpInit::SIZE; 951 Type = IntRecTy::get(); 952 break; 953 case tgtok::XEmpty: 954 Lex.Lex(); // eat the operation 955 Code = UnOpInit::EMPTY; 956 Type = IntRecTy::get(); 957 break; 958 case tgtok::XGetDagOp: 959 Lex.Lex(); // eat the operation 960 if (Lex.getCode() == tgtok::less) { 961 // Parse an optional type suffix, so that you can say 962 // !getdagop<BaseClass>(someDag) as a shorthand for 963 // !cast<BaseClass>(!getdagop(someDag)). 964 Type = ParseOperatorType(); 965 966 if (!Type) { 967 TokError("did not get type for unary operator"); 968 return nullptr; 969 } 970 971 if (!isa<RecordRecTy>(Type)) { 972 TokError("type for !getdagop must be a record type"); 973 // but keep parsing, to consume the operand 974 } 975 } else { 976 Type = RecordRecTy::get({}); 977 } 978 Code = UnOpInit::GETDAGOP; 979 break; 980 } 981 if (!consume(tgtok::l_paren)) { 982 TokError("expected '(' after unary operator"); 983 return nullptr; 984 } 985 986 Init *LHS = ParseValue(CurRec); 987 if (!LHS) return nullptr; 988 989 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) { 990 ListInit *LHSl = dyn_cast<ListInit>(LHS); 991 StringInit *LHSs = dyn_cast<StringInit>(LHS); 992 DagInit *LHSd = dyn_cast<DagInit>(LHS); 993 TypedInit *LHSt = dyn_cast<TypedInit>(LHS); 994 if (!LHSl && !LHSs && !LHSd && !LHSt) { 995 TokError("expected string, list, or dag type argument in unary operator"); 996 return nullptr; 997 } 998 if (LHSt) { 999 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1000 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType()); 1001 DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType()); 1002 if (!LType && !SType && !DType) { 1003 TokError("expected string, list, or dag type argument in unary operator"); 1004 return nullptr; 1005 } 1006 } 1007 } 1008 1009 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) { 1010 ListInit *LHSl = dyn_cast<ListInit>(LHS); 1011 TypedInit *LHSt = dyn_cast<TypedInit>(LHS); 1012 if (!LHSl && !LHSt) { 1013 TokError("expected list type argument in unary operator"); 1014 return nullptr; 1015 } 1016 if (LHSt) { 1017 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1018 if (!LType) { 1019 TokError("expected list type argument in unary operator"); 1020 return nullptr; 1021 } 1022 } 1023 1024 if (LHSl && LHSl->empty()) { 1025 TokError("empty list argument in unary operator"); 1026 return nullptr; 1027 } 1028 if (LHSl) { 1029 Init *Item = LHSl->getElement(0); 1030 TypedInit *Itemt = dyn_cast<TypedInit>(Item); 1031 if (!Itemt) { 1032 TokError("untyped list element in unary operator"); 1033 return nullptr; 1034 } 1035 Type = (Code == UnOpInit::HEAD) ? Itemt->getType() 1036 : ListRecTy::get(Itemt->getType()); 1037 } else { 1038 assert(LHSt && "expected list type argument in unary operator"); 1039 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1040 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType; 1041 } 1042 } 1043 1044 if (!consume(tgtok::r_paren)) { 1045 TokError("expected ')' in unary operator"); 1046 return nullptr; 1047 } 1048 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec); 1049 } 1050 1051 case tgtok::XIsA: { 1052 // Value ::= !isa '<' Type '>' '(' Value ')' 1053 Lex.Lex(); // eat the operation 1054 1055 RecTy *Type = ParseOperatorType(); 1056 if (!Type) 1057 return nullptr; 1058 1059 if (!consume(tgtok::l_paren)) { 1060 TokError("expected '(' after type of !isa"); 1061 return nullptr; 1062 } 1063 1064 Init *LHS = ParseValue(CurRec); 1065 if (!LHS) 1066 return nullptr; 1067 1068 if (!consume(tgtok::r_paren)) { 1069 TokError("expected ')' in !isa"); 1070 return nullptr; 1071 } 1072 1073 return (IsAOpInit::get(Type, LHS))->Fold(); 1074 } 1075 1076 case tgtok::XConcat: 1077 case tgtok::XADD: 1078 case tgtok::XMUL: 1079 case tgtok::XAND: 1080 case tgtok::XOR: 1081 case tgtok::XXOR: 1082 case tgtok::XSRA: 1083 case tgtok::XSRL: 1084 case tgtok::XSHL: 1085 case tgtok::XEq: 1086 case tgtok::XNe: 1087 case tgtok::XLe: 1088 case tgtok::XLt: 1089 case tgtok::XGe: 1090 case tgtok::XGt: 1091 case tgtok::XListConcat: 1092 case tgtok::XListSplat: 1093 case tgtok::XStrConcat: 1094 case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')' 1095 tgtok::TokKind OpTok = Lex.getCode(); 1096 SMLoc OpLoc = Lex.getLoc(); 1097 Lex.Lex(); // eat the operation 1098 1099 BinOpInit::BinaryOp Code; 1100 switch (OpTok) { 1101 default: llvm_unreachable("Unhandled code!"); 1102 case tgtok::XConcat: Code = BinOpInit::CONCAT; break; 1103 case tgtok::XADD: Code = BinOpInit::ADD; break; 1104 case tgtok::XMUL: Code = BinOpInit::MUL; break; 1105 case tgtok::XAND: Code = BinOpInit::AND; break; 1106 case tgtok::XOR: Code = BinOpInit::OR; break; 1107 case tgtok::XXOR: Code = BinOpInit::XOR; break; 1108 case tgtok::XSRA: Code = BinOpInit::SRA; break; 1109 case tgtok::XSRL: Code = BinOpInit::SRL; break; 1110 case tgtok::XSHL: Code = BinOpInit::SHL; break; 1111 case tgtok::XEq: Code = BinOpInit::EQ; break; 1112 case tgtok::XNe: Code = BinOpInit::NE; break; 1113 case tgtok::XLe: Code = BinOpInit::LE; break; 1114 case tgtok::XLt: Code = BinOpInit::LT; break; 1115 case tgtok::XGe: Code = BinOpInit::GE; break; 1116 case tgtok::XGt: Code = BinOpInit::GT; break; 1117 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break; 1118 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break; 1119 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break; 1120 case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break; 1121 } 1122 1123 RecTy *Type = nullptr; 1124 RecTy *ArgType = nullptr; 1125 switch (OpTok) { 1126 default: 1127 llvm_unreachable("Unhandled code!"); 1128 case tgtok::XConcat: 1129 case tgtok::XSetDagOp: 1130 Type = DagRecTy::get(); 1131 ArgType = DagRecTy::get(); 1132 break; 1133 case tgtok::XAND: 1134 case tgtok::XOR: 1135 case tgtok::XXOR: 1136 case tgtok::XSRA: 1137 case tgtok::XSRL: 1138 case tgtok::XSHL: 1139 case tgtok::XADD: 1140 case tgtok::XMUL: 1141 Type = IntRecTy::get(); 1142 ArgType = IntRecTy::get(); 1143 break; 1144 case tgtok::XEq: 1145 case tgtok::XNe: 1146 Type = BitRecTy::get(); 1147 // ArgType for Eq / Ne is not known at this point 1148 break; 1149 case tgtok::XLe: 1150 case tgtok::XLt: 1151 case tgtok::XGe: 1152 case tgtok::XGt: 1153 Type = BitRecTy::get(); 1154 ArgType = IntRecTy::get(); 1155 break; 1156 case tgtok::XListConcat: 1157 // We don't know the list type until we parse the first argument 1158 ArgType = ItemType; 1159 break; 1160 case tgtok::XListSplat: 1161 // Can't do any typechecking until we parse the first argument. 1162 break; 1163 case tgtok::XStrConcat: 1164 Type = StringRecTy::get(); 1165 ArgType = StringRecTy::get(); 1166 break; 1167 } 1168 1169 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) { 1170 Error(OpLoc, Twine("expected value of type '") + 1171 ItemType->getAsString() + "', got '" + 1172 Type->getAsString() + "'"); 1173 return nullptr; 1174 } 1175 1176 if (!consume(tgtok::l_paren)) { 1177 TokError("expected '(' after binary operator"); 1178 return nullptr; 1179 } 1180 1181 SmallVector<Init*, 2> InitList; 1182 1183 for (;;) { 1184 SMLoc InitLoc = Lex.getLoc(); 1185 InitList.push_back(ParseValue(CurRec, ArgType)); 1186 if (!InitList.back()) return nullptr; 1187 1188 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back()); 1189 if (!InitListBack) { 1190 Error(OpLoc, Twine("expected value to be a typed value, got '" + 1191 InitList.back()->getAsString() + "'")); 1192 return nullptr; 1193 } 1194 RecTy *ListType = InitListBack->getType(); 1195 if (!ArgType) { 1196 ArgType = ListType; 1197 1198 switch (Code) { 1199 case BinOpInit::LISTCONCAT: 1200 if (!isa<ListRecTy>(ArgType)) { 1201 Error(InitLoc, Twine("expected a list, got value of type '") + 1202 ArgType->getAsString() + "'"); 1203 return nullptr; 1204 } 1205 break; 1206 case BinOpInit::LISTSPLAT: 1207 if (ItemType && InitList.size() == 1) { 1208 if (!isa<ListRecTy>(ItemType)) { 1209 Error(OpLoc, 1210 Twine("expected output type to be a list, got type '") + 1211 ItemType->getAsString() + "'"); 1212 return nullptr; 1213 } 1214 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) { 1215 Error(OpLoc, Twine("expected first arg type to be '") + 1216 ArgType->getAsString() + 1217 "', got value of type '" + 1218 cast<ListRecTy>(ItemType) 1219 ->getElementType() 1220 ->getAsString() + 1221 "'"); 1222 return nullptr; 1223 } 1224 } 1225 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) { 1226 Error(InitLoc, Twine("expected second parameter to be an int, got " 1227 "value of type '") + 1228 ArgType->getAsString() + "'"); 1229 return nullptr; 1230 } 1231 ArgType = nullptr; // Broken invariant: types not identical. 1232 break; 1233 case BinOpInit::EQ: 1234 case BinOpInit::NE: 1235 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) && 1236 !ArgType->typeIsConvertibleTo(StringRecTy::get())) { 1237 Error(InitLoc, Twine("expected int, bits, or string; got value of " 1238 "type '") + ArgType->getAsString() + "'"); 1239 return nullptr; 1240 } 1241 break; 1242 default: llvm_unreachable("other ops have fixed argument types"); 1243 } 1244 } else { 1245 RecTy *Resolved = resolveTypes(ArgType, ListType); 1246 if (!Resolved) { 1247 Error(InitLoc, Twine("expected value of type '") + 1248 ArgType->getAsString() + "', got '" + 1249 ListType->getAsString() + "'"); 1250 return nullptr; 1251 } 1252 if (Code != BinOpInit::ADD && Code != BinOpInit::AND && 1253 Code != BinOpInit::OR && Code != BinOpInit::XOR && 1254 Code != BinOpInit::SRA && Code != BinOpInit::SRL && 1255 Code != BinOpInit::SHL && Code != BinOpInit::MUL) 1256 ArgType = Resolved; 1257 } 1258 1259 // Deal with BinOps whose arguments have different types, by 1260 // rewriting ArgType in between them. 1261 switch (Code) { 1262 case BinOpInit::SETDAGOP: 1263 // After parsing the first dag argument, switch to expecting 1264 // a record, with no restriction on its superclasses. 1265 ArgType = RecordRecTy::get({}); 1266 break; 1267 default: 1268 break; 1269 } 1270 1271 if (!consume(tgtok::comma)) 1272 break; 1273 } 1274 1275 if (!consume(tgtok::r_paren)) { 1276 TokError("expected ')' in operator"); 1277 return nullptr; 1278 } 1279 1280 // listconcat returns a list with type of the argument. 1281 if (Code == BinOpInit::LISTCONCAT) 1282 Type = ArgType; 1283 // listsplat returns a list of type of the *first* argument. 1284 if (Code == BinOpInit::LISTSPLAT) 1285 Type = cast<TypedInit>(InitList.front())->getType()->getListTy(); 1286 1287 // We allow multiple operands to associative operators like !strconcat as 1288 // shorthand for nesting them. 1289 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT || 1290 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD || 1291 Code == BinOpInit::AND || Code == BinOpInit::OR || 1292 Code == BinOpInit::XOR || Code == BinOpInit::MUL) { 1293 while (InitList.size() > 2) { 1294 Init *RHS = InitList.pop_back_val(); 1295 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec); 1296 InitList.back() = RHS; 1297 } 1298 } 1299 1300 if (InitList.size() == 2) 1301 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 1302 ->Fold(CurRec); 1303 1304 Error(OpLoc, "expected two operands to operator"); 1305 return nullptr; 1306 } 1307 1308 case tgtok::XForEach: { 1309 // Value ::= !foreach '(' Id ',' Value ',' Value ')' 1310 SMLoc OpLoc = Lex.getLoc(); 1311 Lex.Lex(); // eat the operation 1312 if (Lex.getCode() != tgtok::l_paren) { 1313 TokError("expected '(' after !foreach"); 1314 return nullptr; 1315 } 1316 1317 if (Lex.Lex() != tgtok::Id) { // eat the '(' 1318 TokError("first argument of !foreach must be an identifier"); 1319 return nullptr; 1320 } 1321 1322 Init *LHS = StringInit::get(Lex.getCurStrVal()); 1323 Lex.Lex(); 1324 1325 if (CurRec && CurRec->getValue(LHS)) { 1326 TokError((Twine("iteration variable '") + LHS->getAsString() + 1327 "' already defined") 1328 .str()); 1329 return nullptr; 1330 } 1331 1332 if (!consume(tgtok::comma)) { // eat the id 1333 TokError("expected ',' in ternary operator"); 1334 return nullptr; 1335 } 1336 1337 Init *MHS = ParseValue(CurRec); 1338 if (!MHS) 1339 return nullptr; 1340 1341 if (!consume(tgtok::comma)) { 1342 TokError("expected ',' in ternary operator"); 1343 return nullptr; 1344 } 1345 1346 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1347 if (!MHSt) { 1348 TokError("could not get type of !foreach input"); 1349 return nullptr; 1350 } 1351 1352 RecTy *InEltType = nullptr; 1353 RecTy *OutEltType = nullptr; 1354 bool IsDAG = false; 1355 1356 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) { 1357 InEltType = InListTy->getElementType(); 1358 if (ItemType) { 1359 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) { 1360 OutEltType = OutListTy->getElementType(); 1361 } else { 1362 Error(OpLoc, 1363 "expected value of type '" + Twine(ItemType->getAsString()) + 1364 "', but got !foreach of list type"); 1365 return nullptr; 1366 } 1367 } 1368 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) { 1369 InEltType = InDagTy; 1370 if (ItemType && !isa<DagRecTy>(ItemType)) { 1371 Error(OpLoc, 1372 "expected value of type '" + Twine(ItemType->getAsString()) + 1373 "', but got !foreach of dag type"); 1374 return nullptr; 1375 } 1376 IsDAG = true; 1377 } else { 1378 TokError("!foreach must have list or dag input"); 1379 return nullptr; 1380 } 1381 1382 // We need to create a temporary record to provide a scope for the 1383 // iteration variable. 1384 std::unique_ptr<Record> ParseRecTmp; 1385 Record *ParseRec = CurRec; 1386 if (!ParseRec) { 1387 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1388 ParseRec = ParseRecTmp.get(); 1389 } 1390 1391 ParseRec->addValue(RecordVal(LHS, InEltType, false)); 1392 Init *RHS = ParseValue(ParseRec, OutEltType); 1393 ParseRec->removeValue(LHS); 1394 if (!RHS) 1395 return nullptr; 1396 1397 if (!consume(tgtok::r_paren)) { 1398 TokError("expected ')' in binary operator"); 1399 return nullptr; 1400 } 1401 1402 RecTy *OutType; 1403 if (IsDAG) { 1404 OutType = InEltType; 1405 } else { 1406 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1407 if (!RHSt) { 1408 TokError("could not get type of !foreach result"); 1409 return nullptr; 1410 } 1411 OutType = RHSt->getType()->getListTy(); 1412 } 1413 1414 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType)) 1415 ->Fold(CurRec); 1416 } 1417 1418 case tgtok::XDag: 1419 case tgtok::XIf: 1420 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1421 TernOpInit::TernaryOp Code; 1422 RecTy *Type = nullptr; 1423 1424 tgtok::TokKind LexCode = Lex.getCode(); 1425 Lex.Lex(); // eat the operation 1426 switch (LexCode) { 1427 default: llvm_unreachable("Unhandled code!"); 1428 case tgtok::XDag: 1429 Code = TernOpInit::DAG; 1430 Type = DagRecTy::get(); 1431 ItemType = nullptr; 1432 break; 1433 case tgtok::XIf: 1434 Code = TernOpInit::IF; 1435 break; 1436 case tgtok::XSubst: 1437 Code = TernOpInit::SUBST; 1438 break; 1439 } 1440 if (!consume(tgtok::l_paren)) { 1441 TokError("expected '(' after ternary operator"); 1442 return nullptr; 1443 } 1444 1445 Init *LHS = ParseValue(CurRec); 1446 if (!LHS) return nullptr; 1447 1448 if (!consume(tgtok::comma)) { 1449 TokError("expected ',' in ternary operator"); 1450 return nullptr; 1451 } 1452 1453 SMLoc MHSLoc = Lex.getLoc(); 1454 Init *MHS = ParseValue(CurRec, ItemType); 1455 if (!MHS) 1456 return nullptr; 1457 1458 if (!consume(tgtok::comma)) { 1459 TokError("expected ',' in ternary operator"); 1460 return nullptr; 1461 } 1462 1463 SMLoc RHSLoc = Lex.getLoc(); 1464 Init *RHS = ParseValue(CurRec, ItemType); 1465 if (!RHS) 1466 return nullptr; 1467 1468 if (!consume(tgtok::r_paren)) { 1469 TokError("expected ')' in binary operator"); 1470 return nullptr; 1471 } 1472 1473 switch (LexCode) { 1474 default: llvm_unreachable("Unhandled code!"); 1475 case tgtok::XDag: { 1476 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1477 if (!MHSt && !isa<UnsetInit>(MHS)) { 1478 Error(MHSLoc, "could not determine type of the child list in !dag"); 1479 return nullptr; 1480 } 1481 if (MHSt && !isa<ListRecTy>(MHSt->getType())) { 1482 Error(MHSLoc, Twine("expected list of children, got type '") + 1483 MHSt->getType()->getAsString() + "'"); 1484 return nullptr; 1485 } 1486 1487 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1488 if (!RHSt && !isa<UnsetInit>(RHS)) { 1489 Error(RHSLoc, "could not determine type of the name list in !dag"); 1490 return nullptr; 1491 } 1492 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) { 1493 Error(RHSLoc, Twine("expected list<string>, got type '") + 1494 RHSt->getType()->getAsString() + "'"); 1495 return nullptr; 1496 } 1497 1498 if (!MHSt && !RHSt) { 1499 Error(MHSLoc, 1500 "cannot have both unset children and unset names in !dag"); 1501 return nullptr; 1502 } 1503 break; 1504 } 1505 case tgtok::XIf: { 1506 RecTy *MHSTy = nullptr; 1507 RecTy *RHSTy = nullptr; 1508 1509 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS)) 1510 MHSTy = MHSt->getType(); 1511 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS)) 1512 MHSTy = BitsRecTy::get(MHSbits->getNumBits()); 1513 if (isa<BitInit>(MHS)) 1514 MHSTy = BitRecTy::get(); 1515 1516 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS)) 1517 RHSTy = RHSt->getType(); 1518 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS)) 1519 RHSTy = BitsRecTy::get(RHSbits->getNumBits()); 1520 if (isa<BitInit>(RHS)) 1521 RHSTy = BitRecTy::get(); 1522 1523 // For UnsetInit, it's typed from the other hand. 1524 if (isa<UnsetInit>(MHS)) 1525 MHSTy = RHSTy; 1526 if (isa<UnsetInit>(RHS)) 1527 RHSTy = MHSTy; 1528 1529 if (!MHSTy || !RHSTy) { 1530 TokError("could not get type for !if"); 1531 return nullptr; 1532 } 1533 1534 Type = resolveTypes(MHSTy, RHSTy); 1535 if (!Type) { 1536 TokError(Twine("inconsistent types '") + MHSTy->getAsString() + 1537 "' and '" + RHSTy->getAsString() + "' for !if"); 1538 return nullptr; 1539 } 1540 break; 1541 } 1542 case tgtok::XSubst: { 1543 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1544 if (!RHSt) { 1545 TokError("could not get type for !subst"); 1546 return nullptr; 1547 } 1548 Type = RHSt->getType(); 1549 break; 1550 } 1551 } 1552 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec); 1553 } 1554 1555 case tgtok::XCond: 1556 return ParseOperationCond(CurRec, ItemType); 1557 1558 case tgtok::XFoldl: { 1559 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')' 1560 Lex.Lex(); // eat the operation 1561 if (!consume(tgtok::l_paren)) { 1562 TokError("expected '(' after !foldl"); 1563 return nullptr; 1564 } 1565 1566 Init *StartUntyped = ParseValue(CurRec); 1567 if (!StartUntyped) 1568 return nullptr; 1569 1570 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped); 1571 if (!Start) { 1572 TokError(Twine("could not get type of !foldl start: '") + 1573 StartUntyped->getAsString() + "'"); 1574 return nullptr; 1575 } 1576 1577 if (!consume(tgtok::comma)) { 1578 TokError("expected ',' in !foldl"); 1579 return nullptr; 1580 } 1581 1582 Init *ListUntyped = ParseValue(CurRec); 1583 if (!ListUntyped) 1584 return nullptr; 1585 1586 TypedInit *List = dyn_cast<TypedInit>(ListUntyped); 1587 if (!List) { 1588 TokError(Twine("could not get type of !foldl list: '") + 1589 ListUntyped->getAsString() + "'"); 1590 return nullptr; 1591 } 1592 1593 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType()); 1594 if (!ListType) { 1595 TokError(Twine("!foldl list must be a list, but is of type '") + 1596 List->getType()->getAsString()); 1597 return nullptr; 1598 } 1599 1600 if (Lex.getCode() != tgtok::comma) { 1601 TokError("expected ',' in !foldl"); 1602 return nullptr; 1603 } 1604 1605 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1606 TokError("third argument of !foldl must be an identifier"); 1607 return nullptr; 1608 } 1609 1610 Init *A = StringInit::get(Lex.getCurStrVal()); 1611 if (CurRec && CurRec->getValue(A)) { 1612 TokError((Twine("left !foldl variable '") + A->getAsString() + 1613 "' already defined") 1614 .str()); 1615 return nullptr; 1616 } 1617 1618 if (Lex.Lex() != tgtok::comma) { // eat the id 1619 TokError("expected ',' in !foldl"); 1620 return nullptr; 1621 } 1622 1623 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1624 TokError("fourth argument of !foldl must be an identifier"); 1625 return nullptr; 1626 } 1627 1628 Init *B = StringInit::get(Lex.getCurStrVal()); 1629 if (CurRec && CurRec->getValue(B)) { 1630 TokError((Twine("right !foldl variable '") + B->getAsString() + 1631 "' already defined") 1632 .str()); 1633 return nullptr; 1634 } 1635 1636 if (Lex.Lex() != tgtok::comma) { // eat the id 1637 TokError("expected ',' in !foldl"); 1638 return nullptr; 1639 } 1640 Lex.Lex(); // eat the ',' 1641 1642 // We need to create a temporary record to provide a scope for the 1643 // two variables. 1644 std::unique_ptr<Record> ParseRecTmp; 1645 Record *ParseRec = CurRec; 1646 if (!ParseRec) { 1647 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1648 ParseRec = ParseRecTmp.get(); 1649 } 1650 1651 ParseRec->addValue(RecordVal(A, Start->getType(), false)); 1652 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false)); 1653 Init *ExprUntyped = ParseValue(ParseRec); 1654 ParseRec->removeValue(A); 1655 ParseRec->removeValue(B); 1656 if (!ExprUntyped) 1657 return nullptr; 1658 1659 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped); 1660 if (!Expr) { 1661 TokError("could not get type of !foldl expression"); 1662 return nullptr; 1663 } 1664 1665 if (Expr->getType() != Start->getType()) { 1666 TokError(Twine("!foldl expression must be of same type as start (") + 1667 Start->getType()->getAsString() + "), but is of type " + 1668 Expr->getType()->getAsString()); 1669 return nullptr; 1670 } 1671 1672 if (!consume(tgtok::r_paren)) { 1673 TokError("expected ')' in fold operator"); 1674 return nullptr; 1675 } 1676 1677 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType()) 1678 ->Fold(CurRec); 1679 } 1680 } 1681 } 1682 1683 /// ParseOperatorType - Parse a type for an operator. This returns 1684 /// null on error. 1685 /// 1686 /// OperatorType ::= '<' Type '>' 1687 /// 1688 RecTy *TGParser::ParseOperatorType() { 1689 RecTy *Type = nullptr; 1690 1691 if (!consume(tgtok::less)) { 1692 TokError("expected type name for operator"); 1693 return nullptr; 1694 } 1695 1696 Type = ParseType(); 1697 1698 if (!Type) { 1699 TokError("expected type name for operator"); 1700 return nullptr; 1701 } 1702 1703 if (!consume(tgtok::greater)) { 1704 TokError("expected type name for operator"); 1705 return nullptr; 1706 } 1707 1708 return Type; 1709 } 1710 1711 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) { 1712 Lex.Lex(); // eat the operation 'cond' 1713 1714 if (!consume(tgtok::l_paren)) { 1715 TokError("expected '(' after !cond operator"); 1716 return nullptr; 1717 } 1718 1719 // Parse through '[Case: Val,]+' 1720 SmallVector<Init *, 4> Case; 1721 SmallVector<Init *, 4> Val; 1722 while (true) { 1723 if (consume(tgtok::r_paren)) 1724 break; 1725 1726 Init *V = ParseValue(CurRec); 1727 if (!V) 1728 return nullptr; 1729 Case.push_back(V); 1730 1731 if (!consume(tgtok::colon)) { 1732 TokError("expected ':' following a condition in !cond operator"); 1733 return nullptr; 1734 } 1735 1736 V = ParseValue(CurRec, ItemType); 1737 if (!V) 1738 return nullptr; 1739 Val.push_back(V); 1740 1741 if (consume(tgtok::r_paren)) 1742 break; 1743 1744 if (!consume(tgtok::comma)) { 1745 TokError("expected ',' or ')' following a value in !cond operator"); 1746 return nullptr; 1747 } 1748 } 1749 1750 if (Case.size() < 1) { 1751 TokError("there should be at least 1 'condition : value' in the !cond operator"); 1752 return nullptr; 1753 } 1754 1755 // resolve type 1756 RecTy *Type = nullptr; 1757 for (Init *V : Val) { 1758 RecTy *VTy = nullptr; 1759 if (TypedInit *Vt = dyn_cast<TypedInit>(V)) 1760 VTy = Vt->getType(); 1761 if (BitsInit *Vbits = dyn_cast<BitsInit>(V)) 1762 VTy = BitsRecTy::get(Vbits->getNumBits()); 1763 if (isa<BitInit>(V)) 1764 VTy = BitRecTy::get(); 1765 1766 if (Type == nullptr) { 1767 if (!isa<UnsetInit>(V)) 1768 Type = VTy; 1769 } else { 1770 if (!isa<UnsetInit>(V)) { 1771 RecTy *RType = resolveTypes(Type, VTy); 1772 if (!RType) { 1773 TokError(Twine("inconsistent types '") + Type->getAsString() + 1774 "' and '" + VTy->getAsString() + "' for !cond"); 1775 return nullptr; 1776 } 1777 Type = RType; 1778 } 1779 } 1780 } 1781 1782 if (!Type) { 1783 TokError("could not determine type for !cond from its arguments"); 1784 return nullptr; 1785 } 1786 return CondOpInit::get(Case, Val, Type)->Fold(CurRec); 1787 } 1788 1789 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1790 /// 1791 /// SimpleValue ::= IDValue 1792 /// SimpleValue ::= INTVAL 1793 /// SimpleValue ::= STRVAL+ 1794 /// SimpleValue ::= CODEFRAGMENT 1795 /// SimpleValue ::= '?' 1796 /// SimpleValue ::= '{' ValueList '}' 1797 /// SimpleValue ::= ID '<' ValueListNE '>' 1798 /// SimpleValue ::= '[' ValueList ']' 1799 /// SimpleValue ::= '(' IDValue DagArgList ')' 1800 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')' 1801 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')' 1802 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1803 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1804 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1805 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')' 1806 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')' 1807 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1808 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')' 1809 /// 1810 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1811 IDParseMode Mode) { 1812 Init *R = nullptr; 1813 switch (Lex.getCode()) { 1814 default: TokError("Unknown token when parsing a value"); break; 1815 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break; 1816 case tgtok::BinaryIntVal: { 1817 auto BinaryVal = Lex.getCurBinaryIntVal(); 1818 SmallVector<Init*, 16> Bits(BinaryVal.second); 1819 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i) 1820 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i)); 1821 R = BitsInit::get(Bits); 1822 Lex.Lex(); 1823 break; 1824 } 1825 case tgtok::StrVal: { 1826 std::string Val = Lex.getCurStrVal(); 1827 Lex.Lex(); 1828 1829 // Handle multiple consecutive concatenated strings. 1830 while (Lex.getCode() == tgtok::StrVal) { 1831 Val += Lex.getCurStrVal(); 1832 Lex.Lex(); 1833 } 1834 1835 R = StringInit::get(Val); 1836 break; 1837 } 1838 case tgtok::CodeFragment: 1839 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc()); 1840 Lex.Lex(); 1841 break; 1842 case tgtok::question: 1843 R = UnsetInit::get(); 1844 Lex.Lex(); 1845 break; 1846 case tgtok::Id: { 1847 SMLoc NameLoc = Lex.getLoc(); 1848 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 1849 if (Lex.Lex() != tgtok::less) // consume the Id. 1850 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue 1851 1852 // Value ::= ID '<' ValueListNE '>' 1853 if (Lex.Lex() == tgtok::greater) { 1854 TokError("expected non-empty value list"); 1855 return nullptr; 1856 } 1857 1858 // This is a CLASS<initvalslist> expression. This is supposed to synthesize 1859 // a new anonymous definition, deriving from CLASS<initvalslist> with no 1860 // body. 1861 Record *Class = Records.getClass(Name->getValue()); 1862 if (!Class) { 1863 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'"); 1864 return nullptr; 1865 } 1866 1867 SmallVector<Init *, 8> Args; 1868 ParseValueList(Args, CurRec, Class); 1869 if (Args.empty()) return nullptr; 1870 1871 if (!consume(tgtok::greater)) { 1872 TokError("expected '>' at end of value list"); 1873 return nullptr; 1874 } 1875 1876 // Typecheck the template arguments list 1877 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs(); 1878 if (ExpectedArgs.size() < Args.size()) { 1879 Error(NameLoc, 1880 "More template args specified than expected"); 1881 return nullptr; 1882 } 1883 1884 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) { 1885 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]); 1886 if (i < Args.size()) { 1887 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) { 1888 RecTy *ExpectedType = ExpectedArg->getType(); 1889 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) { 1890 Error(NameLoc, 1891 "Value specified for template argument #" + Twine(i) + " (" + 1892 ExpectedArg->getNameInitAsString() + ") is of type '" + 1893 TI->getType()->getAsString() + "', expected '" + 1894 ExpectedType->getAsString() + "': " + TI->getAsString()); 1895 return nullptr; 1896 } 1897 continue; 1898 } 1899 } else if (ExpectedArg->getValue()->isComplete()) 1900 continue; 1901 1902 Error(NameLoc, 1903 "Value not specified for template argument #" + Twine(i) + " (" + 1904 ExpectedArgs[i]->getAsUnquotedString() + ")"); 1905 return nullptr; 1906 } 1907 1908 return VarDefInit::get(Class, Args)->Fold(); 1909 } 1910 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1911 SMLoc BraceLoc = Lex.getLoc(); 1912 Lex.Lex(); // eat the '{' 1913 SmallVector<Init*, 16> Vals; 1914 1915 if (Lex.getCode() != tgtok::r_brace) { 1916 ParseValueList(Vals, CurRec); 1917 if (Vals.empty()) return nullptr; 1918 } 1919 if (!consume(tgtok::r_brace)) { 1920 TokError("expected '}' at end of bit list value"); 1921 return nullptr; 1922 } 1923 1924 SmallVector<Init *, 16> NewBits; 1925 1926 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it 1927 // first. We'll first read everything in to a vector, then we can reverse 1928 // it to get the bits in the correct order for the BitsInit value. 1929 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1930 // FIXME: The following two loops would not be duplicated 1931 // if the API was a little more orthogonal. 1932 1933 // bits<n> values are allowed to initialize n bits. 1934 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) { 1935 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) 1936 NewBits.push_back(BI->getBit((e - i) - 1)); 1937 continue; 1938 } 1939 // bits<n> can also come from variable initializers. 1940 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) { 1941 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) { 1942 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i) 1943 NewBits.push_back(VI->getBit((e - i) - 1)); 1944 continue; 1945 } 1946 // Fallthrough to try convert this to a bit. 1947 } 1948 // All other values must be convertible to just a single bit. 1949 Init *Bit = Vals[i]->getCastTo(BitRecTy::get()); 1950 if (!Bit) { 1951 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() + 1952 ") is not convertable to a bit"); 1953 return nullptr; 1954 } 1955 NewBits.push_back(Bit); 1956 } 1957 std::reverse(NewBits.begin(), NewBits.end()); 1958 return BitsInit::get(NewBits); 1959 } 1960 case tgtok::l_square: { // Value ::= '[' ValueList ']' 1961 Lex.Lex(); // eat the '[' 1962 SmallVector<Init*, 16> Vals; 1963 1964 RecTy *DeducedEltTy = nullptr; 1965 ListRecTy *GivenListTy = nullptr; 1966 1967 if (ItemType) { 1968 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType); 1969 if (!ListType) { 1970 TokError(Twine("Type mismatch for list, expected list type, got ") + 1971 ItemType->getAsString()); 1972 return nullptr; 1973 } 1974 GivenListTy = ListType; 1975 } 1976 1977 if (Lex.getCode() != tgtok::r_square) { 1978 ParseValueList(Vals, CurRec, nullptr, 1979 GivenListTy ? GivenListTy->getElementType() : nullptr); 1980 if (Vals.empty()) return nullptr; 1981 } 1982 if (!consume(tgtok::r_square)) { 1983 TokError("expected ']' at end of list value"); 1984 return nullptr; 1985 } 1986 1987 RecTy *GivenEltTy = nullptr; 1988 if (consume(tgtok::less)) { 1989 // Optional list element type 1990 GivenEltTy = ParseType(); 1991 if (!GivenEltTy) { 1992 // Couldn't parse element type 1993 return nullptr; 1994 } 1995 1996 if (!consume(tgtok::greater)) { 1997 TokError("expected '>' at end of list element type"); 1998 return nullptr; 1999 } 2000 } 2001 2002 // Check elements 2003 RecTy *EltTy = nullptr; 2004 for (Init *V : Vals) { 2005 TypedInit *TArg = dyn_cast<TypedInit>(V); 2006 if (TArg) { 2007 if (EltTy) { 2008 EltTy = resolveTypes(EltTy, TArg->getType()); 2009 if (!EltTy) { 2010 TokError("Incompatible types in list elements"); 2011 return nullptr; 2012 } 2013 } else { 2014 EltTy = TArg->getType(); 2015 } 2016 } 2017 } 2018 2019 if (GivenEltTy) { 2020 if (EltTy) { 2021 // Verify consistency 2022 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) { 2023 TokError("Incompatible types in list elements"); 2024 return nullptr; 2025 } 2026 } 2027 EltTy = GivenEltTy; 2028 } 2029 2030 if (!EltTy) { 2031 if (!ItemType) { 2032 TokError("No type for list"); 2033 return nullptr; 2034 } 2035 DeducedEltTy = GivenListTy->getElementType(); 2036 } else { 2037 // Make sure the deduced type is compatible with the given type 2038 if (GivenListTy) { 2039 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 2040 TokError(Twine("Element type mismatch for list: element type '") + 2041 EltTy->getAsString() + "' not convertible to '" + 2042 GivenListTy->getElementType()->getAsString()); 2043 return nullptr; 2044 } 2045 } 2046 DeducedEltTy = EltTy; 2047 } 2048 2049 return ListInit::get(Vals, DeducedEltTy); 2050 } 2051 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')' 2052 Lex.Lex(); // eat the '(' 2053 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast && 2054 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) { 2055 TokError("expected identifier in dag init"); 2056 return nullptr; 2057 } 2058 2059 Init *Operator = ParseValue(CurRec); 2060 if (!Operator) return nullptr; 2061 2062 // If the operator name is present, parse it. 2063 StringInit *OperatorName = nullptr; 2064 if (consume(tgtok::colon)) { 2065 if (Lex.getCode() != tgtok::VarName) { // eat the ':' 2066 TokError("expected variable name in dag operator"); 2067 return nullptr; 2068 } 2069 OperatorName = StringInit::get(Lex.getCurStrVal()); 2070 Lex.Lex(); // eat the VarName. 2071 } 2072 2073 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs; 2074 if (Lex.getCode() != tgtok::r_paren) { 2075 ParseDagArgList(DagArgs, CurRec); 2076 if (DagArgs.empty()) return nullptr; 2077 } 2078 2079 if (!consume(tgtok::r_paren)) { 2080 TokError("expected ')' in dag init"); 2081 return nullptr; 2082 } 2083 2084 return DagInit::get(Operator, OperatorName, DagArgs); 2085 } 2086 2087 case tgtok::XHead: 2088 case tgtok::XTail: 2089 case tgtok::XSize: 2090 case tgtok::XEmpty: 2091 case tgtok::XCast: 2092 case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')' 2093 case tgtok::XIsA: 2094 case tgtok::XConcat: 2095 case tgtok::XDag: 2096 case tgtok::XADD: 2097 case tgtok::XMUL: 2098 case tgtok::XNOT: 2099 case tgtok::XAND: 2100 case tgtok::XOR: 2101 case tgtok::XXOR: 2102 case tgtok::XSRA: 2103 case tgtok::XSRL: 2104 case tgtok::XSHL: 2105 case tgtok::XEq: 2106 case tgtok::XNe: 2107 case tgtok::XLe: 2108 case tgtok::XLt: 2109 case tgtok::XGe: 2110 case tgtok::XGt: 2111 case tgtok::XListConcat: 2112 case tgtok::XListSplat: 2113 case tgtok::XStrConcat: 2114 case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')' 2115 case tgtok::XIf: 2116 case tgtok::XCond: 2117 case tgtok::XFoldl: 2118 case tgtok::XForEach: 2119 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 2120 return ParseOperation(CurRec, ItemType); 2121 } 2122 } 2123 2124 return R; 2125 } 2126 2127 /// ParseValue - Parse a tblgen value. This returns null on error. 2128 /// 2129 /// Value ::= SimpleValue ValueSuffix* 2130 /// ValueSuffix ::= '{' BitList '}' 2131 /// ValueSuffix ::= '[' BitList ']' 2132 /// ValueSuffix ::= '.' ID 2133 /// 2134 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) { 2135 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode); 2136 if (!Result) return nullptr; 2137 2138 // Parse the suffixes now if present. 2139 while (true) { 2140 switch (Lex.getCode()) { 2141 default: return Result; 2142 case tgtok::l_brace: { 2143 if (Mode == ParseNameMode) 2144 // This is the beginning of the object body. 2145 return Result; 2146 2147 SMLoc CurlyLoc = Lex.getLoc(); 2148 Lex.Lex(); // eat the '{' 2149 SmallVector<unsigned, 16> Ranges; 2150 ParseRangeList(Ranges); 2151 if (Ranges.empty()) return nullptr; 2152 2153 // Reverse the bitlist. 2154 std::reverse(Ranges.begin(), Ranges.end()); 2155 Result = Result->convertInitializerBitRange(Ranges); 2156 if (!Result) { 2157 Error(CurlyLoc, "Invalid bit range for value"); 2158 return nullptr; 2159 } 2160 2161 // Eat the '}'. 2162 if (!consume(tgtok::r_brace)) { 2163 TokError("expected '}' at end of bit range list"); 2164 return nullptr; 2165 } 2166 break; 2167 } 2168 case tgtok::l_square: { 2169 SMLoc SquareLoc = Lex.getLoc(); 2170 Lex.Lex(); // eat the '[' 2171 SmallVector<unsigned, 16> Ranges; 2172 ParseRangeList(Ranges); 2173 if (Ranges.empty()) return nullptr; 2174 2175 Result = Result->convertInitListSlice(Ranges); 2176 if (!Result) { 2177 Error(SquareLoc, "Invalid range for list slice"); 2178 return nullptr; 2179 } 2180 2181 // Eat the ']'. 2182 if (!consume(tgtok::r_square)) { 2183 TokError("expected ']' at end of list slice"); 2184 return nullptr; 2185 } 2186 break; 2187 } 2188 case tgtok::dot: { 2189 if (Lex.Lex() != tgtok::Id) { // eat the . 2190 TokError("expected field identifier after '.'"); 2191 return nullptr; 2192 } 2193 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2194 if (!Result->getFieldType(FieldName)) { 2195 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 2196 Result->getAsString() + "'"); 2197 return nullptr; 2198 } 2199 Result = FieldInit::get(Result, FieldName)->Fold(CurRec); 2200 Lex.Lex(); // eat field name 2201 break; 2202 } 2203 2204 case tgtok::paste: 2205 SMLoc PasteLoc = Lex.getLoc(); 2206 TypedInit *LHS = dyn_cast<TypedInit>(Result); 2207 if (!LHS) { 2208 Error(PasteLoc, "LHS of paste is not typed!"); 2209 return nullptr; 2210 } 2211 2212 // Check if it's a 'listA # listB' 2213 if (isa<ListRecTy>(LHS->getType())) { 2214 Lex.Lex(); // Eat the '#'. 2215 2216 switch (Lex.getCode()) { 2217 case tgtok::colon: 2218 case tgtok::semi: 2219 case tgtok::l_brace: 2220 Result = LHS; // trailing paste, ignore. 2221 break; 2222 default: 2223 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode); 2224 if (!RHSResult) 2225 return nullptr; 2226 Result = BinOpInit::getListConcat(LHS, RHSResult); 2227 } 2228 break; 2229 } 2230 2231 // Create a !strconcat() operation, first casting each operand to 2232 // a string if necessary. 2233 if (LHS->getType() != StringRecTy::get()) { 2234 auto CastLHS = dyn_cast<TypedInit>( 2235 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()) 2236 ->Fold(CurRec)); 2237 if (!CastLHS) { 2238 Error(PasteLoc, 2239 Twine("can't cast '") + LHS->getAsString() + "' to string"); 2240 return nullptr; 2241 } 2242 LHS = CastLHS; 2243 } 2244 2245 TypedInit *RHS = nullptr; 2246 2247 Lex.Lex(); // Eat the '#'. 2248 switch (Lex.getCode()) { 2249 case tgtok::colon: 2250 case tgtok::semi: 2251 case tgtok::l_brace: 2252 // These are all of the tokens that can begin an object body. 2253 // Some of these can also begin values but we disallow those cases 2254 // because they are unlikely to be useful. 2255 2256 // Trailing paste, concat with an empty string. 2257 RHS = StringInit::get(""); 2258 break; 2259 2260 default: 2261 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode); 2262 if (!RHSResult) 2263 return nullptr; 2264 RHS = dyn_cast<TypedInit>(RHSResult); 2265 if (!RHS) { 2266 Error(PasteLoc, "RHS of paste is not typed!"); 2267 return nullptr; 2268 } 2269 2270 if (RHS->getType() != StringRecTy::get()) { 2271 auto CastRHS = dyn_cast<TypedInit>( 2272 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()) 2273 ->Fold(CurRec)); 2274 if (!CastRHS) { 2275 Error(PasteLoc, 2276 Twine("can't cast '") + RHS->getAsString() + "' to string"); 2277 return nullptr; 2278 } 2279 RHS = CastRHS; 2280 } 2281 2282 break; 2283 } 2284 2285 Result = BinOpInit::getStrConcat(LHS, RHS); 2286 break; 2287 } 2288 } 2289 } 2290 2291 /// ParseDagArgList - Parse the argument list for a dag literal expression. 2292 /// 2293 /// DagArg ::= Value (':' VARNAME)? 2294 /// DagArg ::= VARNAME 2295 /// DagArgList ::= DagArg 2296 /// DagArgList ::= DagArgList ',' DagArg 2297 void TGParser::ParseDagArgList( 2298 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result, 2299 Record *CurRec) { 2300 2301 while (true) { 2302 // DagArg ::= VARNAME 2303 if (Lex.getCode() == tgtok::VarName) { 2304 // A missing value is treated like '?'. 2305 StringInit *VarName = StringInit::get(Lex.getCurStrVal()); 2306 Result.emplace_back(UnsetInit::get(), VarName); 2307 Lex.Lex(); 2308 } else { 2309 // DagArg ::= Value (':' VARNAME)? 2310 Init *Val = ParseValue(CurRec); 2311 if (!Val) { 2312 Result.clear(); 2313 return; 2314 } 2315 2316 // If the variable name is present, add it. 2317 StringInit *VarName = nullptr; 2318 if (Lex.getCode() == tgtok::colon) { 2319 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 2320 TokError("expected variable name in dag literal"); 2321 Result.clear(); 2322 return; 2323 } 2324 VarName = StringInit::get(Lex.getCurStrVal()); 2325 Lex.Lex(); // eat the VarName. 2326 } 2327 2328 Result.push_back(std::make_pair(Val, VarName)); 2329 } 2330 if (!consume(tgtok::comma)) 2331 break; 2332 } 2333 } 2334 2335 /// ParseValueList - Parse a comma separated list of values, returning them as a 2336 /// vector. Note that this always expects to be able to parse at least one 2337 /// value. It returns an empty list if this is not possible. 2338 /// 2339 /// ValueList ::= Value (',' Value) 2340 /// 2341 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec, 2342 Record *ArgsRec, RecTy *EltTy) { 2343 RecTy *ItemType = EltTy; 2344 unsigned int ArgN = 0; 2345 if (ArgsRec && !EltTy) { 2346 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2347 if (TArgs.empty()) { 2348 TokError("template argument provided to non-template class"); 2349 Result.clear(); 2350 return; 2351 } 2352 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2353 if (!RV) { 2354 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN] 2355 << ")\n"; 2356 } 2357 assert(RV && "Template argument record not found??"); 2358 ItemType = RV->getType(); 2359 ++ArgN; 2360 } 2361 Result.push_back(ParseValue(CurRec, ItemType)); 2362 if (!Result.back()) { 2363 Result.clear(); 2364 return; 2365 } 2366 2367 while (consume(tgtok::comma)) { 2368 // ignore trailing comma for lists 2369 if (Lex.getCode() == tgtok::r_square) 2370 return; 2371 2372 if (ArgsRec && !EltTy) { 2373 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2374 if (ArgN >= TArgs.size()) { 2375 TokError("too many template arguments"); 2376 Result.clear(); 2377 return; 2378 } 2379 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2380 assert(RV && "Template argument record not found??"); 2381 ItemType = RV->getType(); 2382 ++ArgN; 2383 } 2384 Result.push_back(ParseValue(CurRec, ItemType)); 2385 if (!Result.back()) { 2386 Result.clear(); 2387 return; 2388 } 2389 } 2390 } 2391 2392 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an 2393 /// empty string on error. This can happen in a number of different context's, 2394 /// including within a def or in the template args for a def (which which case 2395 /// CurRec will be non-null) and within the template args for a multiclass (in 2396 /// which case CurRec will be null, but CurMultiClass will be set). This can 2397 /// also happen within a def that is within a multiclass, which will set both 2398 /// CurRec and CurMultiClass. 2399 /// 2400 /// Declaration ::= FIELD? Type ID ('=' Value)? 2401 /// 2402 Init *TGParser::ParseDeclaration(Record *CurRec, 2403 bool ParsingTemplateArgs) { 2404 // Read the field prefix if present. 2405 bool HasField = consume(tgtok::Field); 2406 2407 RecTy *Type = ParseType(); 2408 if (!Type) return nullptr; 2409 2410 if (Lex.getCode() != tgtok::Id) { 2411 TokError("Expected identifier in declaration"); 2412 return nullptr; 2413 } 2414 2415 std::string Str = Lex.getCurStrVal(); 2416 if (Str == "NAME") { 2417 TokError("'" + Str + "' is a reserved variable name"); 2418 return nullptr; 2419 } 2420 2421 SMLoc IdLoc = Lex.getLoc(); 2422 Init *DeclName = StringInit::get(Str); 2423 Lex.Lex(); 2424 2425 if (ParsingTemplateArgs) { 2426 if (CurRec) 2427 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 2428 else 2429 assert(CurMultiClass); 2430 if (CurMultiClass) 2431 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, 2432 "::"); 2433 } 2434 2435 // Add the value. 2436 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type, HasField))) 2437 return nullptr; 2438 2439 // If a value is present, parse it. 2440 if (consume(tgtok::equal)) { 2441 SMLoc ValLoc = Lex.getLoc(); 2442 Init *Val = ParseValue(CurRec, Type); 2443 if (!Val || 2444 SetValue(CurRec, ValLoc, DeclName, None, Val)) 2445 // Return the name, even if an error is thrown. This is so that we can 2446 // continue to make some progress, even without the value having been 2447 // initialized. 2448 return DeclName; 2449 } 2450 2451 return DeclName; 2452 } 2453 2454 /// ParseForeachDeclaration - Read a foreach declaration, returning 2455 /// the name of the declared object or a NULL Init on error. Return 2456 /// the name of the parsed initializer list through ForeachListName. 2457 /// 2458 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 2459 /// ForeachDeclaration ::= ID '=' RangePiece 2460 /// ForeachDeclaration ::= ID '=' Value 2461 /// 2462 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) { 2463 if (Lex.getCode() != tgtok::Id) { 2464 TokError("Expected identifier in foreach declaration"); 2465 return nullptr; 2466 } 2467 2468 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2469 Lex.Lex(); 2470 2471 // If a value is present, parse it. 2472 if (!consume(tgtok::equal)) { 2473 TokError("Expected '=' in foreach declaration"); 2474 return nullptr; 2475 } 2476 2477 RecTy *IterType = nullptr; 2478 SmallVector<unsigned, 16> Ranges; 2479 2480 switch (Lex.getCode()) { 2481 case tgtok::l_brace: { // '{' RangeList '}' 2482 Lex.Lex(); // eat the '{' 2483 ParseRangeList(Ranges); 2484 if (!consume(tgtok::r_brace)) { 2485 TokError("expected '}' at end of bit range list"); 2486 return nullptr; 2487 } 2488 break; 2489 } 2490 2491 default: { 2492 SMLoc ValueLoc = Lex.getLoc(); 2493 Init *I = ParseValue(nullptr); 2494 if (!I) 2495 return nullptr; 2496 2497 TypedInit *TI = dyn_cast<TypedInit>(I); 2498 if (TI && isa<ListRecTy>(TI->getType())) { 2499 ForeachListValue = I; 2500 IterType = cast<ListRecTy>(TI->getType())->getElementType(); 2501 break; 2502 } 2503 2504 if (TI) { 2505 if (ParseRangePiece(Ranges, TI)) 2506 return nullptr; 2507 break; 2508 } 2509 2510 std::string Type; 2511 if (TI) 2512 Type = (Twine("' of type '") + TI->getType()->getAsString()).str(); 2513 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'"); 2514 if (CurMultiClass) { 2515 PrintNote({}, "references to multiclass template arguments cannot be " 2516 "resolved at this time"); 2517 } 2518 return nullptr; 2519 } 2520 } 2521 2522 2523 if (!Ranges.empty()) { 2524 assert(!IterType && "Type already initialized?"); 2525 IterType = IntRecTy::get(); 2526 std::vector<Init*> Values; 2527 for (unsigned R : Ranges) 2528 Values.push_back(IntInit::get(R)); 2529 ForeachListValue = ListInit::get(Values, IterType); 2530 } 2531 2532 if (!IterType) 2533 return nullptr; 2534 2535 return VarInit::get(DeclName, IterType); 2536 } 2537 2538 /// ParseTemplateArgList - Read a template argument list, which is a non-empty 2539 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are 2540 /// template args for a def, which may or may not be in a multiclass. If null, 2541 /// these are the template args for a multiclass. 2542 /// 2543 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>' 2544 /// 2545 bool TGParser::ParseTemplateArgList(Record *CurRec) { 2546 assert(Lex.getCode() == tgtok::less && "Not a template arg list!"); 2547 Lex.Lex(); // eat the '<' 2548 2549 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec; 2550 2551 // Read the first declaration. 2552 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2553 if (!TemplArg) 2554 return true; 2555 2556 TheRecToAddTo->addTemplateArg(TemplArg); 2557 2558 while (consume(tgtok::comma)) { 2559 // Read the following declarations. 2560 SMLoc Loc = Lex.getLoc(); 2561 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2562 if (!TemplArg) 2563 return true; 2564 2565 if (TheRecToAddTo->isTemplateArg(TemplArg)) 2566 return Error(Loc, "template argument with the same name has already been " 2567 "defined"); 2568 2569 TheRecToAddTo->addTemplateArg(TemplArg); 2570 } 2571 2572 if (!consume(tgtok::greater)) 2573 return TokError("expected '>' at end of template argument list"); 2574 return false; 2575 } 2576 2577 /// ParseBodyItem - Parse a single item at within the body of a def or class. 2578 /// 2579 /// BodyItem ::= Declaration ';' 2580 /// BodyItem ::= LET ID OptionalBitList '=' Value ';' 2581 /// BodyItem ::= Defvar 2582 bool TGParser::ParseBodyItem(Record *CurRec) { 2583 if (Lex.getCode() == tgtok::Defvar) 2584 return ParseDefvar(); 2585 2586 if (Lex.getCode() != tgtok::Let) { 2587 if (!ParseDeclaration(CurRec, false)) 2588 return true; 2589 2590 if (!consume(tgtok::semi)) 2591 return TokError("expected ';' after declaration"); 2592 return false; 2593 } 2594 2595 // LET ID OptionalRangeList '=' Value ';' 2596 if (Lex.Lex() != tgtok::Id) 2597 return TokError("expected field identifier after let"); 2598 2599 SMLoc IdLoc = Lex.getLoc(); 2600 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2601 Lex.Lex(); // eat the field name. 2602 2603 SmallVector<unsigned, 16> BitList; 2604 if (ParseOptionalBitList(BitList)) 2605 return true; 2606 std::reverse(BitList.begin(), BitList.end()); 2607 2608 if (!consume(tgtok::equal)) 2609 return TokError("expected '=' in let expression"); 2610 2611 RecordVal *Field = CurRec->getValue(FieldName); 2612 if (!Field) 2613 return TokError("Value '" + FieldName->getValue() + "' unknown!"); 2614 2615 RecTy *Type = Field->getType(); 2616 if (!BitList.empty() && isa<BitsRecTy>(Type)) { 2617 // When assigning to a subset of a 'bits' object, expect the RHS to have 2618 // the type of that subset instead of the type of the whole object. 2619 Type = BitsRecTy::get(BitList.size()); 2620 } 2621 2622 Init *Val = ParseValue(CurRec, Type); 2623 if (!Val) return true; 2624 2625 if (!consume(tgtok::semi)) 2626 return TokError("expected ';' after let expression"); 2627 2628 return SetValue(CurRec, IdLoc, FieldName, BitList, Val); 2629 } 2630 2631 /// ParseBody - Read the body of a class or def. Return true on error, false on 2632 /// success. 2633 /// 2634 /// Body ::= ';' 2635 /// Body ::= '{' BodyList '}' 2636 /// BodyList BodyItem* 2637 /// 2638 bool TGParser::ParseBody(Record *CurRec) { 2639 // If this is a null definition, just eat the semi and return. 2640 if (consume(tgtok::semi)) 2641 return false; 2642 2643 if (!consume(tgtok::l_brace)) 2644 return TokError("Expected ';' or '{' to start body"); 2645 2646 // An object body introduces a new scope for local variables. 2647 TGLocalVarScope *BodyScope = PushLocalScope(); 2648 2649 while (Lex.getCode() != tgtok::r_brace) 2650 if (ParseBodyItem(CurRec)) 2651 return true; 2652 2653 PopLocalScope(BodyScope); 2654 2655 // Eat the '}'. 2656 Lex.Lex(); 2657 return false; 2658 } 2659 2660 /// Apply the current let bindings to \a CurRec. 2661 /// \returns true on error, false otherwise. 2662 bool TGParser::ApplyLetStack(Record *CurRec) { 2663 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack) 2664 for (LetRecord &LR : LetInfo) 2665 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value)) 2666 return true; 2667 return false; 2668 } 2669 2670 bool TGParser::ApplyLetStack(RecordsEntry &Entry) { 2671 if (Entry.Rec) 2672 return ApplyLetStack(Entry.Rec.get()); 2673 2674 for (auto &E : Entry.Loop->Entries) { 2675 if (ApplyLetStack(E)) 2676 return true; 2677 } 2678 2679 return false; 2680 } 2681 2682 /// ParseObjectBody - Parse the body of a def or class. This consists of an 2683 /// optional ClassList followed by a Body. CurRec is the current def or class 2684 /// that is being parsed. 2685 /// 2686 /// ObjectBody ::= BaseClassList Body 2687 /// BaseClassList ::= /*empty*/ 2688 /// BaseClassList ::= ':' BaseClassListNE 2689 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)* 2690 /// 2691 bool TGParser::ParseObjectBody(Record *CurRec) { 2692 // If there is a baseclass list, read it. 2693 if (consume(tgtok::colon)) { 2694 2695 // Read all of the subclasses. 2696 SubClassReference SubClass = ParseSubClassReference(CurRec, false); 2697 while (true) { 2698 // Check for error. 2699 if (!SubClass.Rec) return true; 2700 2701 // Add it. 2702 if (AddSubClass(CurRec, SubClass)) 2703 return true; 2704 2705 if (!consume(tgtok::comma)) 2706 break; 2707 SubClass = ParseSubClassReference(CurRec, false); 2708 } 2709 } 2710 2711 if (ApplyLetStack(CurRec)) 2712 return true; 2713 2714 return ParseBody(CurRec); 2715 } 2716 2717 /// ParseDef - Parse and return a top level or multiclass def, return the record 2718 /// corresponding to it. This returns null on error. 2719 /// 2720 /// DefInst ::= DEF ObjectName ObjectBody 2721 /// 2722 bool TGParser::ParseDef(MultiClass *CurMultiClass) { 2723 SMLoc DefLoc = Lex.getLoc(); 2724 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 2725 Lex.Lex(); // Eat the 'def' token. 2726 2727 // Parse ObjectName and make a record for it. 2728 std::unique_ptr<Record> CurRec; 2729 Init *Name = ParseObjectName(CurMultiClass); 2730 if (!Name) 2731 return true; 2732 2733 if (isa<UnsetInit>(Name)) 2734 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records, 2735 /*Anonymous=*/true); 2736 else 2737 CurRec = std::make_unique<Record>(Name, DefLoc, Records); 2738 2739 if (ParseObjectBody(CurRec.get())) 2740 return true; 2741 2742 return addEntry(std::move(CurRec)); 2743 } 2744 2745 /// ParseDefset - Parse a defset statement. 2746 /// 2747 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}' 2748 /// 2749 bool TGParser::ParseDefset() { 2750 assert(Lex.getCode() == tgtok::Defset); 2751 Lex.Lex(); // Eat the 'defset' token 2752 2753 DefsetRecord Defset; 2754 Defset.Loc = Lex.getLoc(); 2755 RecTy *Type = ParseType(); 2756 if (!Type) 2757 return true; 2758 if (!isa<ListRecTy>(Type)) 2759 return Error(Defset.Loc, "expected list type"); 2760 Defset.EltTy = cast<ListRecTy>(Type)->getElementType(); 2761 2762 if (Lex.getCode() != tgtok::Id) 2763 return TokError("expected identifier"); 2764 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2765 if (Records.getGlobal(DeclName->getValue())) 2766 return TokError("def or global variable of this name already exists"); 2767 2768 if (Lex.Lex() != tgtok::equal) // Eat the identifier 2769 return TokError("expected '='"); 2770 if (Lex.Lex() != tgtok::l_brace) // Eat the '=' 2771 return TokError("expected '{'"); 2772 SMLoc BraceLoc = Lex.getLoc(); 2773 Lex.Lex(); // Eat the '{' 2774 2775 Defsets.push_back(&Defset); 2776 bool Err = ParseObjectList(nullptr); 2777 Defsets.pop_back(); 2778 if (Err) 2779 return true; 2780 2781 if (!consume(tgtok::r_brace)) { 2782 TokError("expected '}' at end of defset"); 2783 return Error(BraceLoc, "to match this '{'"); 2784 } 2785 2786 Records.addExtraGlobal(DeclName->getValue(), 2787 ListInit::get(Defset.Elements, Defset.EltTy)); 2788 return false; 2789 } 2790 2791 /// ParseDefvar - Parse a defvar statement. 2792 /// 2793 /// Defvar ::= DEFVAR Id '=' Value ';' 2794 /// 2795 bool TGParser::ParseDefvar() { 2796 assert(Lex.getCode() == tgtok::Defvar); 2797 Lex.Lex(); // Eat the 'defvar' token 2798 2799 if (Lex.getCode() != tgtok::Id) 2800 return TokError("expected identifier"); 2801 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2802 if (CurLocalScope) { 2803 if (CurLocalScope->varAlreadyDefined(DeclName->getValue())) 2804 return TokError("local variable of this name already exists"); 2805 } else { 2806 if (Records.getGlobal(DeclName->getValue())) 2807 return TokError("def or global variable of this name already exists"); 2808 } 2809 2810 Lex.Lex(); 2811 if (!consume(tgtok::equal)) 2812 return TokError("expected '='"); 2813 2814 Init *Value = ParseValue(nullptr); 2815 if (!Value) 2816 return true; 2817 2818 if (!consume(tgtok::semi)) 2819 return TokError("expected ';'"); 2820 2821 if (CurLocalScope) 2822 CurLocalScope->addVar(DeclName->getValue(), Value); 2823 else 2824 Records.addExtraGlobal(DeclName->getValue(), Value); 2825 2826 return false; 2827 } 2828 2829 /// ParseForeach - Parse a for statement. Return the record corresponding 2830 /// to it. This returns true on error. 2831 /// 2832 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2833 /// Foreach ::= FOREACH Declaration IN Object 2834 /// 2835 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2836 SMLoc Loc = Lex.getLoc(); 2837 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2838 Lex.Lex(); // Eat the 'for' token. 2839 2840 // Make a temporary object to record items associated with the for 2841 // loop. 2842 Init *ListValue = nullptr; 2843 VarInit *IterName = ParseForeachDeclaration(ListValue); 2844 if (!IterName) 2845 return TokError("expected declaration in for"); 2846 2847 if (!consume(tgtok::In)) 2848 return TokError("Unknown tok"); 2849 2850 // Create a loop object and remember it. 2851 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue)); 2852 2853 // A foreach loop introduces a new scope for local variables. 2854 TGLocalVarScope *ForeachScope = PushLocalScope(); 2855 2856 if (Lex.getCode() != tgtok::l_brace) { 2857 // FOREACH Declaration IN Object 2858 if (ParseObject(CurMultiClass)) 2859 return true; 2860 } else { 2861 SMLoc BraceLoc = Lex.getLoc(); 2862 // Otherwise, this is a group foreach. 2863 Lex.Lex(); // eat the '{'. 2864 2865 // Parse the object list. 2866 if (ParseObjectList(CurMultiClass)) 2867 return true; 2868 2869 if (!consume(tgtok::r_brace)) { 2870 TokError("expected '}' at end of foreach command"); 2871 return Error(BraceLoc, "to match this '{'"); 2872 } 2873 } 2874 2875 PopLocalScope(ForeachScope); 2876 2877 // Resolve the loop or store it for later resolution. 2878 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2879 Loops.pop_back(); 2880 2881 return addEntry(std::move(Loop)); 2882 } 2883 2884 /// ParseIf - Parse an if statement. 2885 /// 2886 /// If ::= IF Value THEN IfBody 2887 /// If ::= IF Value THEN IfBody ELSE IfBody 2888 /// 2889 bool TGParser::ParseIf(MultiClass *CurMultiClass) { 2890 SMLoc Loc = Lex.getLoc(); 2891 assert(Lex.getCode() == tgtok::If && "Unknown tok"); 2892 Lex.Lex(); // Eat the 'if' token. 2893 2894 // Make a temporary object to record items associated with the for 2895 // loop. 2896 Init *Condition = ParseValue(nullptr); 2897 if (!Condition) 2898 return true; 2899 2900 if (!consume(tgtok::Then)) 2901 return TokError("Unknown tok"); 2902 2903 // We have to be able to save if statements to execute later, and they have 2904 // to live on the same stack as foreach loops. The simplest implementation 2905 // technique is to convert each 'then' or 'else' clause *into* a foreach 2906 // loop, over a list of length 0 or 1 depending on the condition, and with no 2907 // iteration variable being assigned. 2908 2909 ListInit *EmptyList = ListInit::get({}, BitRecTy::get()); 2910 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get()); 2911 RecTy *BitListTy = ListRecTy::get(BitRecTy::get()); 2912 2913 // The foreach containing the then-clause selects SingletonList if 2914 // the condition is true. 2915 Init *ThenClauseList = 2916 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList, 2917 BitListTy) 2918 ->Fold(nullptr); 2919 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList)); 2920 2921 if (ParseIfBody(CurMultiClass, "then")) 2922 return true; 2923 2924 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2925 Loops.pop_back(); 2926 2927 if (addEntry(std::move(Loop))) 2928 return true; 2929 2930 // Now look for an optional else clause. The if-else syntax has the usual 2931 // dangling-else ambiguity, and by greedily matching an else here if we can, 2932 // we implement the usual resolution of pairing with the innermost unmatched 2933 // if. 2934 if (consume(tgtok::ElseKW)) { 2935 // The foreach containing the else-clause uses the same pair of lists as 2936 // above, but this time, selects SingletonList if the condition is *false*. 2937 Init *ElseClauseList = 2938 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList, 2939 BitListTy) 2940 ->Fold(nullptr); 2941 Loops.push_back( 2942 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList)); 2943 2944 if (ParseIfBody(CurMultiClass, "else")) 2945 return true; 2946 2947 Loop = std::move(Loops.back()); 2948 Loops.pop_back(); 2949 2950 if (addEntry(std::move(Loop))) 2951 return true; 2952 } 2953 2954 return false; 2955 } 2956 2957 /// ParseIfBody - Parse the then-clause or else-clause of an if statement. 2958 /// 2959 /// IfBody ::= Object 2960 /// IfBody ::= '{' ObjectList '}' 2961 /// 2962 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) { 2963 TGLocalVarScope *BodyScope = PushLocalScope(); 2964 2965 if (Lex.getCode() != tgtok::l_brace) { 2966 // A single object. 2967 if (ParseObject(CurMultiClass)) 2968 return true; 2969 } else { 2970 SMLoc BraceLoc = Lex.getLoc(); 2971 // A braced block. 2972 Lex.Lex(); // eat the '{'. 2973 2974 // Parse the object list. 2975 if (ParseObjectList(CurMultiClass)) 2976 return true; 2977 2978 if (!consume(tgtok::r_brace)) { 2979 TokError("expected '}' at end of '" + Kind + "' clause"); 2980 return Error(BraceLoc, "to match this '{'"); 2981 } 2982 } 2983 2984 PopLocalScope(BodyScope); 2985 return false; 2986 } 2987 2988 /// ParseClass - Parse a tblgen class definition. 2989 /// 2990 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2991 /// 2992 bool TGParser::ParseClass() { 2993 assert(Lex.getCode() == tgtok::Class && "Unexpected token!"); 2994 Lex.Lex(); 2995 2996 if (Lex.getCode() != tgtok::Id) 2997 return TokError("expected class name after 'class' keyword"); 2998 2999 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 3000 if (CurRec) { 3001 // If the body was previously defined, this is an error. 3002 if (!CurRec->getValues().empty() || 3003 !CurRec->getSuperClasses().empty() || 3004 !CurRec->getTemplateArgs().empty()) 3005 return TokError("Class '" + CurRec->getNameInitAsString() + 3006 "' already defined"); 3007 } else { 3008 // If this is the first reference to this class, create and add it. 3009 auto NewRec = 3010 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records, 3011 /*Class=*/true); 3012 CurRec = NewRec.get(); 3013 Records.addClass(std::move(NewRec)); 3014 } 3015 Lex.Lex(); // eat the name. 3016 3017 // If there are template args, parse them. 3018 if (Lex.getCode() == tgtok::less) 3019 if (ParseTemplateArgList(CurRec)) 3020 return true; 3021 3022 return ParseObjectBody(CurRec); 3023 } 3024 3025 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 3026 /// of LetRecords. 3027 /// 3028 /// LetList ::= LetItem (',' LetItem)* 3029 /// LetItem ::= ID OptionalRangeList '=' Value 3030 /// 3031 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) { 3032 do { 3033 if (Lex.getCode() != tgtok::Id) { 3034 TokError("expected identifier in let definition"); 3035 Result.clear(); 3036 return; 3037 } 3038 3039 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 3040 SMLoc NameLoc = Lex.getLoc(); 3041 Lex.Lex(); // Eat the identifier. 3042 3043 // Check for an optional RangeList. 3044 SmallVector<unsigned, 16> Bits; 3045 if (ParseOptionalRangeList(Bits)) { 3046 Result.clear(); 3047 return; 3048 } 3049 std::reverse(Bits.begin(), Bits.end()); 3050 3051 if (!consume(tgtok::equal)) { 3052 TokError("expected '=' in let expression"); 3053 Result.clear(); 3054 return; 3055 } 3056 3057 Init *Val = ParseValue(nullptr); 3058 if (!Val) { 3059 Result.clear(); 3060 return; 3061 } 3062 3063 // Now that we have everything, add the record. 3064 Result.emplace_back(Name, Bits, Val, NameLoc); 3065 } while (consume(tgtok::comma)); 3066 } 3067 3068 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of 3069 /// different related productions. This works inside multiclasses too. 3070 /// 3071 /// Object ::= LET LetList IN '{' ObjectList '}' 3072 /// Object ::= LET LetList IN Object 3073 /// 3074 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) { 3075 assert(Lex.getCode() == tgtok::Let && "Unexpected token"); 3076 Lex.Lex(); 3077 3078 // Add this entry to the let stack. 3079 SmallVector<LetRecord, 8> LetInfo; 3080 ParseLetList(LetInfo); 3081 if (LetInfo.empty()) return true; 3082 LetStack.push_back(std::move(LetInfo)); 3083 3084 if (!consume(tgtok::In)) 3085 return TokError("expected 'in' at end of top-level 'let'"); 3086 3087 TGLocalVarScope *LetScope = PushLocalScope(); 3088 3089 // If this is a scalar let, just handle it now 3090 if (Lex.getCode() != tgtok::l_brace) { 3091 // LET LetList IN Object 3092 if (ParseObject(CurMultiClass)) 3093 return true; 3094 } else { // Object ::= LETCommand '{' ObjectList '}' 3095 SMLoc BraceLoc = Lex.getLoc(); 3096 // Otherwise, this is a group let. 3097 Lex.Lex(); // eat the '{'. 3098 3099 // Parse the object list. 3100 if (ParseObjectList(CurMultiClass)) 3101 return true; 3102 3103 if (!consume(tgtok::r_brace)) { 3104 TokError("expected '}' at end of top level let command"); 3105 return Error(BraceLoc, "to match this '{'"); 3106 } 3107 } 3108 3109 PopLocalScope(LetScope); 3110 3111 // Outside this let scope, this let block is not active. 3112 LetStack.pop_back(); 3113 return false; 3114 } 3115 3116 /// ParseMultiClass - Parse a multiclass definition. 3117 /// 3118 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? 3119 /// ':' BaseMultiClassList '{' MultiClassObject+ '}' 3120 /// MultiClassObject ::= DefInst 3121 /// MultiClassObject ::= MultiClassInst 3122 /// MultiClassObject ::= DefMInst 3123 /// MultiClassObject ::= LETCommand '{' ObjectList '}' 3124 /// MultiClassObject ::= LETCommand Object 3125 /// 3126 bool TGParser::ParseMultiClass() { 3127 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token"); 3128 Lex.Lex(); // Eat the multiclass token. 3129 3130 if (Lex.getCode() != tgtok::Id) 3131 return TokError("expected identifier after multiclass for name"); 3132 std::string Name = Lex.getCurStrVal(); 3133 3134 auto Result = 3135 MultiClasses.insert(std::make_pair(Name, 3136 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records))); 3137 3138 if (!Result.second) 3139 return TokError("multiclass '" + Name + "' already defined"); 3140 3141 CurMultiClass = Result.first->second.get(); 3142 Lex.Lex(); // Eat the identifier. 3143 3144 // If there are template args, parse them. 3145 if (Lex.getCode() == tgtok::less) 3146 if (ParseTemplateArgList(nullptr)) 3147 return true; 3148 3149 bool inherits = false; 3150 3151 // If there are submulticlasses, parse them. 3152 if (consume(tgtok::colon)) { 3153 inherits = true; 3154 3155 // Read all of the submulticlasses. 3156 SubMultiClassReference SubMultiClass = 3157 ParseSubMultiClassReference(CurMultiClass); 3158 while (true) { 3159 // Check for error. 3160 if (!SubMultiClass.MC) return true; 3161 3162 // Add it. 3163 if (AddSubMultiClass(CurMultiClass, SubMultiClass)) 3164 return true; 3165 3166 if (!consume(tgtok::comma)) 3167 break; 3168 SubMultiClass = ParseSubMultiClassReference(CurMultiClass); 3169 } 3170 } 3171 3172 if (Lex.getCode() != tgtok::l_brace) { 3173 if (!inherits) 3174 return TokError("expected '{' in multiclass definition"); 3175 if (!consume(tgtok::semi)) 3176 return TokError("expected ';' in multiclass definition"); 3177 } else { 3178 if (Lex.Lex() == tgtok::r_brace) // eat the '{'. 3179 return TokError("multiclass must contain at least one def"); 3180 3181 // A multiclass body introduces a new scope for local variables. 3182 TGLocalVarScope *MulticlassScope = PushLocalScope(); 3183 3184 while (Lex.getCode() != tgtok::r_brace) { 3185 switch (Lex.getCode()) { 3186 default: 3187 return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' " 3188 "or 'if' in multiclass body"); 3189 case tgtok::Let: 3190 case tgtok::Def: 3191 case tgtok::Defm: 3192 case tgtok::Defvar: 3193 case tgtok::Foreach: 3194 case tgtok::If: 3195 if (ParseObject(CurMultiClass)) 3196 return true; 3197 break; 3198 } 3199 } 3200 Lex.Lex(); // eat the '}'. 3201 3202 PopLocalScope(MulticlassScope); 3203 } 3204 3205 CurMultiClass = nullptr; 3206 return false; 3207 } 3208 3209 /// ParseDefm - Parse the instantiation of a multiclass. 3210 /// 3211 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 3212 /// 3213 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 3214 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 3215 Lex.Lex(); // eat the defm 3216 3217 Init *DefmName = ParseObjectName(CurMultiClass); 3218 if (!DefmName) 3219 return true; 3220 if (isa<UnsetInit>(DefmName)) { 3221 DefmName = Records.getNewAnonymousName(); 3222 if (CurMultiClass) 3223 DefmName = BinOpInit::getStrConcat( 3224 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass), 3225 StringRecTy::get()), 3226 DefmName); 3227 } 3228 3229 if (Lex.getCode() != tgtok::colon) 3230 return TokError("expected ':' after defm identifier"); 3231 3232 // Keep track of the new generated record definitions. 3233 std::vector<RecordsEntry> NewEntries; 3234 3235 // This record also inherits from a regular class (non-multiclass)? 3236 bool InheritFromClass = false; 3237 3238 // eat the colon. 3239 Lex.Lex(); 3240 3241 SMLoc SubClassLoc = Lex.getLoc(); 3242 SubClassReference Ref = ParseSubClassReference(nullptr, true); 3243 3244 while (true) { 3245 if (!Ref.Rec) return true; 3246 3247 // To instantiate a multiclass, we need to first get the multiclass, then 3248 // instantiate each def contained in the multiclass with the SubClassRef 3249 // template parameters. 3250 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get(); 3251 assert(MC && "Didn't lookup multiclass correctly?"); 3252 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs; 3253 3254 // Verify that the correct number of template arguments were specified. 3255 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs(); 3256 if (TArgs.size() < TemplateVals.size()) 3257 return Error(SubClassLoc, 3258 "more template args specified than multiclass expects"); 3259 3260 SubstStack Substs; 3261 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 3262 if (i < TemplateVals.size()) { 3263 Substs.emplace_back(TArgs[i], TemplateVals[i]); 3264 } else { 3265 Init *Default = MC->Rec.getValue(TArgs[i])->getValue(); 3266 if (!Default->isComplete()) { 3267 return Error(SubClassLoc, 3268 "value not specified for template argument #" + 3269 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 3270 ") of multiclass '" + MC->Rec.getNameInitAsString() + 3271 "'"); 3272 } 3273 Substs.emplace_back(TArgs[i], Default); 3274 } 3275 } 3276 3277 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName); 3278 3279 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries, 3280 &SubClassLoc)) 3281 return true; 3282 3283 if (!consume(tgtok::comma)) 3284 break; 3285 3286 if (Lex.getCode() != tgtok::Id) 3287 return TokError("expected identifier"); 3288 3289 SubClassLoc = Lex.getLoc(); 3290 3291 // A defm can inherit from regular classes (non-multiclass) as 3292 // long as they come in the end of the inheritance list. 3293 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr); 3294 3295 if (InheritFromClass) 3296 break; 3297 3298 Ref = ParseSubClassReference(nullptr, true); 3299 } 3300 3301 if (InheritFromClass) { 3302 // Process all the classes to inherit as if they were part of a 3303 // regular 'def' and inherit all record values. 3304 SubClassReference SubClass = ParseSubClassReference(nullptr, false); 3305 while (true) { 3306 // Check for error. 3307 if (!SubClass.Rec) return true; 3308 3309 // Get the expanded definition prototypes and teach them about 3310 // the record values the current class to inherit has 3311 for (auto &E : NewEntries) { 3312 // Add it. 3313 if (AddSubClass(E, SubClass)) 3314 return true; 3315 } 3316 3317 if (!consume(tgtok::comma)) 3318 break; 3319 SubClass = ParseSubClassReference(nullptr, false); 3320 } 3321 } 3322 3323 for (auto &E : NewEntries) { 3324 if (ApplyLetStack(E)) 3325 return true; 3326 3327 addEntry(std::move(E)); 3328 } 3329 3330 if (!consume(tgtok::semi)) 3331 return TokError("expected ';' at end of defm"); 3332 3333 return false; 3334 } 3335 3336 /// ParseObject 3337 /// Object ::= ClassInst 3338 /// Object ::= DefInst 3339 /// Object ::= MultiClassInst 3340 /// Object ::= DefMInst 3341 /// Object ::= LETCommand '{' ObjectList '}' 3342 /// Object ::= LETCommand Object 3343 /// Object ::= Defset 3344 /// Object ::= Defvar 3345 bool TGParser::ParseObject(MultiClass *MC) { 3346 switch (Lex.getCode()) { 3347 default: 3348 return TokError("Expected class, def, defm, defset, multiclass, let, " 3349 "foreach or if"); 3350 case tgtok::Let: return ParseTopLevelLet(MC); 3351 case tgtok::Def: return ParseDef(MC); 3352 case tgtok::Foreach: return ParseForeach(MC); 3353 case tgtok::If: return ParseIf(MC); 3354 case tgtok::Defm: return ParseDefm(MC); 3355 case tgtok::Defset: 3356 if (MC) 3357 return TokError("defset is not allowed inside multiclass"); 3358 return ParseDefset(); 3359 case tgtok::Defvar: 3360 return ParseDefvar(); 3361 case tgtok::Class: 3362 if (MC) 3363 return TokError("class is not allowed inside multiclass"); 3364 if (!Loops.empty()) 3365 return TokError("class is not allowed inside foreach loop"); 3366 return ParseClass(); 3367 case tgtok::MultiClass: 3368 if (!Loops.empty()) 3369 return TokError("multiclass is not allowed inside foreach loop"); 3370 return ParseMultiClass(); 3371 } 3372 } 3373 3374 /// ParseObjectList 3375 /// ObjectList :== Object* 3376 bool TGParser::ParseObjectList(MultiClass *MC) { 3377 while (isObjectStart(Lex.getCode())) { 3378 if (ParseObject(MC)) 3379 return true; 3380 } 3381 return false; 3382 } 3383 3384 bool TGParser::ParseFile() { 3385 Lex.Lex(); // Prime the lexer. 3386 if (ParseObjectList()) return true; 3387 3388 // If we have unread input at the end of the file, report it. 3389 if (Lex.getCode() == tgtok::Eof) 3390 return false; 3391 3392 return TokError("Unexpected input at top level"); 3393 } 3394 3395 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3396 LLVM_DUMP_METHOD void RecordsEntry::dump() const { 3397 if (Loop) 3398 Loop->dump(); 3399 if (Rec) 3400 Rec->dump(); 3401 } 3402 3403 LLVM_DUMP_METHOD void ForeachLoop::dump() const { 3404 errs() << "foreach " << IterVar->getAsString() << " = " 3405 << ListValue->getAsString() << " in {\n"; 3406 3407 for (const auto &E : Entries) 3408 E.dump(); 3409 3410 errs() << "}\n"; 3411 } 3412 3413 LLVM_DUMP_METHOD void MultiClass::dump() const { 3414 errs() << "Record:\n"; 3415 Rec.dump(); 3416 3417 errs() << "Defs:\n"; 3418 for (const auto &E : Entries) 3419 E.dump(); 3420 } 3421 #endif 3422