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