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::XGetOp: { // 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::XGetOp: 959 Lex.Lex(); // eat the operation 960 if (Lex.getCode() == tgtok::less) { 961 // Parse an optional type suffix, so that you can say 962 // !getop<BaseClass>(someDag) as a shorthand for 963 // !cast<BaseClass>(!getop(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 !getop must be a record type"); 973 // but keep parsing, to consume the operand 974 } 975 } else { 976 Type = RecordRecTy::get({}); 977 } 978 Code = UnOpInit::GETOP; 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::HEAD || 990 Code == UnOpInit::TAIL || 991 Code == UnOpInit::EMPTY) { 992 ListInit *LHSl = dyn_cast<ListInit>(LHS); 993 StringInit *LHSs = dyn_cast<StringInit>(LHS); 994 TypedInit *LHSt = dyn_cast<TypedInit>(LHS); 995 if (!LHSl && !LHSs && !LHSt) { 996 TokError("expected list or string type argument in unary operator"); 997 return nullptr; 998 } 999 if (LHSt) { 1000 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1001 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType()); 1002 if (!LType && !SType) { 1003 TokError("expected list or string type argument in unary operator"); 1004 return nullptr; 1005 } 1006 } 1007 1008 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL || 1009 Code == UnOpInit::SIZE) { 1010 if (!LHSl && !LHSt) { 1011 TokError("expected list type argument in unary operator"); 1012 return nullptr; 1013 } 1014 } 1015 1016 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) { 1017 if (LHSl && LHSl->empty()) { 1018 TokError("empty list argument in unary operator"); 1019 return nullptr; 1020 } 1021 if (LHSl) { 1022 Init *Item = LHSl->getElement(0); 1023 TypedInit *Itemt = dyn_cast<TypedInit>(Item); 1024 if (!Itemt) { 1025 TokError("untyped list element in unary operator"); 1026 return nullptr; 1027 } 1028 Type = (Code == UnOpInit::HEAD) ? Itemt->getType() 1029 : ListRecTy::get(Itemt->getType()); 1030 } else { 1031 assert(LHSt && "expected list type argument in unary operator"); 1032 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType()); 1033 if (!LType) { 1034 TokError("expected list type argument in unary operator"); 1035 return nullptr; 1036 } 1037 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType; 1038 } 1039 } 1040 } 1041 1042 if (!consume(tgtok::r_paren)) { 1043 TokError("expected ')' in unary operator"); 1044 return nullptr; 1045 } 1046 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec); 1047 } 1048 1049 case tgtok::XIsA: { 1050 // Value ::= !isa '<' Type '>' '(' Value ')' 1051 Lex.Lex(); // eat the operation 1052 1053 RecTy *Type = ParseOperatorType(); 1054 if (!Type) 1055 return nullptr; 1056 1057 if (!consume(tgtok::l_paren)) { 1058 TokError("expected '(' after type of !isa"); 1059 return nullptr; 1060 } 1061 1062 Init *LHS = ParseValue(CurRec); 1063 if (!LHS) 1064 return nullptr; 1065 1066 if (!consume(tgtok::r_paren)) { 1067 TokError("expected ')' in !isa"); 1068 return nullptr; 1069 } 1070 1071 return (IsAOpInit::get(Type, LHS))->Fold(); 1072 } 1073 1074 case tgtok::XConcat: 1075 case tgtok::XADD: 1076 case tgtok::XMUL: 1077 case tgtok::XAND: 1078 case tgtok::XOR: 1079 case tgtok::XXOR: 1080 case tgtok::XSRA: 1081 case tgtok::XSRL: 1082 case tgtok::XSHL: 1083 case tgtok::XEq: 1084 case tgtok::XNe: 1085 case tgtok::XLe: 1086 case tgtok::XLt: 1087 case tgtok::XGe: 1088 case tgtok::XGt: 1089 case tgtok::XListConcat: 1090 case tgtok::XListSplat: 1091 case tgtok::XStrConcat: 1092 case tgtok::XSetOp: { // Value ::= !binop '(' Value ',' Value ')' 1093 tgtok::TokKind OpTok = Lex.getCode(); 1094 SMLoc OpLoc = Lex.getLoc(); 1095 Lex.Lex(); // eat the operation 1096 1097 BinOpInit::BinaryOp Code; 1098 switch (OpTok) { 1099 default: llvm_unreachable("Unhandled code!"); 1100 case tgtok::XConcat: Code = BinOpInit::CONCAT; break; 1101 case tgtok::XADD: Code = BinOpInit::ADD; break; 1102 case tgtok::XMUL: Code = BinOpInit::MUL; break; 1103 case tgtok::XAND: Code = BinOpInit::AND; break; 1104 case tgtok::XOR: Code = BinOpInit::OR; break; 1105 case tgtok::XXOR: Code = BinOpInit::XOR; break; 1106 case tgtok::XSRA: Code = BinOpInit::SRA; break; 1107 case tgtok::XSRL: Code = BinOpInit::SRL; break; 1108 case tgtok::XSHL: Code = BinOpInit::SHL; break; 1109 case tgtok::XEq: Code = BinOpInit::EQ; break; 1110 case tgtok::XNe: Code = BinOpInit::NE; break; 1111 case tgtok::XLe: Code = BinOpInit::LE; break; 1112 case tgtok::XLt: Code = BinOpInit::LT; break; 1113 case tgtok::XGe: Code = BinOpInit::GE; break; 1114 case tgtok::XGt: Code = BinOpInit::GT; break; 1115 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break; 1116 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break; 1117 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break; 1118 case tgtok::XSetOp: Code = BinOpInit::SETOP; break; 1119 } 1120 1121 RecTy *Type = nullptr; 1122 RecTy *ArgType = nullptr; 1123 switch (OpTok) { 1124 default: 1125 llvm_unreachable("Unhandled code!"); 1126 case tgtok::XConcat: 1127 case tgtok::XSetOp: 1128 Type = DagRecTy::get(); 1129 ArgType = DagRecTy::get(); 1130 break; 1131 case tgtok::XAND: 1132 case tgtok::XOR: 1133 case tgtok::XXOR: 1134 case tgtok::XSRA: 1135 case tgtok::XSRL: 1136 case tgtok::XSHL: 1137 case tgtok::XADD: 1138 case tgtok::XMUL: 1139 Type = IntRecTy::get(); 1140 ArgType = IntRecTy::get(); 1141 break; 1142 case tgtok::XEq: 1143 case tgtok::XNe: 1144 Type = BitRecTy::get(); 1145 // ArgType for Eq / Ne is not known at this point 1146 break; 1147 case tgtok::XLe: 1148 case tgtok::XLt: 1149 case tgtok::XGe: 1150 case tgtok::XGt: 1151 Type = BitRecTy::get(); 1152 ArgType = IntRecTy::get(); 1153 break; 1154 case tgtok::XListConcat: 1155 // We don't know the list type until we parse the first argument 1156 ArgType = ItemType; 1157 break; 1158 case tgtok::XListSplat: 1159 // Can't do any typechecking until we parse the first argument. 1160 break; 1161 case tgtok::XStrConcat: 1162 Type = StringRecTy::get(); 1163 ArgType = StringRecTy::get(); 1164 break; 1165 } 1166 1167 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) { 1168 Error(OpLoc, Twine("expected value of type '") + 1169 ItemType->getAsString() + "', got '" + 1170 Type->getAsString() + "'"); 1171 return nullptr; 1172 } 1173 1174 if (!consume(tgtok::l_paren)) { 1175 TokError("expected '(' after binary operator"); 1176 return nullptr; 1177 } 1178 1179 SmallVector<Init*, 2> InitList; 1180 1181 for (;;) { 1182 SMLoc InitLoc = Lex.getLoc(); 1183 InitList.push_back(ParseValue(CurRec, ArgType)); 1184 if (!InitList.back()) return nullptr; 1185 1186 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back()); 1187 if (!InitListBack) { 1188 Error(OpLoc, Twine("expected value to be a typed value, got '" + 1189 InitList.back()->getAsString() + "'")); 1190 return nullptr; 1191 } 1192 RecTy *ListType = InitListBack->getType(); 1193 if (!ArgType) { 1194 ArgType = ListType; 1195 1196 switch (Code) { 1197 case BinOpInit::LISTCONCAT: 1198 if (!isa<ListRecTy>(ArgType)) { 1199 Error(InitLoc, Twine("expected a list, got value of type '") + 1200 ArgType->getAsString() + "'"); 1201 return nullptr; 1202 } 1203 break; 1204 case BinOpInit::LISTSPLAT: 1205 if (ItemType && InitList.size() == 1) { 1206 if (!isa<ListRecTy>(ItemType)) { 1207 Error(OpLoc, 1208 Twine("expected output type to be a list, got type '") + 1209 ItemType->getAsString() + "'"); 1210 return nullptr; 1211 } 1212 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) { 1213 Error(OpLoc, Twine("expected first arg type to be '") + 1214 ArgType->getAsString() + 1215 "', got value of type '" + 1216 cast<ListRecTy>(ItemType) 1217 ->getElementType() 1218 ->getAsString() + 1219 "'"); 1220 return nullptr; 1221 } 1222 } 1223 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) { 1224 Error(InitLoc, Twine("expected second parameter to be an int, got " 1225 "value of type '") + 1226 ArgType->getAsString() + "'"); 1227 return nullptr; 1228 } 1229 ArgType = nullptr; // Broken invariant: types not identical. 1230 break; 1231 case BinOpInit::EQ: 1232 case BinOpInit::NE: 1233 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) && 1234 !ArgType->typeIsConvertibleTo(StringRecTy::get())) { 1235 Error(InitLoc, Twine("expected int, bits, or string; got value of " 1236 "type '") + ArgType->getAsString() + "'"); 1237 return nullptr; 1238 } 1239 break; 1240 default: llvm_unreachable("other ops have fixed argument types"); 1241 } 1242 } else { 1243 RecTy *Resolved = resolveTypes(ArgType, ListType); 1244 if (!Resolved) { 1245 Error(InitLoc, Twine("expected value of type '") + 1246 ArgType->getAsString() + "', got '" + 1247 ListType->getAsString() + "'"); 1248 return nullptr; 1249 } 1250 if (Code != BinOpInit::ADD && Code != BinOpInit::AND && 1251 Code != BinOpInit::OR && Code != BinOpInit::XOR && 1252 Code != BinOpInit::SRA && Code != BinOpInit::SRL && 1253 Code != BinOpInit::SHL && Code != BinOpInit::MUL) 1254 ArgType = Resolved; 1255 } 1256 1257 // Deal with BinOps whose arguments have different types, by 1258 // rewriting ArgType in between them. 1259 switch (Code) { 1260 case BinOpInit::SETOP: 1261 // After parsing the first dag argument, switch to expecting 1262 // a record, with no restriction on its superclasses. 1263 ArgType = RecordRecTy::get({}); 1264 break; 1265 default: 1266 break; 1267 } 1268 1269 if (!consume(tgtok::comma)) 1270 break; 1271 } 1272 1273 if (!consume(tgtok::r_paren)) { 1274 TokError("expected ')' in operator"); 1275 return nullptr; 1276 } 1277 1278 // listconcat returns a list with type of the argument. 1279 if (Code == BinOpInit::LISTCONCAT) 1280 Type = ArgType; 1281 // listsplat returns a list of type of the *first* argument. 1282 if (Code == BinOpInit::LISTSPLAT) 1283 Type = cast<TypedInit>(InitList.front())->getType()->getListTy(); 1284 1285 // We allow multiple operands to associative operators like !strconcat as 1286 // shorthand for nesting them. 1287 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT || 1288 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD || 1289 Code == BinOpInit::AND || Code == BinOpInit::OR || 1290 Code == BinOpInit::XOR || Code == BinOpInit::MUL) { 1291 while (InitList.size() > 2) { 1292 Init *RHS = InitList.pop_back_val(); 1293 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec); 1294 InitList.back() = RHS; 1295 } 1296 } 1297 1298 if (InitList.size() == 2) 1299 return (BinOpInit::get(Code, InitList[0], InitList[1], Type)) 1300 ->Fold(CurRec); 1301 1302 Error(OpLoc, "expected two operands to operator"); 1303 return nullptr; 1304 } 1305 1306 case tgtok::XForEach: { 1307 // Value ::= !foreach '(' Id ',' Value ',' Value ')' 1308 SMLoc OpLoc = Lex.getLoc(); 1309 Lex.Lex(); // eat the operation 1310 if (Lex.getCode() != tgtok::l_paren) { 1311 TokError("expected '(' after !foreach"); 1312 return nullptr; 1313 } 1314 1315 if (Lex.Lex() != tgtok::Id) { // eat the '(' 1316 TokError("first argument of !foreach must be an identifier"); 1317 return nullptr; 1318 } 1319 1320 Init *LHS = StringInit::get(Lex.getCurStrVal()); 1321 Lex.Lex(); 1322 1323 if (CurRec && CurRec->getValue(LHS)) { 1324 TokError((Twine("iteration variable '") + LHS->getAsString() + 1325 "' already defined") 1326 .str()); 1327 return nullptr; 1328 } 1329 1330 if (!consume(tgtok::comma)) { // eat the id 1331 TokError("expected ',' in ternary operator"); 1332 return nullptr; 1333 } 1334 1335 Init *MHS = ParseValue(CurRec); 1336 if (!MHS) 1337 return nullptr; 1338 1339 if (!consume(tgtok::comma)) { 1340 TokError("expected ',' in ternary operator"); 1341 return nullptr; 1342 } 1343 1344 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1345 if (!MHSt) { 1346 TokError("could not get type of !foreach input"); 1347 return nullptr; 1348 } 1349 1350 RecTy *InEltType = nullptr; 1351 RecTy *OutEltType = nullptr; 1352 bool IsDAG = false; 1353 1354 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) { 1355 InEltType = InListTy->getElementType(); 1356 if (ItemType) { 1357 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) { 1358 OutEltType = OutListTy->getElementType(); 1359 } else { 1360 Error(OpLoc, 1361 "expected value of type '" + Twine(ItemType->getAsString()) + 1362 "', but got !foreach of list type"); 1363 return nullptr; 1364 } 1365 } 1366 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) { 1367 InEltType = InDagTy; 1368 if (ItemType && !isa<DagRecTy>(ItemType)) { 1369 Error(OpLoc, 1370 "expected value of type '" + Twine(ItemType->getAsString()) + 1371 "', but got !foreach of dag type"); 1372 return nullptr; 1373 } 1374 IsDAG = true; 1375 } else { 1376 TokError("!foreach must have list or dag input"); 1377 return nullptr; 1378 } 1379 1380 // We need to create a temporary record to provide a scope for the 1381 // iteration variable. 1382 std::unique_ptr<Record> ParseRecTmp; 1383 Record *ParseRec = CurRec; 1384 if (!ParseRec) { 1385 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1386 ParseRec = ParseRecTmp.get(); 1387 } 1388 1389 ParseRec->addValue(RecordVal(LHS, InEltType, false)); 1390 Init *RHS = ParseValue(ParseRec, OutEltType); 1391 ParseRec->removeValue(LHS); 1392 if (!RHS) 1393 return nullptr; 1394 1395 if (!consume(tgtok::r_paren)) { 1396 TokError("expected ')' in binary operator"); 1397 return nullptr; 1398 } 1399 1400 RecTy *OutType; 1401 if (IsDAG) { 1402 OutType = InEltType; 1403 } else { 1404 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1405 if (!RHSt) { 1406 TokError("could not get type of !foreach result"); 1407 return nullptr; 1408 } 1409 OutType = RHSt->getType()->getListTy(); 1410 } 1411 1412 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType)) 1413 ->Fold(CurRec); 1414 } 1415 1416 case tgtok::XDag: 1417 case tgtok::XIf: 1418 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 1419 TernOpInit::TernaryOp Code; 1420 RecTy *Type = nullptr; 1421 1422 tgtok::TokKind LexCode = Lex.getCode(); 1423 Lex.Lex(); // eat the operation 1424 switch (LexCode) { 1425 default: llvm_unreachable("Unhandled code!"); 1426 case tgtok::XDag: 1427 Code = TernOpInit::DAG; 1428 Type = DagRecTy::get(); 1429 ItemType = nullptr; 1430 break; 1431 case tgtok::XIf: 1432 Code = TernOpInit::IF; 1433 break; 1434 case tgtok::XSubst: 1435 Code = TernOpInit::SUBST; 1436 break; 1437 } 1438 if (!consume(tgtok::l_paren)) { 1439 TokError("expected '(' after ternary operator"); 1440 return nullptr; 1441 } 1442 1443 Init *LHS = ParseValue(CurRec); 1444 if (!LHS) return nullptr; 1445 1446 if (!consume(tgtok::comma)) { 1447 TokError("expected ',' in ternary operator"); 1448 return nullptr; 1449 } 1450 1451 SMLoc MHSLoc = Lex.getLoc(); 1452 Init *MHS = ParseValue(CurRec, ItemType); 1453 if (!MHS) 1454 return nullptr; 1455 1456 if (!consume(tgtok::comma)) { 1457 TokError("expected ',' in ternary operator"); 1458 return nullptr; 1459 } 1460 1461 SMLoc RHSLoc = Lex.getLoc(); 1462 Init *RHS = ParseValue(CurRec, ItemType); 1463 if (!RHS) 1464 return nullptr; 1465 1466 if (!consume(tgtok::r_paren)) { 1467 TokError("expected ')' in binary operator"); 1468 return nullptr; 1469 } 1470 1471 switch (LexCode) { 1472 default: llvm_unreachable("Unhandled code!"); 1473 case tgtok::XDag: { 1474 TypedInit *MHSt = dyn_cast<TypedInit>(MHS); 1475 if (!MHSt && !isa<UnsetInit>(MHS)) { 1476 Error(MHSLoc, "could not determine type of the child list in !dag"); 1477 return nullptr; 1478 } 1479 if (MHSt && !isa<ListRecTy>(MHSt->getType())) { 1480 Error(MHSLoc, Twine("expected list of children, got type '") + 1481 MHSt->getType()->getAsString() + "'"); 1482 return nullptr; 1483 } 1484 1485 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1486 if (!RHSt && !isa<UnsetInit>(RHS)) { 1487 Error(RHSLoc, "could not determine type of the name list in !dag"); 1488 return nullptr; 1489 } 1490 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) { 1491 Error(RHSLoc, Twine("expected list<string>, got type '") + 1492 RHSt->getType()->getAsString() + "'"); 1493 return nullptr; 1494 } 1495 1496 if (!MHSt && !RHSt) { 1497 Error(MHSLoc, 1498 "cannot have both unset children and unset names in !dag"); 1499 return nullptr; 1500 } 1501 break; 1502 } 1503 case tgtok::XIf: { 1504 RecTy *MHSTy = nullptr; 1505 RecTy *RHSTy = nullptr; 1506 1507 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS)) 1508 MHSTy = MHSt->getType(); 1509 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS)) 1510 MHSTy = BitsRecTy::get(MHSbits->getNumBits()); 1511 if (isa<BitInit>(MHS)) 1512 MHSTy = BitRecTy::get(); 1513 1514 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS)) 1515 RHSTy = RHSt->getType(); 1516 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS)) 1517 RHSTy = BitsRecTy::get(RHSbits->getNumBits()); 1518 if (isa<BitInit>(RHS)) 1519 RHSTy = BitRecTy::get(); 1520 1521 // For UnsetInit, it's typed from the other hand. 1522 if (isa<UnsetInit>(MHS)) 1523 MHSTy = RHSTy; 1524 if (isa<UnsetInit>(RHS)) 1525 RHSTy = MHSTy; 1526 1527 if (!MHSTy || !RHSTy) { 1528 TokError("could not get type for !if"); 1529 return nullptr; 1530 } 1531 1532 Type = resolveTypes(MHSTy, RHSTy); 1533 if (!Type) { 1534 TokError(Twine("inconsistent types '") + MHSTy->getAsString() + 1535 "' and '" + RHSTy->getAsString() + "' for !if"); 1536 return nullptr; 1537 } 1538 break; 1539 } 1540 case tgtok::XSubst: { 1541 TypedInit *RHSt = dyn_cast<TypedInit>(RHS); 1542 if (!RHSt) { 1543 TokError("could not get type for !subst"); 1544 return nullptr; 1545 } 1546 Type = RHSt->getType(); 1547 break; 1548 } 1549 } 1550 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec); 1551 } 1552 1553 case tgtok::XCond: 1554 return ParseOperationCond(CurRec, ItemType); 1555 1556 case tgtok::XFoldl: { 1557 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')' 1558 Lex.Lex(); // eat the operation 1559 if (!consume(tgtok::l_paren)) { 1560 TokError("expected '(' after !foldl"); 1561 return nullptr; 1562 } 1563 1564 Init *StartUntyped = ParseValue(CurRec); 1565 if (!StartUntyped) 1566 return nullptr; 1567 1568 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped); 1569 if (!Start) { 1570 TokError(Twine("could not get type of !foldl start: '") + 1571 StartUntyped->getAsString() + "'"); 1572 return nullptr; 1573 } 1574 1575 if (!consume(tgtok::comma)) { 1576 TokError("expected ',' in !foldl"); 1577 return nullptr; 1578 } 1579 1580 Init *ListUntyped = ParseValue(CurRec); 1581 if (!ListUntyped) 1582 return nullptr; 1583 1584 TypedInit *List = dyn_cast<TypedInit>(ListUntyped); 1585 if (!List) { 1586 TokError(Twine("could not get type of !foldl list: '") + 1587 ListUntyped->getAsString() + "'"); 1588 return nullptr; 1589 } 1590 1591 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType()); 1592 if (!ListType) { 1593 TokError(Twine("!foldl list must be a list, but is of type '") + 1594 List->getType()->getAsString()); 1595 return nullptr; 1596 } 1597 1598 if (Lex.getCode() != tgtok::comma) { 1599 TokError("expected ',' in !foldl"); 1600 return nullptr; 1601 } 1602 1603 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1604 TokError("third argument of !foldl must be an identifier"); 1605 return nullptr; 1606 } 1607 1608 Init *A = StringInit::get(Lex.getCurStrVal()); 1609 if (CurRec && CurRec->getValue(A)) { 1610 TokError((Twine("left !foldl variable '") + A->getAsString() + 1611 "' already defined") 1612 .str()); 1613 return nullptr; 1614 } 1615 1616 if (Lex.Lex() != tgtok::comma) { // eat the id 1617 TokError("expected ',' in !foldl"); 1618 return nullptr; 1619 } 1620 1621 if (Lex.Lex() != tgtok::Id) { // eat the ',' 1622 TokError("fourth argument of !foldl must be an identifier"); 1623 return nullptr; 1624 } 1625 1626 Init *B = StringInit::get(Lex.getCurStrVal()); 1627 if (CurRec && CurRec->getValue(B)) { 1628 TokError((Twine("right !foldl variable '") + B->getAsString() + 1629 "' already defined") 1630 .str()); 1631 return nullptr; 1632 } 1633 1634 if (Lex.Lex() != tgtok::comma) { // eat the id 1635 TokError("expected ',' in !foldl"); 1636 return nullptr; 1637 } 1638 Lex.Lex(); // eat the ',' 1639 1640 // We need to create a temporary record to provide a scope for the 1641 // two variables. 1642 std::unique_ptr<Record> ParseRecTmp; 1643 Record *ParseRec = CurRec; 1644 if (!ParseRec) { 1645 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records); 1646 ParseRec = ParseRecTmp.get(); 1647 } 1648 1649 ParseRec->addValue(RecordVal(A, Start->getType(), false)); 1650 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false)); 1651 Init *ExprUntyped = ParseValue(ParseRec); 1652 ParseRec->removeValue(A); 1653 ParseRec->removeValue(B); 1654 if (!ExprUntyped) 1655 return nullptr; 1656 1657 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped); 1658 if (!Expr) { 1659 TokError("could not get type of !foldl expression"); 1660 return nullptr; 1661 } 1662 1663 if (Expr->getType() != Start->getType()) { 1664 TokError(Twine("!foldl expression must be of same type as start (") + 1665 Start->getType()->getAsString() + "), but is of type " + 1666 Expr->getType()->getAsString()); 1667 return nullptr; 1668 } 1669 1670 if (!consume(tgtok::r_paren)) { 1671 TokError("expected ')' in fold operator"); 1672 return nullptr; 1673 } 1674 1675 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType()) 1676 ->Fold(CurRec); 1677 } 1678 } 1679 } 1680 1681 /// ParseOperatorType - Parse a type for an operator. This returns 1682 /// null on error. 1683 /// 1684 /// OperatorType ::= '<' Type '>' 1685 /// 1686 RecTy *TGParser::ParseOperatorType() { 1687 RecTy *Type = nullptr; 1688 1689 if (!consume(tgtok::less)) { 1690 TokError("expected type name for operator"); 1691 return nullptr; 1692 } 1693 1694 Type = ParseType(); 1695 1696 if (!Type) { 1697 TokError("expected type name for operator"); 1698 return nullptr; 1699 } 1700 1701 if (!consume(tgtok::greater)) { 1702 TokError("expected type name for operator"); 1703 return nullptr; 1704 } 1705 1706 return Type; 1707 } 1708 1709 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) { 1710 Lex.Lex(); // eat the operation 'cond' 1711 1712 if (!consume(tgtok::l_paren)) { 1713 TokError("expected '(' after !cond operator"); 1714 return nullptr; 1715 } 1716 1717 // Parse through '[Case: Val,]+' 1718 SmallVector<Init *, 4> Case; 1719 SmallVector<Init *, 4> Val; 1720 while (true) { 1721 if (consume(tgtok::r_paren)) 1722 break; 1723 1724 Init *V = ParseValue(CurRec); 1725 if (!V) 1726 return nullptr; 1727 Case.push_back(V); 1728 1729 if (!consume(tgtok::colon)) { 1730 TokError("expected ':' following a condition in !cond operator"); 1731 return nullptr; 1732 } 1733 1734 V = ParseValue(CurRec, ItemType); 1735 if (!V) 1736 return nullptr; 1737 Val.push_back(V); 1738 1739 if (consume(tgtok::r_paren)) 1740 break; 1741 1742 if (!consume(tgtok::comma)) { 1743 TokError("expected ',' or ')' following a value in !cond operator"); 1744 return nullptr; 1745 } 1746 } 1747 1748 if (Case.size() < 1) { 1749 TokError("there should be at least 1 'condition : value' in the !cond operator"); 1750 return nullptr; 1751 } 1752 1753 // resolve type 1754 RecTy *Type = nullptr; 1755 for (Init *V : Val) { 1756 RecTy *VTy = nullptr; 1757 if (TypedInit *Vt = dyn_cast<TypedInit>(V)) 1758 VTy = Vt->getType(); 1759 if (BitsInit *Vbits = dyn_cast<BitsInit>(V)) 1760 VTy = BitsRecTy::get(Vbits->getNumBits()); 1761 if (isa<BitInit>(V)) 1762 VTy = BitRecTy::get(); 1763 1764 if (Type == nullptr) { 1765 if (!isa<UnsetInit>(V)) 1766 Type = VTy; 1767 } else { 1768 if (!isa<UnsetInit>(V)) { 1769 RecTy *RType = resolveTypes(Type, VTy); 1770 if (!RType) { 1771 TokError(Twine("inconsistent types '") + Type->getAsString() + 1772 "' and '" + VTy->getAsString() + "' for !cond"); 1773 return nullptr; 1774 } 1775 Type = RType; 1776 } 1777 } 1778 } 1779 1780 if (!Type) { 1781 TokError("could not determine type for !cond from its arguments"); 1782 return nullptr; 1783 } 1784 return CondOpInit::get(Case, Val, Type)->Fold(CurRec); 1785 } 1786 1787 /// ParseSimpleValue - Parse a tblgen value. This returns null on error. 1788 /// 1789 /// SimpleValue ::= IDValue 1790 /// SimpleValue ::= INTVAL 1791 /// SimpleValue ::= STRVAL+ 1792 /// SimpleValue ::= CODEFRAGMENT 1793 /// SimpleValue ::= '?' 1794 /// SimpleValue ::= '{' ValueList '}' 1795 /// SimpleValue ::= ID '<' ValueListNE '>' 1796 /// SimpleValue ::= '[' ValueList ']' 1797 /// SimpleValue ::= '(' IDValue DagArgList ')' 1798 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')' 1799 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')' 1800 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')' 1801 /// SimpleValue ::= SRATOK '(' Value ',' Value ')' 1802 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')' 1803 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')' 1804 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')' 1805 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')' 1806 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')' 1807 /// 1808 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType, 1809 IDParseMode Mode) { 1810 Init *R = nullptr; 1811 switch (Lex.getCode()) { 1812 default: TokError("Unknown token when parsing a value"); break; 1813 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break; 1814 case tgtok::BinaryIntVal: { 1815 auto BinaryVal = Lex.getCurBinaryIntVal(); 1816 SmallVector<Init*, 16> Bits(BinaryVal.second); 1817 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i) 1818 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i)); 1819 R = BitsInit::get(Bits); 1820 Lex.Lex(); 1821 break; 1822 } 1823 case tgtok::StrVal: { 1824 std::string Val = Lex.getCurStrVal(); 1825 Lex.Lex(); 1826 1827 // Handle multiple consecutive concatenated strings. 1828 while (Lex.getCode() == tgtok::StrVal) { 1829 Val += Lex.getCurStrVal(); 1830 Lex.Lex(); 1831 } 1832 1833 R = StringInit::get(Val); 1834 break; 1835 } 1836 case tgtok::CodeFragment: 1837 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc()); 1838 Lex.Lex(); 1839 break; 1840 case tgtok::question: 1841 R = UnsetInit::get(); 1842 Lex.Lex(); 1843 break; 1844 case tgtok::Id: { 1845 SMLoc NameLoc = Lex.getLoc(); 1846 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 1847 if (Lex.Lex() != tgtok::less) // consume the Id. 1848 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue 1849 1850 // Value ::= ID '<' ValueListNE '>' 1851 if (Lex.Lex() == tgtok::greater) { 1852 TokError("expected non-empty value list"); 1853 return nullptr; 1854 } 1855 1856 // This is a CLASS<initvalslist> expression. This is supposed to synthesize 1857 // a new anonymous definition, deriving from CLASS<initvalslist> with no 1858 // body. 1859 Record *Class = Records.getClass(Name->getValue()); 1860 if (!Class) { 1861 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'"); 1862 return nullptr; 1863 } 1864 1865 SmallVector<Init *, 8> Args; 1866 ParseValueList(Args, CurRec, Class); 1867 if (Args.empty()) return nullptr; 1868 1869 if (!consume(tgtok::greater)) { 1870 TokError("expected '>' at end of value list"); 1871 return nullptr; 1872 } 1873 1874 // Typecheck the template arguments list 1875 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs(); 1876 if (ExpectedArgs.size() < Args.size()) { 1877 Error(NameLoc, 1878 "More template args specified than expected"); 1879 return nullptr; 1880 } 1881 1882 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) { 1883 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]); 1884 if (i < Args.size()) { 1885 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) { 1886 RecTy *ExpectedType = ExpectedArg->getType(); 1887 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) { 1888 Error(NameLoc, 1889 "Value specified for template argument #" + Twine(i) + " (" + 1890 ExpectedArg->getNameInitAsString() + ") is of type '" + 1891 TI->getType()->getAsString() + "', expected '" + 1892 ExpectedType->getAsString() + "': " + TI->getAsString()); 1893 return nullptr; 1894 } 1895 continue; 1896 } 1897 } else if (ExpectedArg->getValue()->isComplete()) 1898 continue; 1899 1900 Error(NameLoc, 1901 "Value not specified for template argument #" + Twine(i) + " (" + 1902 ExpectedArgs[i]->getAsUnquotedString() + ")"); 1903 return nullptr; 1904 } 1905 1906 return VarDefInit::get(Class, Args)->Fold(); 1907 } 1908 case tgtok::l_brace: { // Value ::= '{' ValueList '}' 1909 SMLoc BraceLoc = Lex.getLoc(); 1910 Lex.Lex(); // eat the '{' 1911 SmallVector<Init*, 16> Vals; 1912 1913 if (Lex.getCode() != tgtok::r_brace) { 1914 ParseValueList(Vals, CurRec); 1915 if (Vals.empty()) return nullptr; 1916 } 1917 if (!consume(tgtok::r_brace)) { 1918 TokError("expected '}' at end of bit list value"); 1919 return nullptr; 1920 } 1921 1922 SmallVector<Init *, 16> NewBits; 1923 1924 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it 1925 // first. We'll first read everything in to a vector, then we can reverse 1926 // it to get the bits in the correct order for the BitsInit value. 1927 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1928 // FIXME: The following two loops would not be duplicated 1929 // if the API was a little more orthogonal. 1930 1931 // bits<n> values are allowed to initialize n bits. 1932 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) { 1933 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) 1934 NewBits.push_back(BI->getBit((e - i) - 1)); 1935 continue; 1936 } 1937 // bits<n> can also come from variable initializers. 1938 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) { 1939 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) { 1940 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i) 1941 NewBits.push_back(VI->getBit((e - i) - 1)); 1942 continue; 1943 } 1944 // Fallthrough to try convert this to a bit. 1945 } 1946 // All other values must be convertible to just a single bit. 1947 Init *Bit = Vals[i]->getCastTo(BitRecTy::get()); 1948 if (!Bit) { 1949 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() + 1950 ") is not convertable to a bit"); 1951 return nullptr; 1952 } 1953 NewBits.push_back(Bit); 1954 } 1955 std::reverse(NewBits.begin(), NewBits.end()); 1956 return BitsInit::get(NewBits); 1957 } 1958 case tgtok::l_square: { // Value ::= '[' ValueList ']' 1959 Lex.Lex(); // eat the '[' 1960 SmallVector<Init*, 16> Vals; 1961 1962 RecTy *DeducedEltTy = nullptr; 1963 ListRecTy *GivenListTy = nullptr; 1964 1965 if (ItemType) { 1966 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType); 1967 if (!ListType) { 1968 TokError(Twine("Type mismatch for list, expected list type, got ") + 1969 ItemType->getAsString()); 1970 return nullptr; 1971 } 1972 GivenListTy = ListType; 1973 } 1974 1975 if (Lex.getCode() != tgtok::r_square) { 1976 ParseValueList(Vals, CurRec, nullptr, 1977 GivenListTy ? GivenListTy->getElementType() : nullptr); 1978 if (Vals.empty()) return nullptr; 1979 } 1980 if (!consume(tgtok::r_square)) { 1981 TokError("expected ']' at end of list value"); 1982 return nullptr; 1983 } 1984 1985 RecTy *GivenEltTy = nullptr; 1986 if (consume(tgtok::less)) { 1987 // Optional list element type 1988 GivenEltTy = ParseType(); 1989 if (!GivenEltTy) { 1990 // Couldn't parse element type 1991 return nullptr; 1992 } 1993 1994 if (!consume(tgtok::greater)) { 1995 TokError("expected '>' at end of list element type"); 1996 return nullptr; 1997 } 1998 } 1999 2000 // Check elements 2001 RecTy *EltTy = nullptr; 2002 for (Init *V : Vals) { 2003 TypedInit *TArg = dyn_cast<TypedInit>(V); 2004 if (TArg) { 2005 if (EltTy) { 2006 EltTy = resolveTypes(EltTy, TArg->getType()); 2007 if (!EltTy) { 2008 TokError("Incompatible types in list elements"); 2009 return nullptr; 2010 } 2011 } else { 2012 EltTy = TArg->getType(); 2013 } 2014 } 2015 } 2016 2017 if (GivenEltTy) { 2018 if (EltTy) { 2019 // Verify consistency 2020 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) { 2021 TokError("Incompatible types in list elements"); 2022 return nullptr; 2023 } 2024 } 2025 EltTy = GivenEltTy; 2026 } 2027 2028 if (!EltTy) { 2029 if (!ItemType) { 2030 TokError("No type for list"); 2031 return nullptr; 2032 } 2033 DeducedEltTy = GivenListTy->getElementType(); 2034 } else { 2035 // Make sure the deduced type is compatible with the given type 2036 if (GivenListTy) { 2037 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) { 2038 TokError(Twine("Element type mismatch for list: element type '") + 2039 EltTy->getAsString() + "' not convertible to '" + 2040 GivenListTy->getElementType()->getAsString()); 2041 return nullptr; 2042 } 2043 } 2044 DeducedEltTy = EltTy; 2045 } 2046 2047 return ListInit::get(Vals, DeducedEltTy); 2048 } 2049 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')' 2050 Lex.Lex(); // eat the '(' 2051 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast && 2052 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetOp) { 2053 TokError("expected identifier in dag init"); 2054 return nullptr; 2055 } 2056 2057 Init *Operator = ParseValue(CurRec); 2058 if (!Operator) return nullptr; 2059 2060 // If the operator name is present, parse it. 2061 StringInit *OperatorName = nullptr; 2062 if (consume(tgtok::colon)) { 2063 if (Lex.getCode() != tgtok::VarName) { // eat the ':' 2064 TokError("expected variable name in dag operator"); 2065 return nullptr; 2066 } 2067 OperatorName = StringInit::get(Lex.getCurStrVal()); 2068 Lex.Lex(); // eat the VarName. 2069 } 2070 2071 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs; 2072 if (Lex.getCode() != tgtok::r_paren) { 2073 ParseDagArgList(DagArgs, CurRec); 2074 if (DagArgs.empty()) return nullptr; 2075 } 2076 2077 if (!consume(tgtok::r_paren)) { 2078 TokError("expected ')' in dag init"); 2079 return nullptr; 2080 } 2081 2082 return DagInit::get(Operator, OperatorName, DagArgs); 2083 } 2084 2085 case tgtok::XHead: 2086 case tgtok::XTail: 2087 case tgtok::XSize: 2088 case tgtok::XEmpty: 2089 case tgtok::XCast: 2090 case tgtok::XGetOp: // Value ::= !unop '(' Value ')' 2091 case tgtok::XIsA: 2092 case tgtok::XConcat: 2093 case tgtok::XDag: 2094 case tgtok::XADD: 2095 case tgtok::XMUL: 2096 case tgtok::XNOT: 2097 case tgtok::XAND: 2098 case tgtok::XOR: 2099 case tgtok::XXOR: 2100 case tgtok::XSRA: 2101 case tgtok::XSRL: 2102 case tgtok::XSHL: 2103 case tgtok::XEq: 2104 case tgtok::XNe: 2105 case tgtok::XLe: 2106 case tgtok::XLt: 2107 case tgtok::XGe: 2108 case tgtok::XGt: 2109 case tgtok::XListConcat: 2110 case tgtok::XListSplat: 2111 case tgtok::XStrConcat: 2112 case tgtok::XSetOp: // Value ::= !binop '(' Value ',' Value ')' 2113 case tgtok::XIf: 2114 case tgtok::XCond: 2115 case tgtok::XFoldl: 2116 case tgtok::XForEach: 2117 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')' 2118 return ParseOperation(CurRec, ItemType); 2119 } 2120 } 2121 2122 return R; 2123 } 2124 2125 /// ParseValue - Parse a tblgen value. This returns null on error. 2126 /// 2127 /// Value ::= SimpleValue ValueSuffix* 2128 /// ValueSuffix ::= '{' BitList '}' 2129 /// ValueSuffix ::= '[' BitList ']' 2130 /// ValueSuffix ::= '.' ID 2131 /// 2132 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) { 2133 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode); 2134 if (!Result) return nullptr; 2135 2136 // Parse the suffixes now if present. 2137 while (true) { 2138 switch (Lex.getCode()) { 2139 default: return Result; 2140 case tgtok::l_brace: { 2141 if (Mode == ParseNameMode) 2142 // This is the beginning of the object body. 2143 return Result; 2144 2145 SMLoc CurlyLoc = Lex.getLoc(); 2146 Lex.Lex(); // eat the '{' 2147 SmallVector<unsigned, 16> Ranges; 2148 ParseRangeList(Ranges); 2149 if (Ranges.empty()) return nullptr; 2150 2151 // Reverse the bitlist. 2152 std::reverse(Ranges.begin(), Ranges.end()); 2153 Result = Result->convertInitializerBitRange(Ranges); 2154 if (!Result) { 2155 Error(CurlyLoc, "Invalid bit range for value"); 2156 return nullptr; 2157 } 2158 2159 // Eat the '}'. 2160 if (!consume(tgtok::r_brace)) { 2161 TokError("expected '}' at end of bit range list"); 2162 return nullptr; 2163 } 2164 break; 2165 } 2166 case tgtok::l_square: { 2167 SMLoc SquareLoc = Lex.getLoc(); 2168 Lex.Lex(); // eat the '[' 2169 SmallVector<unsigned, 16> Ranges; 2170 ParseRangeList(Ranges); 2171 if (Ranges.empty()) return nullptr; 2172 2173 Result = Result->convertInitListSlice(Ranges); 2174 if (!Result) { 2175 Error(SquareLoc, "Invalid range for list slice"); 2176 return nullptr; 2177 } 2178 2179 // Eat the ']'. 2180 if (!consume(tgtok::r_square)) { 2181 TokError("expected ']' at end of list slice"); 2182 return nullptr; 2183 } 2184 break; 2185 } 2186 case tgtok::dot: { 2187 if (Lex.Lex() != tgtok::Id) { // eat the . 2188 TokError("expected field identifier after '.'"); 2189 return nullptr; 2190 } 2191 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2192 if (!Result->getFieldType(FieldName)) { 2193 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" + 2194 Result->getAsString() + "'"); 2195 return nullptr; 2196 } 2197 Result = FieldInit::get(Result, FieldName)->Fold(CurRec); 2198 Lex.Lex(); // eat field name 2199 break; 2200 } 2201 2202 case tgtok::paste: 2203 SMLoc PasteLoc = Lex.getLoc(); 2204 TypedInit *LHS = dyn_cast<TypedInit>(Result); 2205 if (!LHS) { 2206 Error(PasteLoc, "LHS of paste is not typed!"); 2207 return nullptr; 2208 } 2209 2210 // Check if it's a 'listA # listB' 2211 if (isa<ListRecTy>(LHS->getType())) { 2212 Lex.Lex(); // Eat the '#'. 2213 2214 switch (Lex.getCode()) { 2215 case tgtok::colon: 2216 case tgtok::semi: 2217 case tgtok::l_brace: 2218 Result = LHS; // trailing paste, ignore. 2219 break; 2220 default: 2221 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode); 2222 if (!RHSResult) 2223 return nullptr; 2224 Result = BinOpInit::getListConcat(LHS, RHSResult); 2225 } 2226 break; 2227 } 2228 2229 // Create a !strconcat() operation, first casting each operand to 2230 // a string if necessary. 2231 if (LHS->getType() != StringRecTy::get()) { 2232 auto CastLHS = dyn_cast<TypedInit>( 2233 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get()) 2234 ->Fold(CurRec)); 2235 if (!CastLHS) { 2236 Error(PasteLoc, 2237 Twine("can't cast '") + LHS->getAsString() + "' to string"); 2238 return nullptr; 2239 } 2240 LHS = CastLHS; 2241 } 2242 2243 TypedInit *RHS = nullptr; 2244 2245 Lex.Lex(); // Eat the '#'. 2246 switch (Lex.getCode()) { 2247 case tgtok::colon: 2248 case tgtok::semi: 2249 case tgtok::l_brace: 2250 // These are all of the tokens that can begin an object body. 2251 // Some of these can also begin values but we disallow those cases 2252 // because they are unlikely to be useful. 2253 2254 // Trailing paste, concat with an empty string. 2255 RHS = StringInit::get(""); 2256 break; 2257 2258 default: 2259 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode); 2260 if (!RHSResult) 2261 return nullptr; 2262 RHS = dyn_cast<TypedInit>(RHSResult); 2263 if (!RHS) { 2264 Error(PasteLoc, "RHS of paste is not typed!"); 2265 return nullptr; 2266 } 2267 2268 if (RHS->getType() != StringRecTy::get()) { 2269 auto CastRHS = dyn_cast<TypedInit>( 2270 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get()) 2271 ->Fold(CurRec)); 2272 if (!CastRHS) { 2273 Error(PasteLoc, 2274 Twine("can't cast '") + RHS->getAsString() + "' to string"); 2275 return nullptr; 2276 } 2277 RHS = CastRHS; 2278 } 2279 2280 break; 2281 } 2282 2283 Result = BinOpInit::getStrConcat(LHS, RHS); 2284 break; 2285 } 2286 } 2287 } 2288 2289 /// ParseDagArgList - Parse the argument list for a dag literal expression. 2290 /// 2291 /// DagArg ::= Value (':' VARNAME)? 2292 /// DagArg ::= VARNAME 2293 /// DagArgList ::= DagArg 2294 /// DagArgList ::= DagArgList ',' DagArg 2295 void TGParser::ParseDagArgList( 2296 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result, 2297 Record *CurRec) { 2298 2299 while (true) { 2300 // DagArg ::= VARNAME 2301 if (Lex.getCode() == tgtok::VarName) { 2302 // A missing value is treated like '?'. 2303 StringInit *VarName = StringInit::get(Lex.getCurStrVal()); 2304 Result.emplace_back(UnsetInit::get(), VarName); 2305 Lex.Lex(); 2306 } else { 2307 // DagArg ::= Value (':' VARNAME)? 2308 Init *Val = ParseValue(CurRec); 2309 if (!Val) { 2310 Result.clear(); 2311 return; 2312 } 2313 2314 // If the variable name is present, add it. 2315 StringInit *VarName = nullptr; 2316 if (Lex.getCode() == tgtok::colon) { 2317 if (Lex.Lex() != tgtok::VarName) { // eat the ':' 2318 TokError("expected variable name in dag literal"); 2319 Result.clear(); 2320 return; 2321 } 2322 VarName = StringInit::get(Lex.getCurStrVal()); 2323 Lex.Lex(); // eat the VarName. 2324 } 2325 2326 Result.push_back(std::make_pair(Val, VarName)); 2327 } 2328 if (!consume(tgtok::comma)) 2329 break; 2330 } 2331 } 2332 2333 /// ParseValueList - Parse a comma separated list of values, returning them as a 2334 /// vector. Note that this always expects to be able to parse at least one 2335 /// value. It returns an empty list if this is not possible. 2336 /// 2337 /// ValueList ::= Value (',' Value) 2338 /// 2339 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec, 2340 Record *ArgsRec, RecTy *EltTy) { 2341 RecTy *ItemType = EltTy; 2342 unsigned int ArgN = 0; 2343 if (ArgsRec && !EltTy) { 2344 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2345 if (TArgs.empty()) { 2346 TokError("template argument provided to non-template class"); 2347 Result.clear(); 2348 return; 2349 } 2350 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2351 if (!RV) { 2352 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN] 2353 << ")\n"; 2354 } 2355 assert(RV && "Template argument record not found??"); 2356 ItemType = RV->getType(); 2357 ++ArgN; 2358 } 2359 Result.push_back(ParseValue(CurRec, ItemType)); 2360 if (!Result.back()) { 2361 Result.clear(); 2362 return; 2363 } 2364 2365 while (consume(tgtok::comma)) { 2366 // ignore trailing comma for lists 2367 if (Lex.getCode() == tgtok::r_square) 2368 return; 2369 2370 if (ArgsRec && !EltTy) { 2371 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs(); 2372 if (ArgN >= TArgs.size()) { 2373 TokError("too many template arguments"); 2374 Result.clear(); 2375 return; 2376 } 2377 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]); 2378 assert(RV && "Template argument record not found??"); 2379 ItemType = RV->getType(); 2380 ++ArgN; 2381 } 2382 Result.push_back(ParseValue(CurRec, ItemType)); 2383 if (!Result.back()) { 2384 Result.clear(); 2385 return; 2386 } 2387 } 2388 } 2389 2390 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an 2391 /// empty string on error. This can happen in a number of different context's, 2392 /// including within a def or in the template args for a def (which which case 2393 /// CurRec will be non-null) and within the template args for a multiclass (in 2394 /// which case CurRec will be null, but CurMultiClass will be set). This can 2395 /// also happen within a def that is within a multiclass, which will set both 2396 /// CurRec and CurMultiClass. 2397 /// 2398 /// Declaration ::= FIELD? Type ID ('=' Value)? 2399 /// 2400 Init *TGParser::ParseDeclaration(Record *CurRec, 2401 bool ParsingTemplateArgs) { 2402 // Read the field prefix if present. 2403 bool HasField = consume(tgtok::Field); 2404 2405 RecTy *Type = ParseType(); 2406 if (!Type) return nullptr; 2407 2408 if (Lex.getCode() != tgtok::Id) { 2409 TokError("Expected identifier in declaration"); 2410 return nullptr; 2411 } 2412 2413 std::string Str = Lex.getCurStrVal(); 2414 if (Str == "NAME") { 2415 TokError("'" + Str + "' is a reserved variable name"); 2416 return nullptr; 2417 } 2418 2419 SMLoc IdLoc = Lex.getLoc(); 2420 Init *DeclName = StringInit::get(Str); 2421 Lex.Lex(); 2422 2423 if (ParsingTemplateArgs) { 2424 if (CurRec) 2425 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":"); 2426 else 2427 assert(CurMultiClass); 2428 if (CurMultiClass) 2429 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, 2430 "::"); 2431 } 2432 2433 // Add the value. 2434 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type, HasField))) 2435 return nullptr; 2436 2437 // If a value is present, parse it. 2438 if (consume(tgtok::equal)) { 2439 SMLoc ValLoc = Lex.getLoc(); 2440 Init *Val = ParseValue(CurRec, Type); 2441 if (!Val || 2442 SetValue(CurRec, ValLoc, DeclName, None, Val)) 2443 // Return the name, even if an error is thrown. This is so that we can 2444 // continue to make some progress, even without the value having been 2445 // initialized. 2446 return DeclName; 2447 } 2448 2449 return DeclName; 2450 } 2451 2452 /// ParseForeachDeclaration - Read a foreach declaration, returning 2453 /// the name of the declared object or a NULL Init on error. Return 2454 /// the name of the parsed initializer list through ForeachListName. 2455 /// 2456 /// ForeachDeclaration ::= ID '=' '{' RangeList '}' 2457 /// ForeachDeclaration ::= ID '=' RangePiece 2458 /// ForeachDeclaration ::= ID '=' Value 2459 /// 2460 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) { 2461 if (Lex.getCode() != tgtok::Id) { 2462 TokError("Expected identifier in foreach declaration"); 2463 return nullptr; 2464 } 2465 2466 Init *DeclName = StringInit::get(Lex.getCurStrVal()); 2467 Lex.Lex(); 2468 2469 // If a value is present, parse it. 2470 if (!consume(tgtok::equal)) { 2471 TokError("Expected '=' in foreach declaration"); 2472 return nullptr; 2473 } 2474 2475 RecTy *IterType = nullptr; 2476 SmallVector<unsigned, 16> Ranges; 2477 2478 switch (Lex.getCode()) { 2479 case tgtok::l_brace: { // '{' RangeList '}' 2480 Lex.Lex(); // eat the '{' 2481 ParseRangeList(Ranges); 2482 if (!consume(tgtok::r_brace)) { 2483 TokError("expected '}' at end of bit range list"); 2484 return nullptr; 2485 } 2486 break; 2487 } 2488 2489 default: { 2490 SMLoc ValueLoc = Lex.getLoc(); 2491 Init *I = ParseValue(nullptr); 2492 if (!I) 2493 return nullptr; 2494 2495 TypedInit *TI = dyn_cast<TypedInit>(I); 2496 if (TI && isa<ListRecTy>(TI->getType())) { 2497 ForeachListValue = I; 2498 IterType = cast<ListRecTy>(TI->getType())->getElementType(); 2499 break; 2500 } 2501 2502 if (TI) { 2503 if (ParseRangePiece(Ranges, TI)) 2504 return nullptr; 2505 break; 2506 } 2507 2508 std::string Type; 2509 if (TI) 2510 Type = (Twine("' of type '") + TI->getType()->getAsString()).str(); 2511 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'"); 2512 if (CurMultiClass) { 2513 PrintNote({}, "references to multiclass template arguments cannot be " 2514 "resolved at this time"); 2515 } 2516 return nullptr; 2517 } 2518 } 2519 2520 2521 if (!Ranges.empty()) { 2522 assert(!IterType && "Type already initialized?"); 2523 IterType = IntRecTy::get(); 2524 std::vector<Init*> Values; 2525 for (unsigned R : Ranges) 2526 Values.push_back(IntInit::get(R)); 2527 ForeachListValue = ListInit::get(Values, IterType); 2528 } 2529 2530 if (!IterType) 2531 return nullptr; 2532 2533 return VarInit::get(DeclName, IterType); 2534 } 2535 2536 /// ParseTemplateArgList - Read a template argument list, which is a non-empty 2537 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are 2538 /// template args for a def, which may or may not be in a multiclass. If null, 2539 /// these are the template args for a multiclass. 2540 /// 2541 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>' 2542 /// 2543 bool TGParser::ParseTemplateArgList(Record *CurRec) { 2544 assert(Lex.getCode() == tgtok::less && "Not a template arg list!"); 2545 Lex.Lex(); // eat the '<' 2546 2547 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec; 2548 2549 // Read the first declaration. 2550 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2551 if (!TemplArg) 2552 return true; 2553 2554 TheRecToAddTo->addTemplateArg(TemplArg); 2555 2556 while (consume(tgtok::comma)) { 2557 // Read the following declarations. 2558 SMLoc Loc = Lex.getLoc(); 2559 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/); 2560 if (!TemplArg) 2561 return true; 2562 2563 if (TheRecToAddTo->isTemplateArg(TemplArg)) 2564 return Error(Loc, "template argument with the same name has already been " 2565 "defined"); 2566 2567 TheRecToAddTo->addTemplateArg(TemplArg); 2568 } 2569 2570 if (!consume(tgtok::greater)) 2571 return TokError("expected '>' at end of template argument list"); 2572 return false; 2573 } 2574 2575 /// ParseBodyItem - Parse a single item at within the body of a def or class. 2576 /// 2577 /// BodyItem ::= Declaration ';' 2578 /// BodyItem ::= LET ID OptionalBitList '=' Value ';' 2579 /// BodyItem ::= Defvar 2580 bool TGParser::ParseBodyItem(Record *CurRec) { 2581 if (Lex.getCode() == tgtok::Defvar) 2582 return ParseDefvar(); 2583 2584 if (Lex.getCode() != tgtok::Let) { 2585 if (!ParseDeclaration(CurRec, false)) 2586 return true; 2587 2588 if (!consume(tgtok::semi)) 2589 return TokError("expected ';' after declaration"); 2590 return false; 2591 } 2592 2593 // LET ID OptionalRangeList '=' Value ';' 2594 if (Lex.Lex() != tgtok::Id) 2595 return TokError("expected field identifier after let"); 2596 2597 SMLoc IdLoc = Lex.getLoc(); 2598 StringInit *FieldName = StringInit::get(Lex.getCurStrVal()); 2599 Lex.Lex(); // eat the field name. 2600 2601 SmallVector<unsigned, 16> BitList; 2602 if (ParseOptionalBitList(BitList)) 2603 return true; 2604 std::reverse(BitList.begin(), BitList.end()); 2605 2606 if (!consume(tgtok::equal)) 2607 return TokError("expected '=' in let expression"); 2608 2609 RecordVal *Field = CurRec->getValue(FieldName); 2610 if (!Field) 2611 return TokError("Value '" + FieldName->getValue() + "' unknown!"); 2612 2613 RecTy *Type = Field->getType(); 2614 if (!BitList.empty() && isa<BitsRecTy>(Type)) { 2615 // When assigning to a subset of a 'bits' object, expect the RHS to have 2616 // the type of that subset instead of the type of the whole object. 2617 Type = BitsRecTy::get(BitList.size()); 2618 } 2619 2620 Init *Val = ParseValue(CurRec, Type); 2621 if (!Val) return true; 2622 2623 if (!consume(tgtok::semi)) 2624 return TokError("expected ';' after let expression"); 2625 2626 return SetValue(CurRec, IdLoc, FieldName, BitList, Val); 2627 } 2628 2629 /// ParseBody - Read the body of a class or def. Return true on error, false on 2630 /// success. 2631 /// 2632 /// Body ::= ';' 2633 /// Body ::= '{' BodyList '}' 2634 /// BodyList BodyItem* 2635 /// 2636 bool TGParser::ParseBody(Record *CurRec) { 2637 // If this is a null definition, just eat the semi and return. 2638 if (consume(tgtok::semi)) 2639 return false; 2640 2641 if (!consume(tgtok::l_brace)) 2642 return TokError("Expected ';' or '{' to start body"); 2643 2644 // An object body introduces a new scope for local variables. 2645 TGLocalVarScope *BodyScope = PushLocalScope(); 2646 2647 while (Lex.getCode() != tgtok::r_brace) 2648 if (ParseBodyItem(CurRec)) 2649 return true; 2650 2651 PopLocalScope(BodyScope); 2652 2653 // Eat the '}'. 2654 Lex.Lex(); 2655 return false; 2656 } 2657 2658 /// Apply the current let bindings to \a CurRec. 2659 /// \returns true on error, false otherwise. 2660 bool TGParser::ApplyLetStack(Record *CurRec) { 2661 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack) 2662 for (LetRecord &LR : LetInfo) 2663 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value)) 2664 return true; 2665 return false; 2666 } 2667 2668 bool TGParser::ApplyLetStack(RecordsEntry &Entry) { 2669 if (Entry.Rec) 2670 return ApplyLetStack(Entry.Rec.get()); 2671 2672 for (auto &E : Entry.Loop->Entries) { 2673 if (ApplyLetStack(E)) 2674 return true; 2675 } 2676 2677 return false; 2678 } 2679 2680 /// ParseObjectBody - Parse the body of a def or class. This consists of an 2681 /// optional ClassList followed by a Body. CurRec is the current def or class 2682 /// that is being parsed. 2683 /// 2684 /// ObjectBody ::= BaseClassList Body 2685 /// BaseClassList ::= /*empty*/ 2686 /// BaseClassList ::= ':' BaseClassListNE 2687 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)* 2688 /// 2689 bool TGParser::ParseObjectBody(Record *CurRec) { 2690 // If there is a baseclass list, read it. 2691 if (consume(tgtok::colon)) { 2692 2693 // Read all of the subclasses. 2694 SubClassReference SubClass = ParseSubClassReference(CurRec, false); 2695 while (true) { 2696 // Check for error. 2697 if (!SubClass.Rec) return true; 2698 2699 // Add it. 2700 if (AddSubClass(CurRec, SubClass)) 2701 return true; 2702 2703 if (!consume(tgtok::comma)) 2704 break; 2705 SubClass = ParseSubClassReference(CurRec, false); 2706 } 2707 } 2708 2709 if (ApplyLetStack(CurRec)) 2710 return true; 2711 2712 return ParseBody(CurRec); 2713 } 2714 2715 /// ParseDef - Parse and return a top level or multiclass def, return the record 2716 /// corresponding to it. This returns null on error. 2717 /// 2718 /// DefInst ::= DEF ObjectName ObjectBody 2719 /// 2720 bool TGParser::ParseDef(MultiClass *CurMultiClass) { 2721 SMLoc DefLoc = Lex.getLoc(); 2722 assert(Lex.getCode() == tgtok::Def && "Unknown tok"); 2723 Lex.Lex(); // Eat the 'def' token. 2724 2725 // Parse ObjectName and make a record for it. 2726 std::unique_ptr<Record> CurRec; 2727 Init *Name = ParseObjectName(CurMultiClass); 2728 if (!Name) 2729 return true; 2730 2731 if (isa<UnsetInit>(Name)) 2732 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records, 2733 /*Anonymous=*/true); 2734 else 2735 CurRec = std::make_unique<Record>(Name, DefLoc, Records); 2736 2737 if (ParseObjectBody(CurRec.get())) 2738 return true; 2739 2740 return addEntry(std::move(CurRec)); 2741 } 2742 2743 /// ParseDefset - Parse a defset statement. 2744 /// 2745 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}' 2746 /// 2747 bool TGParser::ParseDefset() { 2748 assert(Lex.getCode() == tgtok::Defset); 2749 Lex.Lex(); // Eat the 'defset' token 2750 2751 DefsetRecord Defset; 2752 Defset.Loc = Lex.getLoc(); 2753 RecTy *Type = ParseType(); 2754 if (!Type) 2755 return true; 2756 if (!isa<ListRecTy>(Type)) 2757 return Error(Defset.Loc, "expected list type"); 2758 Defset.EltTy = cast<ListRecTy>(Type)->getElementType(); 2759 2760 if (Lex.getCode() != tgtok::Id) 2761 return TokError("expected identifier"); 2762 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2763 if (Records.getGlobal(DeclName->getValue())) 2764 return TokError("def or global variable of this name already exists"); 2765 2766 if (Lex.Lex() != tgtok::equal) // Eat the identifier 2767 return TokError("expected '='"); 2768 if (Lex.Lex() != tgtok::l_brace) // Eat the '=' 2769 return TokError("expected '{'"); 2770 SMLoc BraceLoc = Lex.getLoc(); 2771 Lex.Lex(); // Eat the '{' 2772 2773 Defsets.push_back(&Defset); 2774 bool Err = ParseObjectList(nullptr); 2775 Defsets.pop_back(); 2776 if (Err) 2777 return true; 2778 2779 if (!consume(tgtok::r_brace)) { 2780 TokError("expected '}' at end of defset"); 2781 return Error(BraceLoc, "to match this '{'"); 2782 } 2783 2784 Records.addExtraGlobal(DeclName->getValue(), 2785 ListInit::get(Defset.Elements, Defset.EltTy)); 2786 return false; 2787 } 2788 2789 /// ParseDefvar - Parse a defvar statement. 2790 /// 2791 /// Defvar ::= DEFVAR Id '=' Value ';' 2792 /// 2793 bool TGParser::ParseDefvar() { 2794 assert(Lex.getCode() == tgtok::Defvar); 2795 Lex.Lex(); // Eat the 'defvar' token 2796 2797 if (Lex.getCode() != tgtok::Id) 2798 return TokError("expected identifier"); 2799 StringInit *DeclName = StringInit::get(Lex.getCurStrVal()); 2800 if (CurLocalScope) { 2801 if (CurLocalScope->varAlreadyDefined(DeclName->getValue())) 2802 return TokError("local variable of this name already exists"); 2803 } else { 2804 if (Records.getGlobal(DeclName->getValue())) 2805 return TokError("def or global variable of this name already exists"); 2806 } 2807 2808 Lex.Lex(); 2809 if (!consume(tgtok::equal)) 2810 return TokError("expected '='"); 2811 2812 Init *Value = ParseValue(nullptr); 2813 if (!Value) 2814 return true; 2815 2816 if (!consume(tgtok::semi)) 2817 return TokError("expected ';'"); 2818 2819 if (CurLocalScope) 2820 CurLocalScope->addVar(DeclName->getValue(), Value); 2821 else 2822 Records.addExtraGlobal(DeclName->getValue(), Value); 2823 2824 return false; 2825 } 2826 2827 /// ParseForeach - Parse a for statement. Return the record corresponding 2828 /// to it. This returns true on error. 2829 /// 2830 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}' 2831 /// Foreach ::= FOREACH Declaration IN Object 2832 /// 2833 bool TGParser::ParseForeach(MultiClass *CurMultiClass) { 2834 SMLoc Loc = Lex.getLoc(); 2835 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok"); 2836 Lex.Lex(); // Eat the 'for' token. 2837 2838 // Make a temporary object to record items associated with the for 2839 // loop. 2840 Init *ListValue = nullptr; 2841 VarInit *IterName = ParseForeachDeclaration(ListValue); 2842 if (!IterName) 2843 return TokError("expected declaration in for"); 2844 2845 if (!consume(tgtok::In)) 2846 return TokError("Unknown tok"); 2847 2848 // Create a loop object and remember it. 2849 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue)); 2850 2851 // A foreach loop introduces a new scope for local variables. 2852 TGLocalVarScope *ForeachScope = PushLocalScope(); 2853 2854 if (Lex.getCode() != tgtok::l_brace) { 2855 // FOREACH Declaration IN Object 2856 if (ParseObject(CurMultiClass)) 2857 return true; 2858 } else { 2859 SMLoc BraceLoc = Lex.getLoc(); 2860 // Otherwise, this is a group foreach. 2861 Lex.Lex(); // eat the '{'. 2862 2863 // Parse the object list. 2864 if (ParseObjectList(CurMultiClass)) 2865 return true; 2866 2867 if (!consume(tgtok::r_brace)) { 2868 TokError("expected '}' at end of foreach command"); 2869 return Error(BraceLoc, "to match this '{'"); 2870 } 2871 } 2872 2873 PopLocalScope(ForeachScope); 2874 2875 // Resolve the loop or store it for later resolution. 2876 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2877 Loops.pop_back(); 2878 2879 return addEntry(std::move(Loop)); 2880 } 2881 2882 /// ParseIf - Parse an if statement. 2883 /// 2884 /// If ::= IF Value THEN IfBody 2885 /// If ::= IF Value THEN IfBody ELSE IfBody 2886 /// 2887 bool TGParser::ParseIf(MultiClass *CurMultiClass) { 2888 SMLoc Loc = Lex.getLoc(); 2889 assert(Lex.getCode() == tgtok::If && "Unknown tok"); 2890 Lex.Lex(); // Eat the 'if' token. 2891 2892 // Make a temporary object to record items associated with the for 2893 // loop. 2894 Init *Condition = ParseValue(nullptr); 2895 if (!Condition) 2896 return true; 2897 2898 if (!consume(tgtok::Then)) 2899 return TokError("Unknown tok"); 2900 2901 // We have to be able to save if statements to execute later, and they have 2902 // to live on the same stack as foreach loops. The simplest implementation 2903 // technique is to convert each 'then' or 'else' clause *into* a foreach 2904 // loop, over a list of length 0 or 1 depending on the condition, and with no 2905 // iteration variable being assigned. 2906 2907 ListInit *EmptyList = ListInit::get({}, BitRecTy::get()); 2908 ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get()); 2909 RecTy *BitListTy = ListRecTy::get(BitRecTy::get()); 2910 2911 // The foreach containing the then-clause selects SingletonList if 2912 // the condition is true. 2913 Init *ThenClauseList = 2914 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList, 2915 BitListTy) 2916 ->Fold(nullptr); 2917 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList)); 2918 2919 if (ParseIfBody(CurMultiClass, "then")) 2920 return true; 2921 2922 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back()); 2923 Loops.pop_back(); 2924 2925 if (addEntry(std::move(Loop))) 2926 return true; 2927 2928 // Now look for an optional else clause. The if-else syntax has the usual 2929 // dangling-else ambiguity, and by greedily matching an else here if we can, 2930 // we implement the usual resolution of pairing with the innermost unmatched 2931 // if. 2932 if (consume(tgtok::ElseKW)) { 2933 // The foreach containing the else-clause uses the same pair of lists as 2934 // above, but this time, selects SingletonList if the condition is *false*. 2935 Init *ElseClauseList = 2936 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList, 2937 BitListTy) 2938 ->Fold(nullptr); 2939 Loops.push_back( 2940 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList)); 2941 2942 if (ParseIfBody(CurMultiClass, "else")) 2943 return true; 2944 2945 Loop = std::move(Loops.back()); 2946 Loops.pop_back(); 2947 2948 if (addEntry(std::move(Loop))) 2949 return true; 2950 } 2951 2952 return false; 2953 } 2954 2955 /// ParseIfBody - Parse the then-clause or else-clause of an if statement. 2956 /// 2957 /// IfBody ::= Object 2958 /// IfBody ::= '{' ObjectList '}' 2959 /// 2960 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) { 2961 TGLocalVarScope *BodyScope = PushLocalScope(); 2962 2963 if (Lex.getCode() != tgtok::l_brace) { 2964 // A single object. 2965 if (ParseObject(CurMultiClass)) 2966 return true; 2967 } else { 2968 SMLoc BraceLoc = Lex.getLoc(); 2969 // A braced block. 2970 Lex.Lex(); // eat the '{'. 2971 2972 // Parse the object list. 2973 if (ParseObjectList(CurMultiClass)) 2974 return true; 2975 2976 if (!consume(tgtok::r_brace)) { 2977 TokError("expected '}' at end of '" + Kind + "' clause"); 2978 return Error(BraceLoc, "to match this '{'"); 2979 } 2980 } 2981 2982 PopLocalScope(BodyScope); 2983 return false; 2984 } 2985 2986 /// ParseClass - Parse a tblgen class definition. 2987 /// 2988 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody 2989 /// 2990 bool TGParser::ParseClass() { 2991 assert(Lex.getCode() == tgtok::Class && "Unexpected token!"); 2992 Lex.Lex(); 2993 2994 if (Lex.getCode() != tgtok::Id) 2995 return TokError("expected class name after 'class' keyword"); 2996 2997 Record *CurRec = Records.getClass(Lex.getCurStrVal()); 2998 if (CurRec) { 2999 // If the body was previously defined, this is an error. 3000 if (!CurRec->getValues().empty() || 3001 !CurRec->getSuperClasses().empty() || 3002 !CurRec->getTemplateArgs().empty()) 3003 return TokError("Class '" + CurRec->getNameInitAsString() + 3004 "' already defined"); 3005 } else { 3006 // If this is the first reference to this class, create and add it. 3007 auto NewRec = 3008 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records, 3009 /*Class=*/true); 3010 CurRec = NewRec.get(); 3011 Records.addClass(std::move(NewRec)); 3012 } 3013 Lex.Lex(); // eat the name. 3014 3015 // If there are template args, parse them. 3016 if (Lex.getCode() == tgtok::less) 3017 if (ParseTemplateArgList(CurRec)) 3018 return true; 3019 3020 return ParseObjectBody(CurRec); 3021 } 3022 3023 /// ParseLetList - Parse a non-empty list of assignment expressions into a list 3024 /// of LetRecords. 3025 /// 3026 /// LetList ::= LetItem (',' LetItem)* 3027 /// LetItem ::= ID OptionalRangeList '=' Value 3028 /// 3029 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) { 3030 do { 3031 if (Lex.getCode() != tgtok::Id) { 3032 TokError("expected identifier in let definition"); 3033 Result.clear(); 3034 return; 3035 } 3036 3037 StringInit *Name = StringInit::get(Lex.getCurStrVal()); 3038 SMLoc NameLoc = Lex.getLoc(); 3039 Lex.Lex(); // Eat the identifier. 3040 3041 // Check for an optional RangeList. 3042 SmallVector<unsigned, 16> Bits; 3043 if (ParseOptionalRangeList(Bits)) { 3044 Result.clear(); 3045 return; 3046 } 3047 std::reverse(Bits.begin(), Bits.end()); 3048 3049 if (!consume(tgtok::equal)) { 3050 TokError("expected '=' in let expression"); 3051 Result.clear(); 3052 return; 3053 } 3054 3055 Init *Val = ParseValue(nullptr); 3056 if (!Val) { 3057 Result.clear(); 3058 return; 3059 } 3060 3061 // Now that we have everything, add the record. 3062 Result.emplace_back(Name, Bits, Val, NameLoc); 3063 } while (consume(tgtok::comma)); 3064 } 3065 3066 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of 3067 /// different related productions. This works inside multiclasses too. 3068 /// 3069 /// Object ::= LET LetList IN '{' ObjectList '}' 3070 /// Object ::= LET LetList IN Object 3071 /// 3072 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) { 3073 assert(Lex.getCode() == tgtok::Let && "Unexpected token"); 3074 Lex.Lex(); 3075 3076 // Add this entry to the let stack. 3077 SmallVector<LetRecord, 8> LetInfo; 3078 ParseLetList(LetInfo); 3079 if (LetInfo.empty()) return true; 3080 LetStack.push_back(std::move(LetInfo)); 3081 3082 if (!consume(tgtok::In)) 3083 return TokError("expected 'in' at end of top-level 'let'"); 3084 3085 TGLocalVarScope *LetScope = PushLocalScope(); 3086 3087 // If this is a scalar let, just handle it now 3088 if (Lex.getCode() != tgtok::l_brace) { 3089 // LET LetList IN Object 3090 if (ParseObject(CurMultiClass)) 3091 return true; 3092 } else { // Object ::= LETCommand '{' ObjectList '}' 3093 SMLoc BraceLoc = Lex.getLoc(); 3094 // Otherwise, this is a group let. 3095 Lex.Lex(); // eat the '{'. 3096 3097 // Parse the object list. 3098 if (ParseObjectList(CurMultiClass)) 3099 return true; 3100 3101 if (!consume(tgtok::r_brace)) { 3102 TokError("expected '}' at end of top level let command"); 3103 return Error(BraceLoc, "to match this '{'"); 3104 } 3105 } 3106 3107 PopLocalScope(LetScope); 3108 3109 // Outside this let scope, this let block is not active. 3110 LetStack.pop_back(); 3111 return false; 3112 } 3113 3114 /// ParseMultiClass - Parse a multiclass definition. 3115 /// 3116 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? 3117 /// ':' BaseMultiClassList '{' MultiClassObject+ '}' 3118 /// MultiClassObject ::= DefInst 3119 /// MultiClassObject ::= MultiClassInst 3120 /// MultiClassObject ::= DefMInst 3121 /// MultiClassObject ::= LETCommand '{' ObjectList '}' 3122 /// MultiClassObject ::= LETCommand Object 3123 /// 3124 bool TGParser::ParseMultiClass() { 3125 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token"); 3126 Lex.Lex(); // Eat the multiclass token. 3127 3128 if (Lex.getCode() != tgtok::Id) 3129 return TokError("expected identifier after multiclass for name"); 3130 std::string Name = Lex.getCurStrVal(); 3131 3132 auto Result = 3133 MultiClasses.insert(std::make_pair(Name, 3134 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records))); 3135 3136 if (!Result.second) 3137 return TokError("multiclass '" + Name + "' already defined"); 3138 3139 CurMultiClass = Result.first->second.get(); 3140 Lex.Lex(); // Eat the identifier. 3141 3142 // If there are template args, parse them. 3143 if (Lex.getCode() == tgtok::less) 3144 if (ParseTemplateArgList(nullptr)) 3145 return true; 3146 3147 bool inherits = false; 3148 3149 // If there are submulticlasses, parse them. 3150 if (consume(tgtok::colon)) { 3151 inherits = true; 3152 3153 // Read all of the submulticlasses. 3154 SubMultiClassReference SubMultiClass = 3155 ParseSubMultiClassReference(CurMultiClass); 3156 while (true) { 3157 // Check for error. 3158 if (!SubMultiClass.MC) return true; 3159 3160 // Add it. 3161 if (AddSubMultiClass(CurMultiClass, SubMultiClass)) 3162 return true; 3163 3164 if (!consume(tgtok::comma)) 3165 break; 3166 SubMultiClass = ParseSubMultiClassReference(CurMultiClass); 3167 } 3168 } 3169 3170 if (Lex.getCode() != tgtok::l_brace) { 3171 if (!inherits) 3172 return TokError("expected '{' in multiclass definition"); 3173 if (!consume(tgtok::semi)) 3174 return TokError("expected ';' in multiclass definition"); 3175 } else { 3176 if (Lex.Lex() == tgtok::r_brace) // eat the '{'. 3177 return TokError("multiclass must contain at least one def"); 3178 3179 // A multiclass body introduces a new scope for local variables. 3180 TGLocalVarScope *MulticlassScope = PushLocalScope(); 3181 3182 while (Lex.getCode() != tgtok::r_brace) { 3183 switch (Lex.getCode()) { 3184 default: 3185 return TokError("expected 'let', 'def', 'defm', 'defvar', 'foreach' " 3186 "or 'if' in multiclass body"); 3187 case tgtok::Let: 3188 case tgtok::Def: 3189 case tgtok::Defm: 3190 case tgtok::Defvar: 3191 case tgtok::Foreach: 3192 case tgtok::If: 3193 if (ParseObject(CurMultiClass)) 3194 return true; 3195 break; 3196 } 3197 } 3198 Lex.Lex(); // eat the '}'. 3199 3200 PopLocalScope(MulticlassScope); 3201 } 3202 3203 CurMultiClass = nullptr; 3204 return false; 3205 } 3206 3207 /// ParseDefm - Parse the instantiation of a multiclass. 3208 /// 3209 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';' 3210 /// 3211 bool TGParser::ParseDefm(MultiClass *CurMultiClass) { 3212 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!"); 3213 Lex.Lex(); // eat the defm 3214 3215 Init *DefmName = ParseObjectName(CurMultiClass); 3216 if (!DefmName) 3217 return true; 3218 if (isa<UnsetInit>(DefmName)) { 3219 DefmName = Records.getNewAnonymousName(); 3220 if (CurMultiClass) 3221 DefmName = BinOpInit::getStrConcat( 3222 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass), 3223 StringRecTy::get()), 3224 DefmName); 3225 } 3226 3227 if (Lex.getCode() != tgtok::colon) 3228 return TokError("expected ':' after defm identifier"); 3229 3230 // Keep track of the new generated record definitions. 3231 std::vector<RecordsEntry> NewEntries; 3232 3233 // This record also inherits from a regular class (non-multiclass)? 3234 bool InheritFromClass = false; 3235 3236 // eat the colon. 3237 Lex.Lex(); 3238 3239 SMLoc SubClassLoc = Lex.getLoc(); 3240 SubClassReference Ref = ParseSubClassReference(nullptr, true); 3241 3242 while (true) { 3243 if (!Ref.Rec) return true; 3244 3245 // To instantiate a multiclass, we need to first get the multiclass, then 3246 // instantiate each def contained in the multiclass with the SubClassRef 3247 // template parameters. 3248 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get(); 3249 assert(MC && "Didn't lookup multiclass correctly?"); 3250 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs; 3251 3252 // Verify that the correct number of template arguments were specified. 3253 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs(); 3254 if (TArgs.size() < TemplateVals.size()) 3255 return Error(SubClassLoc, 3256 "more template args specified than multiclass expects"); 3257 3258 SubstStack Substs; 3259 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) { 3260 if (i < TemplateVals.size()) { 3261 Substs.emplace_back(TArgs[i], TemplateVals[i]); 3262 } else { 3263 Init *Default = MC->Rec.getValue(TArgs[i])->getValue(); 3264 if (!Default->isComplete()) { 3265 return Error(SubClassLoc, 3266 "value not specified for template argument #" + 3267 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() + 3268 ") of multiclass '" + MC->Rec.getNameInitAsString() + 3269 "'"); 3270 } 3271 Substs.emplace_back(TArgs[i], Default); 3272 } 3273 } 3274 3275 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName); 3276 3277 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries, 3278 &SubClassLoc)) 3279 return true; 3280 3281 if (!consume(tgtok::comma)) 3282 break; 3283 3284 if (Lex.getCode() != tgtok::Id) 3285 return TokError("expected identifier"); 3286 3287 SubClassLoc = Lex.getLoc(); 3288 3289 // A defm can inherit from regular classes (non-multiclass) as 3290 // long as they come in the end of the inheritance list. 3291 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr); 3292 3293 if (InheritFromClass) 3294 break; 3295 3296 Ref = ParseSubClassReference(nullptr, true); 3297 } 3298 3299 if (InheritFromClass) { 3300 // Process all the classes to inherit as if they were part of a 3301 // regular 'def' and inherit all record values. 3302 SubClassReference SubClass = ParseSubClassReference(nullptr, false); 3303 while (true) { 3304 // Check for error. 3305 if (!SubClass.Rec) return true; 3306 3307 // Get the expanded definition prototypes and teach them about 3308 // the record values the current class to inherit has 3309 for (auto &E : NewEntries) { 3310 // Add it. 3311 if (AddSubClass(E, SubClass)) 3312 return true; 3313 } 3314 3315 if (!consume(tgtok::comma)) 3316 break; 3317 SubClass = ParseSubClassReference(nullptr, false); 3318 } 3319 } 3320 3321 for (auto &E : NewEntries) { 3322 if (ApplyLetStack(E)) 3323 return true; 3324 3325 addEntry(std::move(E)); 3326 } 3327 3328 if (!consume(tgtok::semi)) 3329 return TokError("expected ';' at end of defm"); 3330 3331 return false; 3332 } 3333 3334 /// ParseObject 3335 /// Object ::= ClassInst 3336 /// Object ::= DefInst 3337 /// Object ::= MultiClassInst 3338 /// Object ::= DefMInst 3339 /// Object ::= LETCommand '{' ObjectList '}' 3340 /// Object ::= LETCommand Object 3341 /// Object ::= Defset 3342 /// Object ::= Defvar 3343 bool TGParser::ParseObject(MultiClass *MC) { 3344 switch (Lex.getCode()) { 3345 default: 3346 return TokError("Expected class, def, defm, defset, multiclass, let, " 3347 "foreach or if"); 3348 case tgtok::Let: return ParseTopLevelLet(MC); 3349 case tgtok::Def: return ParseDef(MC); 3350 case tgtok::Foreach: return ParseForeach(MC); 3351 case tgtok::If: return ParseIf(MC); 3352 case tgtok::Defm: return ParseDefm(MC); 3353 case tgtok::Defset: 3354 if (MC) 3355 return TokError("defset is not allowed inside multiclass"); 3356 return ParseDefset(); 3357 case tgtok::Defvar: 3358 return ParseDefvar(); 3359 case tgtok::Class: 3360 if (MC) 3361 return TokError("class is not allowed inside multiclass"); 3362 if (!Loops.empty()) 3363 return TokError("class is not allowed inside foreach loop"); 3364 return ParseClass(); 3365 case tgtok::MultiClass: 3366 if (!Loops.empty()) 3367 return TokError("multiclass is not allowed inside foreach loop"); 3368 return ParseMultiClass(); 3369 } 3370 } 3371 3372 /// ParseObjectList 3373 /// ObjectList :== Object* 3374 bool TGParser::ParseObjectList(MultiClass *MC) { 3375 while (isObjectStart(Lex.getCode())) { 3376 if (ParseObject(MC)) 3377 return true; 3378 } 3379 return false; 3380 } 3381 3382 bool TGParser::ParseFile() { 3383 Lex.Lex(); // Prime the lexer. 3384 if (ParseObjectList()) return true; 3385 3386 // If we have unread input at the end of the file, report it. 3387 if (Lex.getCode() == tgtok::Eof) 3388 return false; 3389 3390 return TokError("Unexpected input at top level"); 3391 } 3392 3393 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3394 LLVM_DUMP_METHOD void RecordsEntry::dump() const { 3395 if (Loop) 3396 Loop->dump(); 3397 if (Rec) 3398 Rec->dump(); 3399 } 3400 3401 LLVM_DUMP_METHOD void ForeachLoop::dump() const { 3402 errs() << "foreach " << IterVar->getAsString() << " = " 3403 << ListValue->getAsString() << " in {\n"; 3404 3405 for (const auto &E : Entries) 3406 E.dump(); 3407 3408 errs() << "}\n"; 3409 } 3410 3411 LLVM_DUMP_METHOD void MultiClass::dump() const { 3412 errs() << "Record:\n"; 3413 Rec.dump(); 3414 3415 errs() << "Defs:\n"; 3416 for (const auto &E : Entries) 3417 E.dump(); 3418 } 3419 #endif 3420