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