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