[RISCV] Refactor predicates for rvv intrinsic patterns.
[llvm-project.git] / llvm / lib / TableGen / TGParser.cpp
blobecd19b98e1b271f89311bb72b6dc088f9c2dd176
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.
11 //===----------------------------------------------------------------------===//
13 #include "TGParser.h"
14 #include "llvm/ADT/DenseMapInfo.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 #include <cassert>
25 #include <cstdint>
26 #include <limits>
28 using namespace llvm;
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
34 namespace llvm {
36 struct SubClassReference {
37 SMRange RefRange;
38 Record *Rec;
39 SmallVector<Init*, 4> TemplateArgs;
41 SubClassReference() : Rec(nullptr) {}
43 bool isInvalid() const { return Rec == nullptr; }
46 struct SubMultiClassReference {
47 SMRange RefRange;
48 MultiClass *MC;
49 SmallVector<Init*, 4> TemplateArgs;
51 SubMultiClassReference() : MC(nullptr) {}
53 bool isInvalid() const { return MC == nullptr; }
54 void dump() const;
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
59 errs() << "Multiclass:\n";
61 MC->dump();
63 errs() << "Template args:\n";
64 for (Init *TA : TemplateArgs)
65 TA->dump();
67 #endif
69 } // end namespace llvm
71 static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
72 BitsInit *BV = cast<BitsInit>(RV.getValue());
73 for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
74 Init *Bit = BV->getBit(i);
75 bool IsReference = false;
76 if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
77 if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
78 if (R.getValue(VI->getName()))
79 IsReference = true;
81 } else if (isa<VarInit>(Bit)) {
82 IsReference = true;
84 if (!(IsReference || Bit->isConcrete()))
85 return false;
87 return true;
90 static void checkConcrete(Record &R) {
91 for (const RecordVal &RV : R.getValues()) {
92 // HACK: Disable this check for variables declared with 'field'. This is
93 // done merely because existing targets have legitimate cases of
94 // non-concrete variables in helper defs. Ideally, we'd introduce a
95 // 'maybe' or 'optional' modifier instead of this.
96 if (RV.isNonconcreteOK())
97 continue;
99 if (Init *V = RV.getValue()) {
100 bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
101 if (!Ok) {
102 PrintError(R.getLoc(),
103 Twine("Initializer of '") + RV.getNameInitAsString() +
104 "' in '" + R.getNameInitAsString() +
105 "' could not be fully resolved: " +
106 RV.getValue()->getAsString());
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass, Init *Name,
115 StringRef Scoper) {
116 RecordKeeper &RK = CurRec.getRecords();
117 Init *NewName = BinOpInit::getStrConcat(CurRec.getNameInit(),
118 StringInit::get(RK, Scoper));
119 NewName = BinOpInit::getStrConcat(NewName, Name);
120 if (CurMultiClass && Scoper != "::") {
121 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
122 StringInit::get(RK, "::"));
123 NewName = BinOpInit::getStrConcat(Prefix, NewName);
126 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
127 NewName = BinOp->Fold(&CurRec);
128 return NewName;
131 /// Return the qualified version of the implicit 'NAME' template argument.
132 static Init *QualifiedNameOfImplicitName(Record &Rec,
133 MultiClass *MC = nullptr) {
134 return QualifyName(Rec, MC, StringInit::get(Rec.getRecords(), "NAME"),
135 MC ? "::" : ":");
138 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
139 return QualifiedNameOfImplicitName(MC->Rec, MC);
142 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
143 if (!CurRec)
144 CurRec = &CurMultiClass->Rec;
146 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
147 // The value already exists in the class, treat this as a set.
148 if (ERV->setValue(RV.getValue()))
149 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
150 RV.getType()->getAsString() + "' is incompatible with " +
151 "previous definition of type '" +
152 ERV->getType()->getAsString() + "'");
153 } else {
154 CurRec->addValue(RV);
156 return false;
159 /// SetValue -
160 /// Return true on error, false on success.
161 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
162 ArrayRef<unsigned> BitList, Init *V,
163 bool AllowSelfAssignment, bool OverrideDefLoc) {
164 if (!V) return false;
166 if (!CurRec) CurRec = &CurMultiClass->Rec;
168 RecordVal *RV = CurRec->getValue(ValName);
169 if (!RV)
170 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
171 "' unknown!");
173 // Do not allow assignments like 'X = X'. This will just cause infinite loops
174 // in the resolution machinery.
175 if (BitList.empty())
176 if (VarInit *VI = dyn_cast<VarInit>(V))
177 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
178 return Error(Loc, "Recursion / self-assignment forbidden");
180 // If we are assigning to a subset of the bits in the value... then we must be
181 // assigning to a field of BitsRecTy, which must have a BitsInit
182 // initializer.
184 if (!BitList.empty()) {
185 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
186 if (!CurVal)
187 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
188 "' is not a bits type");
190 // Convert the incoming value to a bits type of the appropriate size...
191 Init *BI = V->getCastTo(BitsRecTy::get(Records, BitList.size()));
192 if (!BI)
193 return Error(Loc, "Initializer is not compatible with bit range");
195 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
197 // Loop over bits, assigning values as appropriate.
198 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
199 unsigned Bit = BitList[i];
200 if (NewBits[Bit])
201 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
202 ValName->getAsUnquotedString() + "' more than once");
203 NewBits[Bit] = BI->getBit(i);
206 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
207 if (!NewBits[i])
208 NewBits[i] = CurVal->getBit(i);
210 V = BitsInit::get(Records, NewBits);
213 if (OverrideDefLoc ? RV->setValue(V, Loc) : RV->setValue(V)) {
214 std::string InitType;
215 if (BitsInit *BI = dyn_cast<BitsInit>(V))
216 InitType = (Twine("' of type bit initializer with length ") +
217 Twine(BI->getNumBits())).str();
218 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
219 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
220 return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
221 "' of type '" + RV->getType()->getAsString() +
222 "' is incompatible with value '" +
223 V->getAsString() + InitType + "'");
225 return false;
228 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
229 /// args as SubClass's template arguments.
230 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
231 Record *SC = SubClass.Rec;
232 MapResolver R(CurRec);
234 // Loop over all the subclass record's fields. Add template arguments
235 // to the resolver map. Add regular fields to the new record.
236 for (const RecordVal &Field : SC->getValues()) {
237 if (Field.isTemplateArg()) {
238 R.set(Field.getNameInit(), Field.getValue());
239 } else {
240 if (AddValue(CurRec, SubClass.RefRange.Start, Field))
241 return true;
245 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
246 assert(SubClass.TemplateArgs.size() <= TArgs.size() &&
247 "Too many template arguments allowed");
249 // Loop over the template argument names. If a value was specified,
250 // reset the map value. If not and there was no default, complain.
251 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) {
252 if (I < SubClass.TemplateArgs.size())
253 R.set(TArgs[I], SubClass.TemplateArgs[I]);
254 else if (!R.isComplete(TArgs[I]))
255 return Error(SubClass.RefRange.Start,
256 "Value not specified for template argument '" +
257 TArgs[I]->getAsUnquotedString() + "' (#" + Twine(I) +
258 ") of parent class '" + SC->getNameInitAsString() + "'");
261 // Copy the subclass record's assertions to the new record.
262 CurRec->appendAssertions(SC);
264 Init *Name;
265 if (CurRec->isClass())
266 Name = VarInit::get(QualifiedNameOfImplicitName(*CurRec),
267 StringRecTy::get(Records));
268 else
269 Name = CurRec->getNameInit();
270 R.set(QualifiedNameOfImplicitName(*SC), Name);
272 CurRec->resolveReferences(R);
274 // Since everything went well, we can now set the "superclass" list for the
275 // current record.
276 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
277 for (const auto &SCPair : SCs) {
278 if (CurRec->isSubClassOf(SCPair.first))
279 return Error(SubClass.RefRange.Start,
280 "Already subclass of '" + SCPair.first->getName() + "'!\n");
281 CurRec->addSuperClass(SCPair.first, SCPair.second);
284 if (CurRec->isSubClassOf(SC))
285 return Error(SubClass.RefRange.Start,
286 "Already subclass of '" + SC->getName() + "'!\n");
287 CurRec->addSuperClass(SC, SubClass.RefRange);
288 return false;
291 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
292 if (Entry.Rec)
293 return AddSubClass(Entry.Rec.get(), SubClass);
295 if (Entry.Assertion)
296 return false;
298 for (auto &E : Entry.Loop->Entries) {
299 if (AddSubClass(E, SubClass))
300 return true;
303 return false;
306 /// AddSubMultiClass - Add SubMultiClass as a subclass to
307 /// CurMC, resolving its template args as SubMultiClass's
308 /// template arguments.
309 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
310 SubMultiClassReference &SubMultiClass) {
311 MultiClass *SMC = SubMultiClass.MC;
313 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
314 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
315 return Error(SubMultiClass.RefRange.Start,
316 "More template args specified than expected");
318 // Prepare the mapping of template argument name to value, filling in default
319 // values if necessary.
320 SubstStack TemplateArgs;
321 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
322 if (i < SubMultiClass.TemplateArgs.size()) {
323 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
324 } else {
325 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
326 if (!Default->isComplete()) {
327 return Error(SubMultiClass.RefRange.Start,
328 "value not specified for template argument #" + Twine(i) +
329 " (" + SMCTArgs[i]->getAsUnquotedString() +
330 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
331 "'");
333 TemplateArgs.emplace_back(SMCTArgs[i], Default);
337 TemplateArgs.emplace_back(QualifiedNameOfImplicitName(SMC),
338 VarInit::get(QualifiedNameOfImplicitName(CurMC),
339 StringRecTy::get(Records)));
341 // Add all of the defs in the subclass into the current multiclass.
342 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
345 /// Add a record, foreach loop, or assertion to the current context.
346 bool TGParser::addEntry(RecordsEntry E) {
347 assert((!!E.Rec + !!E.Loop + !!E.Assertion) == 1 &&
348 "RecordsEntry has invalid number of items");
350 // If we are parsing a loop, add it to the loop's entries.
351 if (!Loops.empty()) {
352 Loops.back()->Entries.push_back(std::move(E));
353 return false;
356 // If it is a loop, then resolve and perform the loop.
357 if (E.Loop) {
358 SubstStack Stack;
359 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
360 CurMultiClass ? &CurMultiClass->Entries : nullptr);
363 // If we are parsing a multiclass, add it to the multiclass's entries.
364 if (CurMultiClass) {
365 CurMultiClass->Entries.push_back(std::move(E));
366 return false;
369 // If it is an assertion, then it's a top-level one, so check it.
370 if (E.Assertion) {
371 CheckAssert(E.Assertion->Loc, E.Assertion->Condition, E.Assertion->Message);
372 return false;
375 // It must be a record, so finish it off.
376 return addDefOne(std::move(E.Rec));
379 /// Resolve the entries in \p Loop, going over inner loops recursively
380 /// and making the given subsitutions of (name, value) pairs.
382 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
383 /// are added to the global record keeper.
384 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
385 bool Final, std::vector<RecordsEntry> *Dest,
386 SMLoc *Loc) {
388 MapResolver R;
389 for (const auto &S : Substs)
390 R.set(S.first, S.second);
391 Init *List = Loop.ListValue->resolveReferences(R);
393 // For if-then-else blocks, we lower to a foreach loop whose list is a
394 // ternary selection between lists of different length. Since we don't
395 // have a means to track variable length record lists, we *must* resolve
396 // the condition here. We want to defer final resolution of the arms
397 // until the resulting records are finalized.
398 // e.g. !if(!exists<SchedWrite>("__does_not_exist__"), [1], [])
399 if (auto *TI = dyn_cast<TernOpInit>(List);
400 TI && TI->getOpcode() == TernOpInit::IF && Final) {
401 Init *OldLHS = TI->getLHS();
402 R.setFinal(true);
403 Init *LHS = OldLHS->resolveReferences(R);
404 if (LHS == OldLHS) {
405 PrintError(Loop.Loc,
406 Twine("unable to resolve if condition '") +
407 LHS->getAsString() + "' at end of containing scope");
408 return true;
410 Init *MHS = TI->getMHS();
411 Init *RHS = TI->getRHS();
412 List = TernOpInit::get(TernOpInit::IF, LHS, MHS, RHS, TI->getType())
413 ->Fold(nullptr);
416 auto LI = dyn_cast<ListInit>(List);
417 if (!LI) {
418 if (!Final) {
419 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
420 List));
421 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
422 Loc);
425 PrintError(Loop.Loc, Twine("attempting to loop over '") +
426 List->getAsString() + "', expected a list");
427 return true;
430 bool Error = false;
431 for (auto *Elt : *LI) {
432 if (Loop.IterVar)
433 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
434 Error = resolve(Loop.Entries, Substs, Final, Dest);
435 if (Loop.IterVar)
436 Substs.pop_back();
437 if (Error)
438 break;
440 return Error;
443 /// Resolve the entries in \p Source, going over loops recursively and
444 /// making the given substitutions of (name, value) pairs.
446 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
447 /// are added to the global record keeper.
448 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
449 SubstStack &Substs, bool Final,
450 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
451 bool Error = false;
452 for (auto &E : Source) {
453 if (E.Loop) {
454 Error = resolve(*E.Loop, Substs, Final, Dest);
456 } else if (E.Assertion) {
457 MapResolver R;
458 for (const auto &S : Substs)
459 R.set(S.first, S.second);
460 Init *Condition = E.Assertion->Condition->resolveReferences(R);
461 Init *Message = E.Assertion->Message->resolveReferences(R);
463 if (Dest)
464 Dest->push_back(std::make_unique<Record::AssertionInfo>(
465 E.Assertion->Loc, Condition, Message));
466 else
467 CheckAssert(E.Assertion->Loc, Condition, Message);
469 } else {
470 auto Rec = std::make_unique<Record>(*E.Rec);
471 if (Loc)
472 Rec->appendLoc(*Loc);
474 MapResolver R(Rec.get());
475 for (const auto &S : Substs)
476 R.set(S.first, S.second);
477 Rec->resolveReferences(R);
479 if (Dest)
480 Dest->push_back(std::move(Rec));
481 else
482 Error = addDefOne(std::move(Rec));
484 if (Error)
485 break;
487 return Error;
490 /// Resolve the record fully and add it to the record keeper.
491 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
492 Init *NewName = nullptr;
493 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
494 if (!Rec->isAnonymous()) {
495 PrintError(Rec->getLoc(),
496 "def already exists: " + Rec->getNameInitAsString());
497 PrintNote(Prev->getLoc(), "location of previous definition");
498 return true;
500 NewName = Records.getNewAnonymousName();
503 Rec->resolveReferences(NewName);
504 checkConcrete(*Rec);
506 if (!isa<StringInit>(Rec->getNameInit())) {
507 PrintError(Rec->getLoc(), Twine("record name '") +
508 Rec->getNameInit()->getAsString() +
509 "' could not be fully resolved");
510 return true;
513 // Check the assertions.
514 Rec->checkRecordAssertions();
516 // If ObjectBody has template arguments, it's an error.
517 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
519 for (DefsetRecord *Defset : Defsets) {
520 DefInit *I = Rec->getDefInit();
521 if (!I->getType()->typeIsA(Defset->EltTy)) {
522 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
523 I->getType()->getAsString() +
524 "' to defset");
525 PrintNote(Defset->Loc, "location of defset declaration");
526 return true;
528 Defset->Elements.push_back(I);
531 Records.addDef(std::move(Rec));
532 return false;
535 //===----------------------------------------------------------------------===//
536 // Parser Code
537 //===----------------------------------------------------------------------===//
539 /// isObjectStart - Return true if this is a valid first token for a statement.
540 static bool isObjectStart(tgtok::TokKind K) {
541 return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
542 K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
543 K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
544 K == tgtok::MultiClass;
547 bool TGParser::consume(tgtok::TokKind K) {
548 if (Lex.getCode() == K) {
549 Lex.Lex();
550 return true;
552 return false;
555 /// ParseObjectName - If a valid object name is specified, return it. If no
556 /// name is specified, return the unset initializer. Return nullptr on parse
557 /// error.
558 /// ObjectName ::= Value [ '#' Value ]*
559 /// ObjectName ::= /*empty*/
561 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
562 switch (Lex.getCode()) {
563 case tgtok::colon:
564 case tgtok::semi:
565 case tgtok::l_brace:
566 // These are all of the tokens that can begin an object body.
567 // Some of these can also begin values but we disallow those cases
568 // because they are unlikely to be useful.
569 return UnsetInit::get(Records);
570 default:
571 break;
574 Record *CurRec = nullptr;
575 if (CurMultiClass)
576 CurRec = &CurMultiClass->Rec;
578 Init *Name = ParseValue(CurRec, StringRecTy::get(Records), ParseNameMode);
579 if (!Name)
580 return nullptr;
582 if (CurMultiClass) {
583 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
584 HasReferenceResolver R(NameStr);
585 Name->resolveReferences(R);
586 if (!R.found())
587 Name = BinOpInit::getStrConcat(
588 VarInit::get(NameStr, StringRecTy::get(Records)), Name);
591 return Name;
594 /// ParseClassID - Parse and resolve a reference to a class name. This returns
595 /// null on error.
597 /// ClassID ::= ID
599 Record *TGParser::ParseClassID() {
600 if (Lex.getCode() != tgtok::Id) {
601 TokError("expected name for ClassID");
602 return nullptr;
605 Record *Result = Records.getClass(Lex.getCurStrVal());
606 if (!Result) {
607 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
608 if (MultiClasses[Lex.getCurStrVal()].get())
609 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
610 Lex.getCurStrVal() + "'");
611 else
612 TokError(Msg);
613 } else if (TrackReferenceLocs) {
614 Result->appendReferenceLoc(Lex.getLocRange());
617 Lex.Lex();
618 return Result;
621 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
622 /// This returns null on error.
624 /// MultiClassID ::= ID
626 MultiClass *TGParser::ParseMultiClassID() {
627 if (Lex.getCode() != tgtok::Id) {
628 TokError("expected name for MultiClassID");
629 return nullptr;
632 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
633 if (!Result)
634 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
636 Lex.Lex();
637 return Result;
640 /// ParseSubClassReference - Parse a reference to a subclass or a
641 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
643 /// SubClassRef ::= ClassID
644 /// SubClassRef ::= ClassID '<' ValueList '>'
646 SubClassReference TGParser::
647 ParseSubClassReference(Record *CurRec, bool isDefm) {
648 SubClassReference Result;
649 Result.RefRange.Start = Lex.getLoc();
651 if (isDefm) {
652 if (MultiClass *MC = ParseMultiClassID())
653 Result.Rec = &MC->Rec;
654 } else {
655 Result.Rec = ParseClassID();
657 if (!Result.Rec) return Result;
659 // If there is no template arg list, we're done.
660 if (!consume(tgtok::less)) {
661 Result.RefRange.End = Lex.getLoc();
662 return Result;
665 if (ParseTemplateArgValueList(Result.TemplateArgs, CurRec, Result.Rec)) {
666 Result.Rec = nullptr; // Error parsing value list.
667 return Result;
670 if (CheckTemplateArgValues(Result.TemplateArgs, Result.RefRange.Start,
671 Result.Rec)) {
672 Result.Rec = nullptr; // Error checking value list.
673 return Result;
676 Result.RefRange.End = Lex.getLoc();
677 return Result;
680 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
681 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
682 /// Record* on error.
684 /// SubMultiClassRef ::= MultiClassID
685 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
687 SubMultiClassReference TGParser::
688 ParseSubMultiClassReference(MultiClass *CurMC) {
689 SubMultiClassReference Result;
690 Result.RefRange.Start = Lex.getLoc();
692 Result.MC = ParseMultiClassID();
693 if (!Result.MC) return Result;
695 // If there is no template arg list, we're done.
696 if (!consume(tgtok::less)) {
697 Result.RefRange.End = Lex.getLoc();
698 return Result;
701 if (ParseTemplateArgValueList(Result.TemplateArgs, &CurMC->Rec,
702 &Result.MC->Rec)) {
703 Result.MC = nullptr; // Error parsing value list.
704 return Result;
707 Result.RefRange.End = Lex.getLoc();
709 return Result;
712 /// ParseSliceElement - Parse subscript or range
714 /// SliceElement ::= Value<list<int>>
715 /// SliceElement ::= Value<int>
716 /// SliceElement ::= Value<int> '...' Value<int>
717 /// SliceElement ::= Value<int> '-' Value<int> (deprecated)
718 /// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
720 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
722 TypedInit *TGParser::ParseSliceElement(Record *CurRec) {
723 auto LHSLoc = Lex.getLoc();
724 auto *CurVal = ParseValue(CurRec);
725 if (!CurVal)
726 return nullptr;
727 auto *LHS = cast<TypedInit>(CurVal);
729 TypedInit *RHS = nullptr;
730 switch (Lex.getCode()) {
731 case tgtok::dotdotdot:
732 case tgtok::minus: { // Deprecated
733 Lex.Lex(); // eat
734 auto RHSLoc = Lex.getLoc();
735 CurVal = ParseValue(CurRec);
736 if (!CurVal)
737 return nullptr;
738 RHS = cast<TypedInit>(CurVal);
739 if (!isa<IntRecTy>(RHS->getType())) {
740 Error(RHSLoc,
741 "expected int...int, got " + Twine(RHS->getType()->getAsString()));
742 return nullptr;
744 break;
746 case tgtok::IntVal: { // Deprecated "-num"
747 auto i = -Lex.getCurIntVal();
748 if (i < 0) {
749 TokError("invalid range, cannot be negative");
750 return nullptr;
752 RHS = IntInit::get(Records, i);
753 Lex.Lex(); // eat IntVal
754 break;
756 default: // Single value (IntRecTy or ListRecTy)
757 return LHS;
760 assert(RHS);
761 assert(isa<IntRecTy>(RHS->getType()));
763 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
764 if (!isa<IntRecTy>(LHS->getType())) {
765 Error(LHSLoc,
766 "expected int...int, got " + Twine(LHS->getType()->getAsString()));
767 return nullptr;
770 return cast<TypedInit>(BinOpInit::get(BinOpInit::RANGEC, LHS, RHS,
771 IntRecTy::get(Records)->getListTy())
772 ->Fold(CurRec));
775 /// ParseSliceElements - Parse subscripts in square brackets.
777 /// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
779 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
781 /// Returns ListRecTy by defaut.
782 /// Returns IntRecTy if;
783 /// - Single=true
784 /// - SliceElements is Value<int> w/o trailing comma
786 TypedInit *TGParser::ParseSliceElements(Record *CurRec, bool Single) {
787 TypedInit *CurVal;
788 SmallVector<Init *, 2> Elems; // int
789 SmallVector<TypedInit *, 2> Slices; // list<int>
791 auto FlushElems = [&] {
792 if (!Elems.empty()) {
793 Slices.push_back(ListInit::get(Elems, IntRecTy::get(Records)));
794 Elems.clear();
798 do {
799 auto LHSLoc = Lex.getLoc();
800 CurVal = ParseSliceElement(CurRec);
801 if (!CurVal)
802 return nullptr;
803 auto *CurValTy = CurVal->getType();
805 if (auto *ListValTy = dyn_cast<ListRecTy>(CurValTy)) {
806 if (!isa<IntRecTy>(ListValTy->getElementType())) {
807 Error(LHSLoc,
808 "expected list<int>, got " + Twine(ListValTy->getAsString()));
809 return nullptr;
812 FlushElems();
813 Slices.push_back(CurVal);
814 Single = false;
815 CurVal = nullptr;
816 } else if (!isa<IntRecTy>(CurValTy)) {
817 Error(LHSLoc,
818 "unhandled type " + Twine(CurValTy->getAsString()) + " in range");
819 return nullptr;
822 if (Lex.getCode() != tgtok::comma)
823 break;
825 Lex.Lex(); // eat comma
827 // `[i,]` is not LISTELEM but LISTSLICE
828 Single = false;
829 if (CurVal)
830 Elems.push_back(CurVal);
831 CurVal = nullptr;
832 } while (Lex.getCode() != tgtok::r_square);
834 if (CurVal) {
835 // LISTELEM
836 if (Single)
837 return CurVal;
839 Elems.push_back(CurVal);
842 FlushElems();
844 // Concatenate lists in Slices
845 TypedInit *Result = nullptr;
846 for (auto *Slice : Slices) {
847 Result = (Result ? cast<TypedInit>(BinOpInit::getListConcat(Result, Slice))
848 : Slice);
851 return Result;
854 /// ParseRangePiece - Parse a bit/value range.
855 /// RangePiece ::= INTVAL
856 /// RangePiece ::= INTVAL '...' INTVAL
857 /// RangePiece ::= INTVAL '-' INTVAL
858 /// RangePiece ::= INTVAL INTVAL
859 // The last two forms are deprecated.
860 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
861 TypedInit *FirstItem) {
862 Init *CurVal = FirstItem;
863 if (!CurVal)
864 CurVal = ParseValue(nullptr);
866 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
867 if (!II)
868 return TokError("expected integer or bitrange");
870 int64_t Start = II->getValue();
871 int64_t End;
873 if (Start < 0)
874 return TokError("invalid range, cannot be negative");
876 switch (Lex.getCode()) {
877 default:
878 Ranges.push_back(Start);
879 return false;
881 case tgtok::dotdotdot:
882 case tgtok::minus: {
883 Lex.Lex(); // eat
885 Init *I_End = ParseValue(nullptr);
886 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
887 if (!II_End) {
888 TokError("expected integer value as end of range");
889 return true;
892 End = II_End->getValue();
893 break;
895 case tgtok::IntVal: {
896 End = -Lex.getCurIntVal();
897 Lex.Lex();
898 break;
901 if (End < 0)
902 return TokError("invalid range, cannot be negative");
904 // Add to the range.
905 if (Start < End)
906 for (; Start <= End; ++Start)
907 Ranges.push_back(Start);
908 else
909 for (; Start >= End; --Start)
910 Ranges.push_back(Start);
911 return false;
914 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
916 /// RangeList ::= RangePiece (',' RangePiece)*
918 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
919 // Parse the first piece.
920 if (ParseRangePiece(Result)) {
921 Result.clear();
922 return;
924 while (consume(tgtok::comma))
925 // Parse the next range piece.
926 if (ParseRangePiece(Result)) {
927 Result.clear();
928 return;
932 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
933 /// OptionalRangeList ::= '<' RangeList '>'
934 /// OptionalRangeList ::= /*empty*/
935 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
936 SMLoc StartLoc = Lex.getLoc();
937 if (!consume(tgtok::less))
938 return false;
940 // Parse the range list.
941 ParseRangeList(Ranges);
942 if (Ranges.empty()) return true;
944 if (!consume(tgtok::greater)) {
945 TokError("expected '>' at end of range list");
946 return Error(StartLoc, "to match this '<'");
948 return false;
951 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
952 /// OptionalBitList ::= '{' RangeList '}'
953 /// OptionalBitList ::= /*empty*/
954 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
955 SMLoc StartLoc = Lex.getLoc();
956 if (!consume(tgtok::l_brace))
957 return false;
959 // Parse the range list.
960 ParseRangeList(Ranges);
961 if (Ranges.empty()) return true;
963 if (!consume(tgtok::r_brace)) {
964 TokError("expected '}' at end of bit list");
965 return Error(StartLoc, "to match this '{'");
967 return false;
970 /// ParseType - Parse and return a tblgen type. This returns null on error.
972 /// Type ::= STRING // string type
973 /// Type ::= CODE // code type
974 /// Type ::= BIT // bit type
975 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
976 /// Type ::= INT // int type
977 /// Type ::= LIST '<' Type '>' // list<x> type
978 /// Type ::= DAG // dag type
979 /// Type ::= ClassID // Record Type
981 RecTy *TGParser::ParseType() {
982 switch (Lex.getCode()) {
983 default: TokError("Unknown token when expecting a type"); return nullptr;
984 case tgtok::String:
985 case tgtok::Code:
986 Lex.Lex();
987 return StringRecTy::get(Records);
988 case tgtok::Bit:
989 Lex.Lex();
990 return BitRecTy::get(Records);
991 case tgtok::Int:
992 Lex.Lex();
993 return IntRecTy::get(Records);
994 case tgtok::Dag:
995 Lex.Lex();
996 return DagRecTy::get(Records);
997 case tgtok::Id:
998 if (Record *R = ParseClassID())
999 return RecordRecTy::get(R);
1000 TokError("unknown class name");
1001 return nullptr;
1002 case tgtok::Bits: {
1003 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1004 TokError("expected '<' after bits type");
1005 return nullptr;
1007 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
1008 TokError("expected integer in bits<n> type");
1009 return nullptr;
1011 uint64_t Val = Lex.getCurIntVal();
1012 if (Lex.Lex() != tgtok::greater) { // Eat count.
1013 TokError("expected '>' at end of bits<n> type");
1014 return nullptr;
1016 Lex.Lex(); // Eat '>'
1017 return BitsRecTy::get(Records, Val);
1019 case tgtok::List: {
1020 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1021 TokError("expected '<' after list type");
1022 return nullptr;
1024 Lex.Lex(); // Eat '<'
1025 RecTy *SubType = ParseType();
1026 if (!SubType) return nullptr;
1028 if (!consume(tgtok::greater)) {
1029 TokError("expected '>' at end of list<ty> type");
1030 return nullptr;
1032 return ListRecTy::get(SubType);
1037 /// ParseIDValue
1038 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMRange NameLoc,
1039 IDParseMode Mode) {
1040 if (CurRec) {
1041 if (RecordVal *RV = CurRec->getValue(Name)) {
1042 if (TrackReferenceLocs)
1043 RV->addReferenceLoc(NameLoc);
1044 return VarInit::get(Name, RV->getType());
1048 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
1049 Init *TemplateArgName;
1050 if (CurMultiClass) {
1051 TemplateArgName =
1052 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
1053 } else
1054 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
1056 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
1057 if (TemplateRec->isTemplateArg(TemplateArgName)) {
1058 RecordVal *RV = TemplateRec->getValue(TemplateArgName);
1059 assert(RV && "Template arg doesn't exist??");
1060 RV->setUsed(true);
1061 if (TrackReferenceLocs)
1062 RV->addReferenceLoc(NameLoc);
1063 return VarInit::get(TemplateArgName, RV->getType());
1064 } else if (Name->getValue() == "NAME") {
1065 return VarInit::get(TemplateArgName, StringRecTy::get(Records));
1069 if (CurLocalScope)
1070 if (Init *I = CurLocalScope->getVar(Name->getValue()))
1071 return I;
1073 // If this is in a foreach loop, make sure it's not a loop iterator
1074 for (const auto &L : Loops) {
1075 if (L->IterVar) {
1076 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
1077 if (IterVar && IterVar->getNameInit() == Name)
1078 return IterVar;
1082 if (Mode == ParseNameMode)
1083 return Name;
1085 if (Init *I = Records.getGlobal(Name->getValue())) {
1086 // Add a reference to the global if it's a record.
1087 if (TrackReferenceLocs) {
1088 if (auto *Def = dyn_cast<DefInit>(I))
1089 Def->getDef()->appendReferenceLoc(NameLoc);
1091 return I;
1094 // Allow self-references of concrete defs, but delay the lookup so that we
1095 // get the correct type.
1096 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
1097 CurRec->getNameInit() == Name)
1098 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
1100 Error(NameLoc.Start, "Variable not defined: '" + Name->getValue() + "'");
1101 return nullptr;
1104 /// ParseOperation - Parse an operator. This returns null on error.
1106 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1108 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
1109 switch (Lex.getCode()) {
1110 default:
1111 TokError("unknown bang operator");
1112 return nullptr;
1113 case tgtok::XNOT:
1114 case tgtok::XToLower:
1115 case tgtok::XToUpper:
1116 case tgtok::XLOG2:
1117 case tgtok::XHead:
1118 case tgtok::XTail:
1119 case tgtok::XSize:
1120 case tgtok::XEmpty:
1121 case tgtok::XCast:
1122 case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
1123 UnOpInit::UnaryOp Code;
1124 RecTy *Type = nullptr;
1126 switch (Lex.getCode()) {
1127 default: llvm_unreachable("Unhandled code!");
1128 case tgtok::XCast:
1129 Lex.Lex(); // eat the operation
1130 Code = UnOpInit::CAST;
1132 Type = ParseOperatorType();
1134 if (!Type) {
1135 TokError("did not get type for unary operator");
1136 return nullptr;
1139 break;
1140 case tgtok::XToLower:
1141 Lex.Lex(); // eat the operation
1142 Code = UnOpInit::TOLOWER;
1143 Type = StringRecTy::get(Records);
1144 break;
1145 case tgtok::XToUpper:
1146 Lex.Lex(); // eat the operation
1147 Code = UnOpInit::TOUPPER;
1148 Type = StringRecTy::get(Records);
1149 break;
1150 case tgtok::XNOT:
1151 Lex.Lex(); // eat the operation
1152 Code = UnOpInit::NOT;
1153 Type = IntRecTy::get(Records);
1154 break;
1155 case tgtok::XLOG2:
1156 Lex.Lex(); // eat the operation
1157 Code = UnOpInit::LOG2;
1158 Type = IntRecTy::get(Records);
1159 break;
1160 case tgtok::XHead:
1161 Lex.Lex(); // eat the operation
1162 Code = UnOpInit::HEAD;
1163 break;
1164 case tgtok::XTail:
1165 Lex.Lex(); // eat the operation
1166 Code = UnOpInit::TAIL;
1167 break;
1168 case tgtok::XSize:
1169 Lex.Lex();
1170 Code = UnOpInit::SIZE;
1171 Type = IntRecTy::get(Records);
1172 break;
1173 case tgtok::XEmpty:
1174 Lex.Lex(); // eat the operation
1175 Code = UnOpInit::EMPTY;
1176 Type = IntRecTy::get(Records);
1177 break;
1178 case tgtok::XGetDagOp:
1179 Lex.Lex(); // eat the operation
1180 if (Lex.getCode() == tgtok::less) {
1181 // Parse an optional type suffix, so that you can say
1182 // !getdagop<BaseClass>(someDag) as a shorthand for
1183 // !cast<BaseClass>(!getdagop(someDag)).
1184 Type = ParseOperatorType();
1186 if (!Type) {
1187 TokError("did not get type for unary operator");
1188 return nullptr;
1191 if (!isa<RecordRecTy>(Type)) {
1192 TokError("type for !getdagop must be a record type");
1193 // but keep parsing, to consume the operand
1195 } else {
1196 Type = RecordRecTy::get(Records, {});
1198 Code = UnOpInit::GETDAGOP;
1199 break;
1201 if (!consume(tgtok::l_paren)) {
1202 TokError("expected '(' after unary operator");
1203 return nullptr;
1206 Init *LHS = ParseValue(CurRec);
1207 if (!LHS) return nullptr;
1209 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
1210 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1211 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1212 DagInit *LHSd = dyn_cast<DagInit>(LHS);
1213 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1214 if (!LHSl && !LHSs && !LHSd && !LHSt) {
1215 TokError("expected string, list, or dag type argument in unary operator");
1216 return nullptr;
1218 if (LHSt) {
1219 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1220 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1221 DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1222 if (!LType && !SType && !DType) {
1223 TokError("expected string, list, or dag type argument in unary operator");
1224 return nullptr;
1229 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1230 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1231 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1232 if (!LHSl && !LHSt) {
1233 TokError("expected list type argument in unary operator");
1234 return nullptr;
1236 if (LHSt) {
1237 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1238 if (!LType) {
1239 TokError("expected list type argument in unary operator");
1240 return nullptr;
1244 if (LHSl && LHSl->empty()) {
1245 TokError("empty list argument in unary operator");
1246 return nullptr;
1248 if (LHSl) {
1249 Init *Item = LHSl->getElement(0);
1250 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1251 if (!Itemt) {
1252 TokError("untyped list element in unary operator");
1253 return nullptr;
1255 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1256 : ListRecTy::get(Itemt->getType());
1257 } else {
1258 assert(LHSt && "expected list type argument in unary operator");
1259 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1260 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1264 if (!consume(tgtok::r_paren)) {
1265 TokError("expected ')' in unary operator");
1266 return nullptr;
1268 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1271 case tgtok::XIsA: {
1272 // Value ::= !isa '<' Type '>' '(' Value ')'
1273 Lex.Lex(); // eat the operation
1275 RecTy *Type = ParseOperatorType();
1276 if (!Type)
1277 return nullptr;
1279 if (!consume(tgtok::l_paren)) {
1280 TokError("expected '(' after type of !isa");
1281 return nullptr;
1284 Init *LHS = ParseValue(CurRec);
1285 if (!LHS)
1286 return nullptr;
1288 if (!consume(tgtok::r_paren)) {
1289 TokError("expected ')' in !isa");
1290 return nullptr;
1293 return (IsAOpInit::get(Type, LHS))->Fold();
1296 case tgtok::XExists: {
1297 // Value ::= !exists '<' Type '>' '(' Value ')'
1298 Lex.Lex(); // eat the operation
1300 RecTy *Type = ParseOperatorType();
1301 if (!Type)
1302 return nullptr;
1304 if (!consume(tgtok::l_paren)) {
1305 TokError("expected '(' after type of !exists");
1306 return nullptr;
1309 SMLoc ExprLoc = Lex.getLoc();
1310 Init *Expr = ParseValue(CurRec);
1311 if (!Expr)
1312 return nullptr;
1314 TypedInit *ExprType = dyn_cast<TypedInit>(Expr);
1315 if (!ExprType) {
1316 Error(ExprLoc, "expected string type argument in !exists operator");
1317 return nullptr;
1320 RecordRecTy *RecType = dyn_cast<RecordRecTy>(ExprType->getType());
1321 if (RecType) {
1322 Error(ExprLoc,
1323 "expected string type argument in !exists operator, please "
1324 "use !isa instead");
1325 return nullptr;
1328 StringRecTy *SType = dyn_cast<StringRecTy>(ExprType->getType());
1329 if (!SType) {
1330 Error(ExprLoc, "expected string type argument in !exists operator");
1331 return nullptr;
1334 if (!consume(tgtok::r_paren)) {
1335 TokError("expected ')' in !exists");
1336 return nullptr;
1339 return (ExistsOpInit::get(Type, Expr))->Fold(CurRec);
1342 case tgtok::XConcat:
1343 case tgtok::XADD:
1344 case tgtok::XSUB:
1345 case tgtok::XMUL:
1346 case tgtok::XDIV:
1347 case tgtok::XAND:
1348 case tgtok::XOR:
1349 case tgtok::XXOR:
1350 case tgtok::XSRA:
1351 case tgtok::XSRL:
1352 case tgtok::XSHL:
1353 case tgtok::XEq:
1354 case tgtok::XNe:
1355 case tgtok::XLe:
1356 case tgtok::XLt:
1357 case tgtok::XGe:
1358 case tgtok::XGt:
1359 case tgtok::XListConcat:
1360 case tgtok::XListSplat:
1361 case tgtok::XListRemove:
1362 case tgtok::XRange:
1363 case tgtok::XStrConcat:
1364 case tgtok::XInterleave:
1365 case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1366 tgtok::TokKind OpTok = Lex.getCode();
1367 SMLoc OpLoc = Lex.getLoc();
1368 Lex.Lex(); // eat the operation
1370 BinOpInit::BinaryOp Code;
1371 switch (OpTok) {
1372 default: llvm_unreachable("Unhandled code!");
1373 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1374 case tgtok::XADD: Code = BinOpInit::ADD; break;
1375 case tgtok::XSUB: Code = BinOpInit::SUB; break;
1376 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1377 case tgtok::XDIV: Code = BinOpInit::DIV; break;
1378 case tgtok::XAND: Code = BinOpInit::AND; break;
1379 case tgtok::XOR: Code = BinOpInit::OR; break;
1380 case tgtok::XXOR: Code = BinOpInit::XOR; break;
1381 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1382 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1383 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1384 case tgtok::XEq: Code = BinOpInit::EQ; break;
1385 case tgtok::XNe: Code = BinOpInit::NE; break;
1386 case tgtok::XLe: Code = BinOpInit::LE; break;
1387 case tgtok::XLt: Code = BinOpInit::LT; break;
1388 case tgtok::XGe: Code = BinOpInit::GE; break;
1389 case tgtok::XGt: Code = BinOpInit::GT; break;
1390 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1391 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1392 case tgtok::XListRemove: Code = BinOpInit::LISTREMOVE; break;
1393 case tgtok::XRange: Code = BinOpInit::RANGE; break;
1394 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1395 case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1396 case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
1399 RecTy *Type = nullptr;
1400 RecTy *ArgType = nullptr;
1401 switch (OpTok) {
1402 default:
1403 llvm_unreachable("Unhandled code!");
1404 case tgtok::XConcat:
1405 case tgtok::XSetDagOp:
1406 Type = DagRecTy::get(Records);
1407 ArgType = DagRecTy::get(Records);
1408 break;
1409 case tgtok::XAND:
1410 case tgtok::XOR:
1411 case tgtok::XXOR:
1412 case tgtok::XSRA:
1413 case tgtok::XSRL:
1414 case tgtok::XSHL:
1415 case tgtok::XADD:
1416 case tgtok::XSUB:
1417 case tgtok::XMUL:
1418 case tgtok::XDIV:
1419 Type = IntRecTy::get(Records);
1420 ArgType = IntRecTy::get(Records);
1421 break;
1422 case tgtok::XEq:
1423 case tgtok::XNe:
1424 case tgtok::XLe:
1425 case tgtok::XLt:
1426 case tgtok::XGe:
1427 case tgtok::XGt:
1428 Type = BitRecTy::get(Records);
1429 // ArgType for the comparison operators is not yet known.
1430 break;
1431 case tgtok::XListConcat:
1432 // We don't know the list type until we parse the first argument.
1433 ArgType = ItemType;
1434 break;
1435 case tgtok::XListSplat:
1436 // Can't do any typechecking until we parse the first argument.
1437 break;
1438 case tgtok::XListRemove:
1439 // We don't know the list type until we parse the first argument.
1440 ArgType = ItemType;
1441 break;
1442 case tgtok::XRange:
1443 Type = IntRecTy::get(Records)->getListTy();
1444 // ArgType may be either Int or List.
1445 break;
1446 case tgtok::XStrConcat:
1447 Type = StringRecTy::get(Records);
1448 ArgType = StringRecTy::get(Records);
1449 break;
1450 case tgtok::XInterleave:
1451 Type = StringRecTy::get(Records);
1452 // The first argument type is not yet known.
1455 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1456 Error(OpLoc, Twine("expected value of type '") +
1457 ItemType->getAsString() + "', got '" +
1458 Type->getAsString() + "'");
1459 return nullptr;
1462 if (!consume(tgtok::l_paren)) {
1463 TokError("expected '(' after binary operator");
1464 return nullptr;
1467 SmallVector<Init*, 2> InitList;
1469 // Note that this loop consumes an arbitrary number of arguments.
1470 // The actual count is checked later.
1471 for (;;) {
1472 SMLoc InitLoc = Lex.getLoc();
1473 InitList.push_back(ParseValue(CurRec, ArgType));
1474 if (!InitList.back()) return nullptr;
1476 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1477 if (!InitListBack) {
1478 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1479 InitList.back()->getAsString() + "'"));
1480 return nullptr;
1482 RecTy *ListType = InitListBack->getType();
1484 if (!ArgType) {
1485 // Argument type must be determined from the argument itself.
1486 ArgType = ListType;
1488 switch (Code) {
1489 case BinOpInit::LISTCONCAT:
1490 if (!isa<ListRecTy>(ArgType)) {
1491 Error(InitLoc, Twine("expected a list, got value of type '") +
1492 ArgType->getAsString() + "'");
1493 return nullptr;
1495 break;
1496 case BinOpInit::LISTSPLAT:
1497 if (ItemType && InitList.size() == 1) {
1498 if (!isa<ListRecTy>(ItemType)) {
1499 Error(OpLoc,
1500 Twine("expected output type to be a list, got type '") +
1501 ItemType->getAsString() + "'");
1502 return nullptr;
1504 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1505 Error(OpLoc, Twine("expected first arg type to be '") +
1506 ArgType->getAsString() +
1507 "', got value of type '" +
1508 cast<ListRecTy>(ItemType)
1509 ->getElementType()
1510 ->getAsString() +
1511 "'");
1512 return nullptr;
1515 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1516 Error(InitLoc, Twine("expected second parameter to be an int, got "
1517 "value of type '") +
1518 ArgType->getAsString() + "'");
1519 return nullptr;
1521 ArgType = nullptr; // Broken invariant: types not identical.
1522 break;
1523 case BinOpInit::LISTREMOVE:
1524 if (!isa<ListRecTy>(ArgType)) {
1525 Error(InitLoc, Twine("expected a list, got value of type '") +
1526 ArgType->getAsString() + "'");
1527 return nullptr;
1529 break;
1530 case BinOpInit::RANGE:
1531 if (InitList.size() == 1) {
1532 if (isa<ListRecTy>(ArgType)) {
1533 ArgType = nullptr; // Detect error if 2nd arg were present.
1534 } else if (isa<IntRecTy>(ArgType)) {
1535 // Assume 2nd arg should be IntRecTy
1536 } else {
1537 Error(InitLoc,
1538 Twine("expected list or int, got value of type '") +
1539 ArgType->getAsString() + "'");
1540 return nullptr;
1542 } else {
1543 // Don't come here unless 1st arg is ListRecTy.
1544 assert(isa<ListRecTy>(cast<TypedInit>(InitList[0])->getType()));
1545 Error(InitLoc,
1546 Twine("expected one list, got extra value of type '") +
1547 ArgType->getAsString() + "'");
1548 return nullptr;
1550 break;
1551 case BinOpInit::EQ:
1552 case BinOpInit::NE:
1553 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1554 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records)) &&
1555 !ArgType->typeIsConvertibleTo(RecordRecTy::get(Records, {}))) {
1556 Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1557 "got value of type '") + ArgType->getAsString() +
1558 "'");
1559 return nullptr;
1561 break;
1562 case BinOpInit::LE:
1563 case BinOpInit::LT:
1564 case BinOpInit::GE:
1565 case BinOpInit::GT:
1566 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1567 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records))) {
1568 Error(InitLoc, Twine("expected bit, bits, int, or string; "
1569 "got value of type '") + ArgType->getAsString() +
1570 "'");
1571 return nullptr;
1573 break;
1574 case BinOpInit::INTERLEAVE:
1575 switch (InitList.size()) {
1576 case 1: // First argument must be a list of strings or integers.
1577 if (ArgType != StringRecTy::get(Records)->getListTy() &&
1578 !ArgType->typeIsConvertibleTo(
1579 IntRecTy::get(Records)->getListTy())) {
1580 Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1581 "got value of type '") +
1582 ArgType->getAsString() + "'");
1583 return nullptr;
1585 break;
1586 case 2: // Second argument must be a string.
1587 if (!isa<StringRecTy>(ArgType)) {
1588 Error(InitLoc, Twine("expected second argument to be a string, "
1589 "got value of type '") +
1590 ArgType->getAsString() + "'");
1591 return nullptr;
1593 break;
1594 default: ;
1596 ArgType = nullptr; // Broken invariant: types not identical.
1597 break;
1598 default: llvm_unreachable("other ops have fixed argument types");
1601 } else {
1602 // Desired argument type is a known and in ArgType.
1603 RecTy *Resolved = resolveTypes(ArgType, ListType);
1604 if (!Resolved) {
1605 Error(InitLoc, Twine("expected value of type '") +
1606 ArgType->getAsString() + "', got '" +
1607 ListType->getAsString() + "'");
1608 return nullptr;
1610 if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1611 Code != BinOpInit::AND && Code != BinOpInit::OR &&
1612 Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1613 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1614 Code != BinOpInit::MUL && Code != BinOpInit::DIV)
1615 ArgType = Resolved;
1618 // Deal with BinOps whose arguments have different types, by
1619 // rewriting ArgType in between them.
1620 switch (Code) {
1621 case BinOpInit::SETDAGOP:
1622 // After parsing the first dag argument, switch to expecting
1623 // a record, with no restriction on its superclasses.
1624 ArgType = RecordRecTy::get(Records, {});
1625 break;
1626 default:
1627 break;
1630 if (!consume(tgtok::comma))
1631 break;
1634 if (!consume(tgtok::r_paren)) {
1635 TokError("expected ')' in operator");
1636 return nullptr;
1639 // listconcat returns a list with type of the argument.
1640 if (Code == BinOpInit::LISTCONCAT)
1641 Type = ArgType;
1642 // listsplat returns a list of type of the *first* argument.
1643 if (Code == BinOpInit::LISTSPLAT)
1644 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1645 // listremove returns a list with type of the argument.
1646 if (Code == BinOpInit::LISTREMOVE)
1647 Type = ArgType;
1649 if (Code == BinOpInit::RANGE) {
1650 Init *LHS, *RHS;
1651 auto ArgCount = InitList.size();
1652 assert(ArgCount >= 1);
1653 auto *Arg0 = cast<TypedInit>(InitList[0]);
1654 auto *Arg0Ty = Arg0->getType();
1655 if (ArgCount == 1) {
1656 if (isa<ListRecTy>(Arg0Ty)) {
1657 // (0, !size(arg))
1658 LHS = IntInit::get(Records, 0);
1659 RHS = UnOpInit::get(UnOpInit::SIZE, Arg0, IntRecTy::get(Records))
1660 ->Fold(CurRec);
1661 } else {
1662 assert(isa<IntRecTy>(Arg0Ty));
1663 // (0, arg)
1664 LHS = IntInit::get(Records, 0);
1665 RHS = Arg0;
1667 } else if (ArgCount == 2) {
1668 assert(isa<IntRecTy>(Arg0Ty));
1669 auto *Arg1 = cast<TypedInit>(InitList[1]);
1670 assert(isa<IntRecTy>(Arg1->getType()));
1671 LHS = Arg0;
1672 RHS = Arg1;
1673 } else {
1674 Error(OpLoc, "expected at most two values of integer");
1675 return nullptr;
1677 return BinOpInit::get(Code, LHS, RHS, Type)->Fold(CurRec);
1680 // We allow multiple operands to associative operators like !strconcat as
1681 // shorthand for nesting them.
1682 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1683 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1684 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1685 Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1686 while (InitList.size() > 2) {
1687 Init *RHS = InitList.pop_back_val();
1688 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1689 InitList.back() = RHS;
1693 if (InitList.size() == 2)
1694 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1695 ->Fold(CurRec);
1697 Error(OpLoc, "expected two operands to operator");
1698 return nullptr;
1701 case tgtok::XForEach:
1702 case tgtok::XFilter: {
1703 return ParseOperationForEachFilter(CurRec, ItemType);
1706 case tgtok::XDag:
1707 case tgtok::XIf:
1708 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1709 TernOpInit::TernaryOp Code;
1710 RecTy *Type = nullptr;
1712 tgtok::TokKind LexCode = Lex.getCode();
1713 Lex.Lex(); // eat the operation
1714 switch (LexCode) {
1715 default: llvm_unreachable("Unhandled code!");
1716 case tgtok::XDag:
1717 Code = TernOpInit::DAG;
1718 Type = DagRecTy::get(Records);
1719 ItemType = nullptr;
1720 break;
1721 case tgtok::XIf:
1722 Code = TernOpInit::IF;
1723 break;
1724 case tgtok::XSubst:
1725 Code = TernOpInit::SUBST;
1726 break;
1728 if (!consume(tgtok::l_paren)) {
1729 TokError("expected '(' after ternary operator");
1730 return nullptr;
1733 Init *LHS = ParseValue(CurRec);
1734 if (!LHS) return nullptr;
1736 if (!consume(tgtok::comma)) {
1737 TokError("expected ',' in ternary operator");
1738 return nullptr;
1741 SMLoc MHSLoc = Lex.getLoc();
1742 Init *MHS = ParseValue(CurRec, ItemType);
1743 if (!MHS)
1744 return nullptr;
1746 if (!consume(tgtok::comma)) {
1747 TokError("expected ',' in ternary operator");
1748 return nullptr;
1751 SMLoc RHSLoc = Lex.getLoc();
1752 Init *RHS = ParseValue(CurRec, ItemType);
1753 if (!RHS)
1754 return nullptr;
1756 if (!consume(tgtok::r_paren)) {
1757 TokError("expected ')' in binary operator");
1758 return nullptr;
1761 switch (LexCode) {
1762 default: llvm_unreachable("Unhandled code!");
1763 case tgtok::XDag: {
1764 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1765 if (!MHSt && !isa<UnsetInit>(MHS)) {
1766 Error(MHSLoc, "could not determine type of the child list in !dag");
1767 return nullptr;
1769 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1770 Error(MHSLoc, Twine("expected list of children, got type '") +
1771 MHSt->getType()->getAsString() + "'");
1772 return nullptr;
1775 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1776 if (!RHSt && !isa<UnsetInit>(RHS)) {
1777 Error(RHSLoc, "could not determine type of the name list in !dag");
1778 return nullptr;
1780 if (RHSt && StringRecTy::get(Records)->getListTy() != RHSt->getType()) {
1781 Error(RHSLoc, Twine("expected list<string>, got type '") +
1782 RHSt->getType()->getAsString() + "'");
1783 return nullptr;
1786 if (!MHSt && !RHSt) {
1787 Error(MHSLoc,
1788 "cannot have both unset children and unset names in !dag");
1789 return nullptr;
1791 break;
1793 case tgtok::XIf: {
1794 RecTy *MHSTy = nullptr;
1795 RecTy *RHSTy = nullptr;
1797 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1798 MHSTy = MHSt->getType();
1799 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1800 MHSTy = BitsRecTy::get(Records, MHSbits->getNumBits());
1801 if (isa<BitInit>(MHS))
1802 MHSTy = BitRecTy::get(Records);
1804 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1805 RHSTy = RHSt->getType();
1806 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1807 RHSTy = BitsRecTy::get(Records, RHSbits->getNumBits());
1808 if (isa<BitInit>(RHS))
1809 RHSTy = BitRecTy::get(Records);
1811 // For UnsetInit, it's typed from the other hand.
1812 if (isa<UnsetInit>(MHS))
1813 MHSTy = RHSTy;
1814 if (isa<UnsetInit>(RHS))
1815 RHSTy = MHSTy;
1817 if (!MHSTy || !RHSTy) {
1818 TokError("could not get type for !if");
1819 return nullptr;
1822 Type = resolveTypes(MHSTy, RHSTy);
1823 if (!Type) {
1824 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1825 "' and '" + RHSTy->getAsString() + "' for !if");
1826 return nullptr;
1828 break;
1830 case tgtok::XSubst: {
1831 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1832 if (!RHSt) {
1833 TokError("could not get type for !subst");
1834 return nullptr;
1836 Type = RHSt->getType();
1837 break;
1840 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1843 case tgtok::XSubstr:
1844 return ParseOperationSubstr(CurRec, ItemType);
1846 case tgtok::XFind:
1847 return ParseOperationFind(CurRec, ItemType);
1849 case tgtok::XCond:
1850 return ParseOperationCond(CurRec, ItemType);
1852 case tgtok::XFoldl: {
1853 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1854 Lex.Lex(); // eat the operation
1855 if (!consume(tgtok::l_paren)) {
1856 TokError("expected '(' after !foldl");
1857 return nullptr;
1860 Init *StartUntyped = ParseValue(CurRec);
1861 if (!StartUntyped)
1862 return nullptr;
1864 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1865 if (!Start) {
1866 TokError(Twine("could not get type of !foldl start: '") +
1867 StartUntyped->getAsString() + "'");
1868 return nullptr;
1871 if (!consume(tgtok::comma)) {
1872 TokError("expected ',' in !foldl");
1873 return nullptr;
1876 Init *ListUntyped = ParseValue(CurRec);
1877 if (!ListUntyped)
1878 return nullptr;
1880 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1881 if (!List) {
1882 TokError(Twine("could not get type of !foldl list: '") +
1883 ListUntyped->getAsString() + "'");
1884 return nullptr;
1887 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1888 if (!ListType) {
1889 TokError(Twine("!foldl list must be a list, but is of type '") +
1890 List->getType()->getAsString());
1891 return nullptr;
1894 if (Lex.getCode() != tgtok::comma) {
1895 TokError("expected ',' in !foldl");
1896 return nullptr;
1899 if (Lex.Lex() != tgtok::Id) { // eat the ','
1900 TokError("third argument of !foldl must be an identifier");
1901 return nullptr;
1904 Init *A = StringInit::get(Records, Lex.getCurStrVal());
1905 if (CurRec && CurRec->getValue(A)) {
1906 TokError((Twine("left !foldl variable '") + A->getAsString() +
1907 "' already defined")
1908 .str());
1909 return nullptr;
1912 if (Lex.Lex() != tgtok::comma) { // eat the id
1913 TokError("expected ',' in !foldl");
1914 return nullptr;
1917 if (Lex.Lex() != tgtok::Id) { // eat the ','
1918 TokError("fourth argument of !foldl must be an identifier");
1919 return nullptr;
1922 Init *B = StringInit::get(Records, Lex.getCurStrVal());
1923 if (CurRec && CurRec->getValue(B)) {
1924 TokError((Twine("right !foldl variable '") + B->getAsString() +
1925 "' already defined")
1926 .str());
1927 return nullptr;
1930 if (Lex.Lex() != tgtok::comma) { // eat the id
1931 TokError("expected ',' in !foldl");
1932 return nullptr;
1934 Lex.Lex(); // eat the ','
1936 // We need to create a temporary record to provide a scope for the
1937 // two variables.
1938 std::unique_ptr<Record> ParseRecTmp;
1939 Record *ParseRec = CurRec;
1940 if (!ParseRec) {
1941 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1942 ParseRec = ParseRecTmp.get();
1945 ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
1946 ParseRec->addValue(RecordVal(B, ListType->getElementType(),
1947 RecordVal::FK_Normal));
1948 Init *ExprUntyped = ParseValue(ParseRec);
1949 ParseRec->removeValue(A);
1950 ParseRec->removeValue(B);
1951 if (!ExprUntyped)
1952 return nullptr;
1954 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1955 if (!Expr) {
1956 TokError("could not get type of !foldl expression");
1957 return nullptr;
1960 if (Expr->getType() != Start->getType()) {
1961 TokError(Twine("!foldl expression must be of same type as start (") +
1962 Start->getType()->getAsString() + "), but is of type " +
1963 Expr->getType()->getAsString());
1964 return nullptr;
1967 if (!consume(tgtok::r_paren)) {
1968 TokError("expected ')' in fold operator");
1969 return nullptr;
1972 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1973 ->Fold(CurRec);
1978 /// ParseOperatorType - Parse a type for an operator. This returns
1979 /// null on error.
1981 /// OperatorType ::= '<' Type '>'
1983 RecTy *TGParser::ParseOperatorType() {
1984 RecTy *Type = nullptr;
1986 if (!consume(tgtok::less)) {
1987 TokError("expected type name for operator");
1988 return nullptr;
1991 if (Lex.getCode() == tgtok::Code)
1992 TokError("the 'code' type is not allowed in bang operators; use 'string'");
1994 Type = ParseType();
1996 if (!Type) {
1997 TokError("expected type name for operator");
1998 return nullptr;
2001 if (!consume(tgtok::greater)) {
2002 TokError("expected type name for operator");
2003 return nullptr;
2006 return Type;
2009 /// Parse the !substr operation. Return null on error.
2011 /// Substr ::= !substr(string, start-int [, length-int]) => string
2012 Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
2013 TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
2014 RecTy *Type = StringRecTy::get(Records);
2016 Lex.Lex(); // eat the operation
2018 if (!consume(tgtok::l_paren)) {
2019 TokError("expected '(' after !substr operator");
2020 return nullptr;
2023 Init *LHS = ParseValue(CurRec);
2024 if (!LHS)
2025 return nullptr;
2027 if (!consume(tgtok::comma)) {
2028 TokError("expected ',' in !substr operator");
2029 return nullptr;
2032 SMLoc MHSLoc = Lex.getLoc();
2033 Init *MHS = ParseValue(CurRec);
2034 if (!MHS)
2035 return nullptr;
2037 SMLoc RHSLoc = Lex.getLoc();
2038 Init *RHS;
2039 if (consume(tgtok::comma)) {
2040 RHSLoc = Lex.getLoc();
2041 RHS = ParseValue(CurRec);
2042 if (!RHS)
2043 return nullptr;
2044 } else {
2045 RHS = IntInit::get(Records, std::numeric_limits<int64_t>::max());
2048 if (!consume(tgtok::r_paren)) {
2049 TokError("expected ')' in !substr operator");
2050 return nullptr;
2053 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2054 Error(RHSLoc, Twine("expected value of type '") +
2055 ItemType->getAsString() + "', got '" +
2056 Type->getAsString() + "'");
2059 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
2060 if (!LHSt && !isa<UnsetInit>(LHS)) {
2061 TokError("could not determine type of the string in !substr");
2062 return nullptr;
2064 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2065 TokError(Twine("expected string, got type '") +
2066 LHSt->getType()->getAsString() + "'");
2067 return nullptr;
2070 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2071 if (!MHSt && !isa<UnsetInit>(MHS)) {
2072 TokError("could not determine type of the start position in !substr");
2073 return nullptr;
2075 if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
2076 Error(MHSLoc, Twine("expected int, got type '") +
2077 MHSt->getType()->getAsString() + "'");
2078 return nullptr;
2081 if (RHS) {
2082 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2083 if (!RHSt && !isa<UnsetInit>(RHS)) {
2084 TokError("could not determine type of the length in !substr");
2085 return nullptr;
2087 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2088 TokError(Twine("expected int, got type '") +
2089 RHSt->getType()->getAsString() + "'");
2090 return nullptr;
2094 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2097 /// Parse the !find operation. Return null on error.
2099 /// Substr ::= !find(string, string [, start-int]) => int
2100 Init *TGParser::ParseOperationFind(Record *CurRec, RecTy *ItemType) {
2101 TernOpInit::TernaryOp Code = TernOpInit::FIND;
2102 RecTy *Type = IntRecTy::get(Records);
2104 Lex.Lex(); // eat the operation
2106 if (!consume(tgtok::l_paren)) {
2107 TokError("expected '(' after !find operator");
2108 return nullptr;
2111 Init *LHS = ParseValue(CurRec);
2112 if (!LHS)
2113 return nullptr;
2115 if (!consume(tgtok::comma)) {
2116 TokError("expected ',' in !find operator");
2117 return nullptr;
2120 SMLoc MHSLoc = Lex.getLoc();
2121 Init *MHS = ParseValue(CurRec);
2122 if (!MHS)
2123 return nullptr;
2125 SMLoc RHSLoc = Lex.getLoc();
2126 Init *RHS;
2127 if (consume(tgtok::comma)) {
2128 RHSLoc = Lex.getLoc();
2129 RHS = ParseValue(CurRec);
2130 if (!RHS)
2131 return nullptr;
2132 } else {
2133 RHS = IntInit::get(Records, 0);
2136 if (!consume(tgtok::r_paren)) {
2137 TokError("expected ')' in !find operator");
2138 return nullptr;
2141 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2142 Error(RHSLoc, Twine("expected value of type '") +
2143 ItemType->getAsString() + "', got '" +
2144 Type->getAsString() + "'");
2147 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
2148 if (!LHSt && !isa<UnsetInit>(LHS)) {
2149 TokError("could not determine type of the source string in !find");
2150 return nullptr;
2152 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2153 TokError(Twine("expected string, got type '") +
2154 LHSt->getType()->getAsString() + "'");
2155 return nullptr;
2158 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2159 if (!MHSt && !isa<UnsetInit>(MHS)) {
2160 TokError("could not determine type of the target string in !find");
2161 return nullptr;
2163 if (MHSt && !isa<StringRecTy>(MHSt->getType())) {
2164 Error(MHSLoc, Twine("expected string, got type '") +
2165 MHSt->getType()->getAsString() + "'");
2166 return nullptr;
2169 if (RHS) {
2170 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2171 if (!RHSt && !isa<UnsetInit>(RHS)) {
2172 TokError("could not determine type of the start position in !find");
2173 return nullptr;
2175 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2176 TokError(Twine("expected int, got type '") +
2177 RHSt->getType()->getAsString() + "'");
2178 return nullptr;
2182 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2185 /// Parse the !foreach and !filter operations. Return null on error.
2187 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2188 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
2189 Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
2190 SMLoc OpLoc = Lex.getLoc();
2191 tgtok::TokKind Operation = Lex.getCode();
2192 Lex.Lex(); // eat the operation
2193 if (Lex.getCode() != tgtok::l_paren) {
2194 TokError("expected '(' after !foreach/!filter");
2195 return nullptr;
2198 if (Lex.Lex() != tgtok::Id) { // eat the '('
2199 TokError("first argument of !foreach/!filter must be an identifier");
2200 return nullptr;
2203 Init *LHS = StringInit::get(Records, Lex.getCurStrVal());
2204 Lex.Lex(); // eat the ID.
2206 if (CurRec && CurRec->getValue(LHS)) {
2207 TokError((Twine("iteration variable '") + LHS->getAsString() +
2208 "' is already defined")
2209 .str());
2210 return nullptr;
2213 if (!consume(tgtok::comma)) {
2214 TokError("expected ',' in !foreach/!filter");
2215 return nullptr;
2218 Init *MHS = ParseValue(CurRec);
2219 if (!MHS)
2220 return nullptr;
2222 if (!consume(tgtok::comma)) {
2223 TokError("expected ',' in !foreach/!filter");
2224 return nullptr;
2227 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2228 if (!MHSt) {
2229 TokError("could not get type of !foreach/!filter list or dag");
2230 return nullptr;
2233 RecTy *InEltType = nullptr;
2234 RecTy *ExprEltType = nullptr;
2235 bool IsDAG = false;
2237 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
2238 InEltType = InListTy->getElementType();
2239 if (ItemType) {
2240 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
2241 ExprEltType = (Operation == tgtok::XForEach)
2242 ? OutListTy->getElementType()
2243 : IntRecTy::get(Records);
2244 } else {
2245 Error(OpLoc,
2246 "expected value of type '" +
2247 Twine(ItemType->getAsString()) +
2248 "', but got list type");
2249 return nullptr;
2252 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
2253 if (Operation == tgtok::XFilter) {
2254 TokError("!filter must have a list argument");
2255 return nullptr;
2257 InEltType = InDagTy;
2258 if (ItemType && !isa<DagRecTy>(ItemType)) {
2259 Error(OpLoc,
2260 "expected value of type '" + Twine(ItemType->getAsString()) +
2261 "', but got dag type");
2262 return nullptr;
2264 IsDAG = true;
2265 } else {
2266 if (Operation == tgtok::XForEach)
2267 TokError("!foreach must have a list or dag argument");
2268 else
2269 TokError("!filter must have a list argument");
2270 return nullptr;
2273 // We need to create a temporary record to provide a scope for the
2274 // iteration variable.
2275 std::unique_ptr<Record> ParseRecTmp;
2276 Record *ParseRec = CurRec;
2277 if (!ParseRec) {
2278 ParseRecTmp =
2279 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
2280 ParseRec = ParseRecTmp.get();
2283 ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
2284 Init *RHS = ParseValue(ParseRec, ExprEltType);
2285 ParseRec->removeValue(LHS);
2286 if (!RHS)
2287 return nullptr;
2289 if (!consume(tgtok::r_paren)) {
2290 TokError("expected ')' in !foreach/!filter");
2291 return nullptr;
2294 RecTy *OutType = InEltType;
2295 if (Operation == tgtok::XForEach && !IsDAG) {
2296 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2297 if (!RHSt) {
2298 TokError("could not get type of !foreach result expression");
2299 return nullptr;
2301 OutType = RHSt->getType()->getListTy();
2302 } else if (Operation == tgtok::XFilter) {
2303 OutType = InEltType->getListTy();
2306 return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
2307 : TernOpInit::FILTER,
2308 LHS, MHS, RHS, OutType))
2309 ->Fold(CurRec);
2312 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
2313 Lex.Lex(); // eat the operation 'cond'
2315 if (!consume(tgtok::l_paren)) {
2316 TokError("expected '(' after !cond operator");
2317 return nullptr;
2320 // Parse through '[Case: Val,]+'
2321 SmallVector<Init *, 4> Case;
2322 SmallVector<Init *, 4> Val;
2323 while (true) {
2324 if (consume(tgtok::r_paren))
2325 break;
2327 Init *V = ParseValue(CurRec);
2328 if (!V)
2329 return nullptr;
2330 Case.push_back(V);
2332 if (!consume(tgtok::colon)) {
2333 TokError("expected ':' following a condition in !cond operator");
2334 return nullptr;
2337 V = ParseValue(CurRec, ItemType);
2338 if (!V)
2339 return nullptr;
2340 Val.push_back(V);
2342 if (consume(tgtok::r_paren))
2343 break;
2345 if (!consume(tgtok::comma)) {
2346 TokError("expected ',' or ')' following a value in !cond operator");
2347 return nullptr;
2351 if (Case.size() < 1) {
2352 TokError("there should be at least 1 'condition : value' in the !cond operator");
2353 return nullptr;
2356 // resolve type
2357 RecTy *Type = nullptr;
2358 for (Init *V : Val) {
2359 RecTy *VTy = nullptr;
2360 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
2361 VTy = Vt->getType();
2362 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
2363 VTy = BitsRecTy::get(Records, Vbits->getNumBits());
2364 if (isa<BitInit>(V))
2365 VTy = BitRecTy::get(Records);
2367 if (Type == nullptr) {
2368 if (!isa<UnsetInit>(V))
2369 Type = VTy;
2370 } else {
2371 if (!isa<UnsetInit>(V)) {
2372 RecTy *RType = resolveTypes(Type, VTy);
2373 if (!RType) {
2374 TokError(Twine("inconsistent types '") + Type->getAsString() +
2375 "' and '" + VTy->getAsString() + "' for !cond");
2376 return nullptr;
2378 Type = RType;
2383 if (!Type) {
2384 TokError("could not determine type for !cond from its arguments");
2385 return nullptr;
2387 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
2390 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2392 /// SimpleValue ::= IDValue
2393 /// SimpleValue ::= INTVAL
2394 /// SimpleValue ::= STRVAL+
2395 /// SimpleValue ::= CODEFRAGMENT
2396 /// SimpleValue ::= '?'
2397 /// SimpleValue ::= '{' ValueList '}'
2398 /// SimpleValue ::= ID '<' ValueListNE '>'
2399 /// SimpleValue ::= '[' ValueList ']'
2400 /// SimpleValue ::= '(' IDValue DagArgList ')'
2401 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2402 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2403 /// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2404 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2405 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2406 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2407 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2408 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2409 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2410 /// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2411 /// SimpleValue ::= RANGE '(' Value ')'
2412 /// SimpleValue ::= RANGE '(' Value ',' Value ')'
2413 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2414 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2416 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
2417 IDParseMode Mode) {
2418 Init *R = nullptr;
2419 switch (Lex.getCode()) {
2420 default: TokError("Unknown or reserved token when parsing a value"); break;
2422 case tgtok::TrueVal:
2423 R = IntInit::get(Records, 1);
2424 Lex.Lex();
2425 break;
2426 case tgtok::FalseVal:
2427 R = IntInit::get(Records, 0);
2428 Lex.Lex();
2429 break;
2430 case tgtok::IntVal:
2431 R = IntInit::get(Records, Lex.getCurIntVal());
2432 Lex.Lex();
2433 break;
2434 case tgtok::BinaryIntVal: {
2435 auto BinaryVal = Lex.getCurBinaryIntVal();
2436 SmallVector<Init*, 16> Bits(BinaryVal.second);
2437 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
2438 Bits[i] = BitInit::get(Records, BinaryVal.first & (1LL << i));
2439 R = BitsInit::get(Records, Bits);
2440 Lex.Lex();
2441 break;
2443 case tgtok::StrVal: {
2444 std::string Val = Lex.getCurStrVal();
2445 Lex.Lex();
2447 // Handle multiple consecutive concatenated strings.
2448 while (Lex.getCode() == tgtok::StrVal) {
2449 Val += Lex.getCurStrVal();
2450 Lex.Lex();
2453 R = StringInit::get(Records, Val);
2454 break;
2456 case tgtok::CodeFragment:
2457 R = StringInit::get(Records, Lex.getCurStrVal(), StringInit::SF_Code);
2458 Lex.Lex();
2459 break;
2460 case tgtok::question:
2461 R = UnsetInit::get(Records);
2462 Lex.Lex();
2463 break;
2464 case tgtok::Id: {
2465 SMRange NameLoc = Lex.getLocRange();
2466 StringInit *Name = StringInit::get(Records, Lex.getCurStrVal());
2467 if (Lex.Lex() != tgtok::less) // consume the Id.
2468 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
2470 // Value ::= CLASSID '<' ValueListNE '>' (CLASSID has been consumed)
2471 // This is supposed to synthesize a new anonymous definition, deriving
2472 // from the class with the template arguments, but no body.
2473 Record *Class = Records.getClass(Name->getValue());
2474 if (!Class) {
2475 Error(NameLoc.Start,
2476 "Expected a class name, got '" + Name->getValue() + "'");
2477 return nullptr;
2480 SmallVector<Init *, 8> Args;
2481 Lex.Lex(); // consume the <
2482 if (ParseTemplateArgValueList(Args, CurRec, Class))
2483 return nullptr; // Error parsing value list.
2485 if (CheckTemplateArgValues(Args, NameLoc.Start, Class))
2486 return nullptr; // Error checking template argument values.
2488 // Loop through the arguments that were not specified and make sure
2489 // they have a complete value.
2490 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
2491 for (unsigned I = Args.size(), E = TArgs.size(); I < E; ++I) {
2492 RecordVal *Arg = Class->getValue(TArgs[I]);
2493 if (!Arg->getValue()->isComplete()) {
2494 Error(NameLoc.Start, "Value not specified for template argument '" +
2495 TArgs[I]->getAsUnquotedString() + "' (#" +
2496 Twine(I) + ") of parent class '" +
2497 Class->getNameInitAsString() + "'");
2501 if (TrackReferenceLocs)
2502 Class->appendReferenceLoc(NameLoc);
2503 return VarDefInit::get(Class, Args)->Fold();
2505 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
2506 SMLoc BraceLoc = Lex.getLoc();
2507 Lex.Lex(); // eat the '{'
2508 SmallVector<Init*, 16> Vals;
2510 if (Lex.getCode() != tgtok::r_brace) {
2511 ParseValueList(Vals, CurRec);
2512 if (Vals.empty()) return nullptr;
2514 if (!consume(tgtok::r_brace)) {
2515 TokError("expected '}' at end of bit list value");
2516 return nullptr;
2519 SmallVector<Init *, 16> NewBits;
2521 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2522 // first. We'll first read everything in to a vector, then we can reverse
2523 // it to get the bits in the correct order for the BitsInit value.
2524 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2525 // FIXME: The following two loops would not be duplicated
2526 // if the API was a little more orthogonal.
2528 // bits<n> values are allowed to initialize n bits.
2529 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
2530 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2531 NewBits.push_back(BI->getBit((e - i) - 1));
2532 continue;
2534 // bits<n> can also come from variable initializers.
2535 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
2536 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2537 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2538 NewBits.push_back(VI->getBit((e - i) - 1));
2539 continue;
2541 // Fallthrough to try convert this to a bit.
2543 // All other values must be convertible to just a single bit.
2544 Init *Bit = Vals[i]->getCastTo(BitRecTy::get(Records));
2545 if (!Bit) {
2546 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2547 ") is not convertable to a bit");
2548 return nullptr;
2550 NewBits.push_back(Bit);
2552 std::reverse(NewBits.begin(), NewBits.end());
2553 return BitsInit::get(Records, NewBits);
2555 case tgtok::l_square: { // Value ::= '[' ValueList ']'
2556 Lex.Lex(); // eat the '['
2557 SmallVector<Init*, 16> Vals;
2559 RecTy *DeducedEltTy = nullptr;
2560 ListRecTy *GivenListTy = nullptr;
2562 if (ItemType) {
2563 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2564 if (!ListType) {
2565 TokError(Twine("Encountered a list when expecting a ") +
2566 ItemType->getAsString());
2567 return nullptr;
2569 GivenListTy = ListType;
2572 if (Lex.getCode() != tgtok::r_square) {
2573 ParseValueList(Vals, CurRec,
2574 GivenListTy ? GivenListTy->getElementType() : nullptr);
2575 if (Vals.empty()) return nullptr;
2577 if (!consume(tgtok::r_square)) {
2578 TokError("expected ']' at end of list value");
2579 return nullptr;
2582 RecTy *GivenEltTy = nullptr;
2583 if (consume(tgtok::less)) {
2584 // Optional list element type
2585 GivenEltTy = ParseType();
2586 if (!GivenEltTy) {
2587 // Couldn't parse element type
2588 return nullptr;
2591 if (!consume(tgtok::greater)) {
2592 TokError("expected '>' at end of list element type");
2593 return nullptr;
2597 // Check elements
2598 RecTy *EltTy = nullptr;
2599 for (Init *V : Vals) {
2600 TypedInit *TArg = dyn_cast<TypedInit>(V);
2601 if (TArg) {
2602 if (EltTy) {
2603 EltTy = resolveTypes(EltTy, TArg->getType());
2604 if (!EltTy) {
2605 TokError("Incompatible types in list elements");
2606 return nullptr;
2608 } else {
2609 EltTy = TArg->getType();
2614 if (GivenEltTy) {
2615 if (EltTy) {
2616 // Verify consistency
2617 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2618 TokError("Incompatible types in list elements");
2619 return nullptr;
2622 EltTy = GivenEltTy;
2625 if (!EltTy) {
2626 if (!ItemType) {
2627 TokError("No type for list");
2628 return nullptr;
2630 DeducedEltTy = GivenListTy->getElementType();
2631 } else {
2632 // Make sure the deduced type is compatible with the given type
2633 if (GivenListTy) {
2634 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2635 TokError(Twine("Element type mismatch for list: element type '") +
2636 EltTy->getAsString() + "' not convertible to '" +
2637 GivenListTy->getElementType()->getAsString());
2638 return nullptr;
2641 DeducedEltTy = EltTy;
2644 return ListInit::get(Vals, DeducedEltTy);
2646 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2647 Lex.Lex(); // eat the '('
2648 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2649 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2650 TokError("expected identifier in dag init");
2651 return nullptr;
2654 Init *Operator = ParseValue(CurRec);
2655 if (!Operator) return nullptr;
2657 // If the operator name is present, parse it.
2658 StringInit *OperatorName = nullptr;
2659 if (consume(tgtok::colon)) {
2660 if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2661 TokError("expected variable name in dag operator");
2662 return nullptr;
2664 OperatorName = StringInit::get(Records, Lex.getCurStrVal());
2665 Lex.Lex(); // eat the VarName.
2668 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2669 if (Lex.getCode() != tgtok::r_paren) {
2670 ParseDagArgList(DagArgs, CurRec);
2671 if (DagArgs.empty()) return nullptr;
2674 if (!consume(tgtok::r_paren)) {
2675 TokError("expected ')' in dag init");
2676 return nullptr;
2679 return DagInit::get(Operator, OperatorName, DagArgs);
2682 case tgtok::XHead:
2683 case tgtok::XTail:
2684 case tgtok::XSize:
2685 case tgtok::XEmpty:
2686 case tgtok::XCast:
2687 case tgtok::XToLower:
2688 case tgtok::XToUpper:
2689 case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
2690 case tgtok::XExists:
2691 case tgtok::XIsA:
2692 case tgtok::XConcat:
2693 case tgtok::XDag:
2694 case tgtok::XADD:
2695 case tgtok::XSUB:
2696 case tgtok::XMUL:
2697 case tgtok::XDIV:
2698 case tgtok::XNOT:
2699 case tgtok::XLOG2:
2700 case tgtok::XAND:
2701 case tgtok::XOR:
2702 case tgtok::XXOR:
2703 case tgtok::XSRA:
2704 case tgtok::XSRL:
2705 case tgtok::XSHL:
2706 case tgtok::XEq:
2707 case tgtok::XNe:
2708 case tgtok::XLe:
2709 case tgtok::XLt:
2710 case tgtok::XGe:
2711 case tgtok::XGt:
2712 case tgtok::XListConcat:
2713 case tgtok::XListSplat:
2714 case tgtok::XListRemove:
2715 case tgtok::XRange:
2716 case tgtok::XStrConcat:
2717 case tgtok::XInterleave:
2718 case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
2719 case tgtok::XIf:
2720 case tgtok::XCond:
2721 case tgtok::XFoldl:
2722 case tgtok::XForEach:
2723 case tgtok::XFilter:
2724 case tgtok::XSubst:
2725 case tgtok::XSubstr:
2726 case tgtok::XFind: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2727 return ParseOperation(CurRec, ItemType);
2731 return R;
2734 /// ParseValue - Parse a TableGen value. This returns null on error.
2736 /// Value ::= SimpleValue ValueSuffix*
2737 /// ValueSuffix ::= '{' BitList '}'
2738 /// ValueSuffix ::= '[' SliceElements ']'
2739 /// ValueSuffix ::= '.' ID
2741 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2742 SMLoc LHSLoc = Lex.getLoc();
2743 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2744 if (!Result) return nullptr;
2746 // Parse the suffixes now if present.
2747 while (true) {
2748 switch (Lex.getCode()) {
2749 default: return Result;
2750 case tgtok::l_brace: {
2751 if (Mode == ParseNameMode)
2752 // This is the beginning of the object body.
2753 return Result;
2755 SMLoc CurlyLoc = Lex.getLoc();
2756 Lex.Lex(); // eat the '{'
2757 SmallVector<unsigned, 16> Ranges;
2758 ParseRangeList(Ranges);
2759 if (Ranges.empty()) return nullptr;
2761 // Reverse the bitlist.
2762 std::reverse(Ranges.begin(), Ranges.end());
2763 Result = Result->convertInitializerBitRange(Ranges);
2764 if (!Result) {
2765 Error(CurlyLoc, "Invalid bit range for value");
2766 return nullptr;
2769 // Eat the '}'.
2770 if (!consume(tgtok::r_brace)) {
2771 TokError("expected '}' at end of bit range list");
2772 return nullptr;
2774 break;
2776 case tgtok::l_square: {
2777 auto *LHS = dyn_cast<TypedInit>(Result);
2778 if (!LHS) {
2779 Error(LHSLoc, "Invalid value, list expected");
2780 return nullptr;
2783 auto *LHSTy = dyn_cast<ListRecTy>(LHS->getType());
2784 if (!LHSTy) {
2785 Error(LHSLoc, "Type '" + Twine(LHS->getType()->getAsString()) +
2786 "' is invalid, list expected");
2787 return nullptr;
2790 Lex.Lex(); // eat the '['
2791 TypedInit *RHS = ParseSliceElements(CurRec, /*Single=*/true);
2792 if (!RHS)
2793 return nullptr;
2795 if (isa<ListRecTy>(RHS->getType())) {
2796 Result =
2797 BinOpInit::get(BinOpInit::LISTSLICE, LHS, RHS, LHSTy)->Fold(CurRec);
2798 } else {
2799 Result = BinOpInit::get(BinOpInit::LISTELEM, LHS, RHS,
2800 LHSTy->getElementType())
2801 ->Fold(CurRec);
2804 assert(Result);
2806 // Eat the ']'.
2807 if (!consume(tgtok::r_square)) {
2808 TokError("expected ']' at end of list slice");
2809 return nullptr;
2811 break;
2813 case tgtok::dot: {
2814 if (Lex.Lex() != tgtok::Id) { // eat the .
2815 TokError("expected field identifier after '.'");
2816 return nullptr;
2818 SMRange FieldNameLoc = Lex.getLocRange();
2819 StringInit *FieldName = StringInit::get(Records, Lex.getCurStrVal());
2820 if (!Result->getFieldType(FieldName)) {
2821 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2822 Result->getAsString() + "'");
2823 return nullptr;
2826 // Add a reference to this field if we know the record class.
2827 if (TrackReferenceLocs) {
2828 if (auto *DI = dyn_cast<DefInit>(Result)) {
2829 DI->getDef()->getValue(FieldName)->addReferenceLoc(FieldNameLoc);
2830 } else if (auto *TI = dyn_cast<TypedInit>(Result)) {
2831 if (auto *RecTy = dyn_cast<RecordRecTy>(TI->getType())) {
2832 for (Record *R : RecTy->getClasses())
2833 if (auto *RV = R->getValue(FieldName))
2834 RV->addReferenceLoc(FieldNameLoc);
2839 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2840 Lex.Lex(); // eat field name
2841 break;
2844 case tgtok::paste:
2845 SMLoc PasteLoc = Lex.getLoc();
2846 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2847 if (!LHS) {
2848 Error(PasteLoc, "LHS of paste is not typed!");
2849 return nullptr;
2852 // Check if it's a 'listA # listB'
2853 if (isa<ListRecTy>(LHS->getType())) {
2854 Lex.Lex(); // Eat the '#'.
2856 assert(Mode == ParseValueMode && "encountered paste of lists in name");
2858 switch (Lex.getCode()) {
2859 case tgtok::colon:
2860 case tgtok::semi:
2861 case tgtok::l_brace:
2862 Result = LHS; // trailing paste, ignore.
2863 break;
2864 default:
2865 Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
2866 if (!RHSResult)
2867 return nullptr;
2868 Result = BinOpInit::getListConcat(LHS, RHSResult);
2869 break;
2871 break;
2874 // Create a !strconcat() operation, first casting each operand to
2875 // a string if necessary.
2876 if (LHS->getType() != StringRecTy::get(Records)) {
2877 auto CastLHS = dyn_cast<TypedInit>(
2878 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get(Records))
2879 ->Fold(CurRec));
2880 if (!CastLHS) {
2881 Error(PasteLoc,
2882 Twine("can't cast '") + LHS->getAsString() + "' to string");
2883 return nullptr;
2885 LHS = CastLHS;
2888 TypedInit *RHS = nullptr;
2890 Lex.Lex(); // Eat the '#'.
2891 switch (Lex.getCode()) {
2892 case tgtok::colon:
2893 case tgtok::semi:
2894 case tgtok::l_brace:
2895 // These are all of the tokens that can begin an object body.
2896 // Some of these can also begin values but we disallow those cases
2897 // because they are unlikely to be useful.
2899 // Trailing paste, concat with an empty string.
2900 RHS = StringInit::get(Records, "");
2901 break;
2903 default:
2904 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2905 if (!RHSResult)
2906 return nullptr;
2907 RHS = dyn_cast<TypedInit>(RHSResult);
2908 if (!RHS) {
2909 Error(PasteLoc, "RHS of paste is not typed!");
2910 return nullptr;
2913 if (RHS->getType() != StringRecTy::get(Records)) {
2914 auto CastRHS = dyn_cast<TypedInit>(
2915 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get(Records))
2916 ->Fold(CurRec));
2917 if (!CastRHS) {
2918 Error(PasteLoc,
2919 Twine("can't cast '") + RHS->getAsString() + "' to string");
2920 return nullptr;
2922 RHS = CastRHS;
2925 break;
2928 Result = BinOpInit::getStrConcat(LHS, RHS);
2929 break;
2934 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2936 /// DagArg ::= Value (':' VARNAME)?
2937 /// DagArg ::= VARNAME
2938 /// DagArgList ::= DagArg
2939 /// DagArgList ::= DagArgList ',' DagArg
2940 void TGParser::ParseDagArgList(
2941 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2942 Record *CurRec) {
2944 while (true) {
2945 // DagArg ::= VARNAME
2946 if (Lex.getCode() == tgtok::VarName) {
2947 // A missing value is treated like '?'.
2948 StringInit *VarName = StringInit::get(Records, Lex.getCurStrVal());
2949 Result.emplace_back(UnsetInit::get(Records), VarName);
2950 Lex.Lex();
2951 } else {
2952 // DagArg ::= Value (':' VARNAME)?
2953 Init *Val = ParseValue(CurRec);
2954 if (!Val) {
2955 Result.clear();
2956 return;
2959 // If the variable name is present, add it.
2960 StringInit *VarName = nullptr;
2961 if (Lex.getCode() == tgtok::colon) {
2962 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2963 TokError("expected variable name in dag literal");
2964 Result.clear();
2965 return;
2967 VarName = StringInit::get(Records, Lex.getCurStrVal());
2968 Lex.Lex(); // eat the VarName.
2971 Result.push_back(std::make_pair(Val, VarName));
2973 if (!consume(tgtok::comma))
2974 break;
2978 /// ParseValueList - Parse a comma separated list of values, returning them
2979 /// in a vector. Note that this always expects to be able to parse at least one
2980 /// value. It returns an empty list if this is not possible.
2982 /// ValueList ::= Value (',' Value)
2984 void TGParser::ParseValueList(SmallVectorImpl<Init *> &Result, Record *CurRec,
2985 RecTy *ItemType) {
2987 Result.push_back(ParseValue(CurRec, ItemType));
2988 if (!Result.back()) {
2989 Result.clear();
2990 return;
2993 while (consume(tgtok::comma)) {
2994 // ignore trailing comma for lists
2995 if (Lex.getCode() == tgtok::r_square)
2996 return;
2997 Result.push_back(ParseValue(CurRec, ItemType));
2998 if (!Result.back()) {
2999 Result.clear();
3000 return;
3005 // ParseTemplateArgValueList - Parse a template argument list with the syntax
3006 // shown, filling in the Result vector. The open angle has been consumed.
3007 // An empty argument list is allowed. Return false if okay, true if an
3008 // error was detected.
3010 // TemplateArgList ::= '<' [Value {',' Value}*] '>'
3011 bool TGParser::ParseTemplateArgValueList(SmallVectorImpl<Init *> &Result,
3012 Record *CurRec, Record *ArgsRec) {
3014 assert(Result.empty() && "Result vector is not empty");
3015 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
3016 unsigned ArgIndex = 0;
3017 RecTy *ItemType;
3019 if (consume(tgtok::greater)) // empty value list
3020 return false;
3022 while (true) {
3023 if (ArgIndex >= TArgs.size()) {
3024 TokError("Too many template arguments: " + utostr(ArgIndex + 1));
3025 return true;
3027 const RecordVal *Arg = ArgsRec->getValue(TArgs[ArgIndex]);
3028 assert(Arg && "Template argument record not found");
3030 ItemType = Arg->getType();
3031 Init *Value = ParseValue(CurRec, ItemType);
3032 if (!Value)
3033 return true;
3034 Result.push_back(Value);
3036 if (consume(tgtok::greater)) // end of argument list?
3037 return false;
3038 if (!consume(tgtok::comma))
3039 return TokError("Expected comma before next argument");
3040 ++ArgIndex;
3044 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3045 /// empty string on error. This can happen in a number of different contexts,
3046 /// including within a def or in the template args for a class (in which case
3047 /// CurRec will be non-null) and within the template args for a multiclass (in
3048 /// which case CurRec will be null, but CurMultiClass will be set). This can
3049 /// also happen within a def that is within a multiclass, which will set both
3050 /// CurRec and CurMultiClass.
3052 /// Declaration ::= FIELD? Type ID ('=' Value)?
3054 Init *TGParser::ParseDeclaration(Record *CurRec,
3055 bool ParsingTemplateArgs) {
3056 // Read the field prefix if present.
3057 bool HasField = consume(tgtok::Field);
3059 RecTy *Type = ParseType();
3060 if (!Type) return nullptr;
3062 if (Lex.getCode() != tgtok::Id) {
3063 TokError("Expected identifier in declaration");
3064 return nullptr;
3067 std::string Str = Lex.getCurStrVal();
3068 if (Str == "NAME") {
3069 TokError("'" + Str + "' is a reserved variable name");
3070 return nullptr;
3073 SMLoc IdLoc = Lex.getLoc();
3074 Init *DeclName = StringInit::get(Records, Str);
3075 Lex.Lex();
3077 bool BadField;
3078 if (!ParsingTemplateArgs) { // def, possibly in a multiclass
3079 BadField = AddValue(CurRec, IdLoc,
3080 RecordVal(DeclName, IdLoc, Type,
3081 HasField ? RecordVal::FK_NonconcreteOK
3082 : RecordVal::FK_Normal));
3084 } else if (CurRec) { // class template argument
3085 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
3086 BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
3087 RecordVal::FK_TemplateArg));
3089 } else { // multiclass template argument
3090 assert(CurMultiClass && "invalid context for template argument");
3091 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName, "::");
3092 BadField = AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
3093 RecordVal::FK_TemplateArg));
3095 if (BadField)
3096 return nullptr;
3098 // If a value is present, parse it and set new field's value.
3099 if (consume(tgtok::equal)) {
3100 SMLoc ValLoc = Lex.getLoc();
3101 Init *Val = ParseValue(CurRec, Type);
3102 if (!Val ||
3103 SetValue(CurRec, ValLoc, DeclName, std::nullopt, Val,
3104 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3105 // Return the name, even if an error is thrown. This is so that we can
3106 // continue to make some progress, even without the value having been
3107 // initialized.
3108 return DeclName;
3112 return DeclName;
3115 /// ParseForeachDeclaration - Read a foreach declaration, returning
3116 /// the name of the declared object or a NULL Init on error. Return
3117 /// the name of the parsed initializer list through ForeachListName.
3119 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3120 /// ForeachDeclaration ::= ID '=' RangePiece
3121 /// ForeachDeclaration ::= ID '=' Value
3123 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
3124 if (Lex.getCode() != tgtok::Id) {
3125 TokError("Expected identifier in foreach declaration");
3126 return nullptr;
3129 Init *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3130 Lex.Lex();
3132 // If a value is present, parse it.
3133 if (!consume(tgtok::equal)) {
3134 TokError("Expected '=' in foreach declaration");
3135 return nullptr;
3138 RecTy *IterType = nullptr;
3139 SmallVector<unsigned, 16> Ranges;
3141 switch (Lex.getCode()) {
3142 case tgtok::l_brace: { // '{' RangeList '}'
3143 Lex.Lex(); // eat the '{'
3144 ParseRangeList(Ranges);
3145 if (!consume(tgtok::r_brace)) {
3146 TokError("expected '}' at end of bit range list");
3147 return nullptr;
3149 break;
3152 default: {
3153 SMLoc ValueLoc = Lex.getLoc();
3154 Init *I = ParseValue(nullptr);
3155 if (!I)
3156 return nullptr;
3158 TypedInit *TI = dyn_cast<TypedInit>(I);
3159 if (TI && isa<ListRecTy>(TI->getType())) {
3160 ForeachListValue = I;
3161 IterType = cast<ListRecTy>(TI->getType())->getElementType();
3162 break;
3165 if (TI) {
3166 if (ParseRangePiece(Ranges, TI))
3167 return nullptr;
3168 break;
3171 Error(ValueLoc, "expected a list, got '" + I->getAsString() + "'");
3172 if (CurMultiClass) {
3173 PrintNote({}, "references to multiclass template arguments cannot be "
3174 "resolved at this time");
3176 return nullptr;
3181 if (!Ranges.empty()) {
3182 assert(!IterType && "Type already initialized?");
3183 IterType = IntRecTy::get(Records);
3184 std::vector<Init *> Values;
3185 for (unsigned R : Ranges)
3186 Values.push_back(IntInit::get(Records, R));
3187 ForeachListValue = ListInit::get(Values, IterType);
3190 if (!IterType)
3191 return nullptr;
3193 return VarInit::get(DeclName, IterType);
3196 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
3197 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3198 /// template args for a class. If null, these are the template args for a
3199 /// multiclass.
3201 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3203 bool TGParser::ParseTemplateArgList(Record *CurRec) {
3204 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
3205 Lex.Lex(); // eat the '<'
3207 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
3209 // Read the first declaration.
3210 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
3211 if (!TemplArg)
3212 return true;
3214 TheRecToAddTo->addTemplateArg(TemplArg);
3216 while (consume(tgtok::comma)) {
3217 // Read the following declarations.
3218 SMLoc Loc = Lex.getLoc();
3219 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
3220 if (!TemplArg)
3221 return true;
3223 if (TheRecToAddTo->isTemplateArg(TemplArg))
3224 return Error(Loc, "template argument with the same name has already been "
3225 "defined");
3227 TheRecToAddTo->addTemplateArg(TemplArg);
3230 if (!consume(tgtok::greater))
3231 return TokError("expected '>' at end of template argument list");
3232 return false;
3235 /// ParseBodyItem - Parse a single item within the body of a def or class.
3237 /// BodyItem ::= Declaration ';'
3238 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
3239 /// BodyItem ::= Defvar
3240 /// BodyItem ::= Assert
3242 bool TGParser::ParseBodyItem(Record *CurRec) {
3243 if (Lex.getCode() == tgtok::Assert)
3244 return ParseAssert(nullptr, CurRec);
3246 if (Lex.getCode() == tgtok::Defvar)
3247 return ParseDefvar(CurRec);
3249 if (Lex.getCode() != tgtok::Let) {
3250 if (!ParseDeclaration(CurRec, false))
3251 return true;
3253 if (!consume(tgtok::semi))
3254 return TokError("expected ';' after declaration");
3255 return false;
3258 // LET ID OptionalRangeList '=' Value ';'
3259 if (Lex.Lex() != tgtok::Id)
3260 return TokError("expected field identifier after let");
3262 SMLoc IdLoc = Lex.getLoc();
3263 StringInit *FieldName = StringInit::get(Records, Lex.getCurStrVal());
3264 Lex.Lex(); // eat the field name.
3266 SmallVector<unsigned, 16> BitList;
3267 if (ParseOptionalBitList(BitList))
3268 return true;
3269 std::reverse(BitList.begin(), BitList.end());
3271 if (!consume(tgtok::equal))
3272 return TokError("expected '=' in let expression");
3274 RecordVal *Field = CurRec->getValue(FieldName);
3275 if (!Field)
3276 return TokError("Value '" + FieldName->getValue() + "' unknown!");
3278 RecTy *Type = Field->getType();
3279 if (!BitList.empty() && isa<BitsRecTy>(Type)) {
3280 // When assigning to a subset of a 'bits' object, expect the RHS to have
3281 // the type of that subset instead of the type of the whole object.
3282 Type = BitsRecTy::get(Records, BitList.size());
3285 Init *Val = ParseValue(CurRec, Type);
3286 if (!Val) return true;
3288 if (!consume(tgtok::semi))
3289 return TokError("expected ';' after let expression");
3291 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
3294 /// ParseBody - Read the body of a class or def. Return true on error, false on
3295 /// success.
3297 /// Body ::= ';'
3298 /// Body ::= '{' BodyList '}'
3299 /// BodyList BodyItem*
3301 bool TGParser::ParseBody(Record *CurRec) {
3302 // If this is a null definition, just eat the semi and return.
3303 if (consume(tgtok::semi))
3304 return false;
3306 if (!consume(tgtok::l_brace))
3307 return TokError("Expected '{' to start body or ';' for declaration only");
3309 // An object body introduces a new scope for local variables.
3310 TGLocalVarScope *BodyScope = PushLocalScope();
3312 while (Lex.getCode() != tgtok::r_brace)
3313 if (ParseBodyItem(CurRec))
3314 return true;
3316 PopLocalScope(BodyScope);
3318 // Eat the '}'.
3319 Lex.Lex();
3321 // If we have a semicolon, print a gentle error.
3322 SMLoc SemiLoc = Lex.getLoc();
3323 if (consume(tgtok::semi)) {
3324 PrintError(SemiLoc, "A class or def body should not end with a semicolon");
3325 PrintNote("Semicolon ignored; remove to eliminate this error");
3328 return false;
3331 /// Apply the current let bindings to \a CurRec.
3332 /// \returns true on error, false otherwise.
3333 bool TGParser::ApplyLetStack(Record *CurRec) {
3334 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
3335 for (LetRecord &LR : LetInfo)
3336 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
3337 return true;
3338 return false;
3341 /// Apply the current let bindings to the RecordsEntry.
3342 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
3343 if (Entry.Rec)
3344 return ApplyLetStack(Entry.Rec.get());
3346 // Let bindings are not applied to assertions.
3347 if (Entry.Assertion)
3348 return false;
3350 for (auto &E : Entry.Loop->Entries) {
3351 if (ApplyLetStack(E))
3352 return true;
3355 return false;
3358 /// ParseObjectBody - Parse the body of a def or class. This consists of an
3359 /// optional ClassList followed by a Body. CurRec is the current def or class
3360 /// that is being parsed.
3362 /// ObjectBody ::= BaseClassList Body
3363 /// BaseClassList ::= /*empty*/
3364 /// BaseClassList ::= ':' BaseClassListNE
3365 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3367 bool TGParser::ParseObjectBody(Record *CurRec) {
3368 // If there is a baseclass list, read it.
3369 if (consume(tgtok::colon)) {
3371 // Read all of the subclasses.
3372 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
3373 while (true) {
3374 // Check for error.
3375 if (!SubClass.Rec) return true;
3377 // Add it.
3378 if (AddSubClass(CurRec, SubClass))
3379 return true;
3381 if (!consume(tgtok::comma))
3382 break;
3383 SubClass = ParseSubClassReference(CurRec, false);
3387 if (ApplyLetStack(CurRec))
3388 return true;
3390 return ParseBody(CurRec);
3393 /// ParseDef - Parse and return a top level or multiclass record definition.
3394 /// Return false if okay, true if error.
3396 /// DefInst ::= DEF ObjectName ObjectBody
3398 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
3399 SMLoc DefLoc = Lex.getLoc();
3400 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
3401 Lex.Lex(); // Eat the 'def' token.
3403 // If the name of the def is an Id token, use that for the location.
3404 // Otherwise, the name is more complex and we use the location of the 'def'
3405 // token.
3406 SMLoc NameLoc = Lex.getCode() == tgtok::Id ? Lex.getLoc() : DefLoc;
3408 // Parse ObjectName and make a record for it.
3409 std::unique_ptr<Record> CurRec;
3410 Init *Name = ParseObjectName(CurMultiClass);
3411 if (!Name)
3412 return true;
3414 if (isa<UnsetInit>(Name)) {
3415 CurRec =
3416 std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
3417 /*Anonymous=*/true);
3418 } else {
3419 CurRec = std::make_unique<Record>(Name, NameLoc, Records);
3422 if (ParseObjectBody(CurRec.get()))
3423 return true;
3425 return addEntry(std::move(CurRec));
3428 /// ParseDefset - Parse a defset statement.
3430 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3432 bool TGParser::ParseDefset() {
3433 assert(Lex.getCode() == tgtok::Defset);
3434 Lex.Lex(); // Eat the 'defset' token
3436 DefsetRecord Defset;
3437 Defset.Loc = Lex.getLoc();
3438 RecTy *Type = ParseType();
3439 if (!Type)
3440 return true;
3441 if (!isa<ListRecTy>(Type))
3442 return Error(Defset.Loc, "expected list type");
3443 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
3445 if (Lex.getCode() != tgtok::Id)
3446 return TokError("expected identifier");
3447 StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3448 if (Records.getGlobal(DeclName->getValue()))
3449 return TokError("def or global variable of this name already exists");
3451 if (Lex.Lex() != tgtok::equal) // Eat the identifier
3452 return TokError("expected '='");
3453 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
3454 return TokError("expected '{'");
3455 SMLoc BraceLoc = Lex.getLoc();
3456 Lex.Lex(); // Eat the '{'
3458 Defsets.push_back(&Defset);
3459 bool Err = ParseObjectList(nullptr);
3460 Defsets.pop_back();
3461 if (Err)
3462 return true;
3464 if (!consume(tgtok::r_brace)) {
3465 TokError("expected '}' at end of defset");
3466 return Error(BraceLoc, "to match this '{'");
3469 Records.addExtraGlobal(DeclName->getValue(),
3470 ListInit::get(Defset.Elements, Defset.EltTy));
3471 return false;
3474 /// ParseDefvar - Parse a defvar statement.
3476 /// Defvar ::= DEFVAR Id '=' Value ';'
3478 bool TGParser::ParseDefvar(Record *CurRec) {
3479 assert(Lex.getCode() == tgtok::Defvar);
3480 Lex.Lex(); // Eat the 'defvar' token
3482 if (Lex.getCode() != tgtok::Id)
3483 return TokError("expected identifier");
3484 StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3485 if (CurLocalScope) {
3486 if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
3487 return TokError("local variable of this name already exists");
3488 } else {
3489 if (Records.getGlobal(DeclName->getValue()))
3490 return TokError("def or global variable of this name already exists");
3493 Lex.Lex();
3494 if (!consume(tgtok::equal))
3495 return TokError("expected '='");
3497 Init *Value = ParseValue(CurRec);
3498 if (!Value)
3499 return true;
3501 if (!consume(tgtok::semi))
3502 return TokError("expected ';'");
3504 if (CurLocalScope)
3505 CurLocalScope->addVar(DeclName->getValue(), Value);
3506 else
3507 Records.addExtraGlobal(DeclName->getValue(), Value);
3509 return false;
3512 /// ParseForeach - Parse a for statement. Return the record corresponding
3513 /// to it. This returns true on error.
3515 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3516 /// Foreach ::= FOREACH Declaration IN Object
3518 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
3519 SMLoc Loc = Lex.getLoc();
3520 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
3521 Lex.Lex(); // Eat the 'for' token.
3523 // Make a temporary object to record items associated with the for
3524 // loop.
3525 Init *ListValue = nullptr;
3526 VarInit *IterName = ParseForeachDeclaration(ListValue);
3527 if (!IterName)
3528 return TokError("expected declaration in for");
3530 if (!consume(tgtok::In))
3531 return TokError("Unknown tok");
3533 // Create a loop object and remember it.
3534 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
3536 // A foreach loop introduces a new scope for local variables.
3537 TGLocalVarScope *ForeachScope = PushLocalScope();
3539 if (Lex.getCode() != tgtok::l_brace) {
3540 // FOREACH Declaration IN Object
3541 if (ParseObject(CurMultiClass))
3542 return true;
3543 } else {
3544 SMLoc BraceLoc = Lex.getLoc();
3545 // Otherwise, this is a group foreach.
3546 Lex.Lex(); // eat the '{'.
3548 // Parse the object list.
3549 if (ParseObjectList(CurMultiClass))
3550 return true;
3552 if (!consume(tgtok::r_brace)) {
3553 TokError("expected '}' at end of foreach command");
3554 return Error(BraceLoc, "to match this '{'");
3558 PopLocalScope(ForeachScope);
3560 // Resolve the loop or store it for later resolution.
3561 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3562 Loops.pop_back();
3564 return addEntry(std::move(Loop));
3567 /// ParseIf - Parse an if statement.
3569 /// If ::= IF Value THEN IfBody
3570 /// If ::= IF Value THEN IfBody ELSE IfBody
3572 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
3573 SMLoc Loc = Lex.getLoc();
3574 assert(Lex.getCode() == tgtok::If && "Unknown tok");
3575 Lex.Lex(); // Eat the 'if' token.
3577 // Make a temporary object to record items associated with the for
3578 // loop.
3579 Init *Condition = ParseValue(nullptr);
3580 if (!Condition)
3581 return true;
3583 if (!consume(tgtok::Then))
3584 return TokError("Unknown tok");
3586 // We have to be able to save if statements to execute later, and they have
3587 // to live on the same stack as foreach loops. The simplest implementation
3588 // technique is to convert each 'then' or 'else' clause *into* a foreach
3589 // loop, over a list of length 0 or 1 depending on the condition, and with no
3590 // iteration variable being assigned.
3592 ListInit *EmptyList = ListInit::get({}, BitRecTy::get(Records));
3593 ListInit *SingletonList =
3594 ListInit::get({BitInit::get(Records, true)}, BitRecTy::get(Records));
3595 RecTy *BitListTy = ListRecTy::get(BitRecTy::get(Records));
3597 // The foreach containing the then-clause selects SingletonList if
3598 // the condition is true.
3599 Init *ThenClauseList =
3600 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
3601 BitListTy)
3602 ->Fold(nullptr);
3603 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
3605 if (ParseIfBody(CurMultiClass, "then"))
3606 return true;
3608 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3609 Loops.pop_back();
3611 if (addEntry(std::move(Loop)))
3612 return true;
3614 // Now look for an optional else clause. The if-else syntax has the usual
3615 // dangling-else ambiguity, and by greedily matching an else here if we can,
3616 // we implement the usual resolution of pairing with the innermost unmatched
3617 // if.
3618 if (consume(tgtok::ElseKW)) {
3619 // The foreach containing the else-clause uses the same pair of lists as
3620 // above, but this time, selects SingletonList if the condition is *false*.
3621 Init *ElseClauseList =
3622 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
3623 BitListTy)
3624 ->Fold(nullptr);
3625 Loops.push_back(
3626 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
3628 if (ParseIfBody(CurMultiClass, "else"))
3629 return true;
3631 Loop = std::move(Loops.back());
3632 Loops.pop_back();
3634 if (addEntry(std::move(Loop)))
3635 return true;
3638 return false;
3641 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3643 /// IfBody ::= Object
3644 /// IfBody ::= '{' ObjectList '}'
3646 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3647 TGLocalVarScope *BodyScope = PushLocalScope();
3649 if (Lex.getCode() != tgtok::l_brace) {
3650 // A single object.
3651 if (ParseObject(CurMultiClass))
3652 return true;
3653 } else {
3654 SMLoc BraceLoc = Lex.getLoc();
3655 // A braced block.
3656 Lex.Lex(); // eat the '{'.
3658 // Parse the object list.
3659 if (ParseObjectList(CurMultiClass))
3660 return true;
3662 if (!consume(tgtok::r_brace)) {
3663 TokError("expected '}' at end of '" + Kind + "' clause");
3664 return Error(BraceLoc, "to match this '{'");
3668 PopLocalScope(BodyScope);
3669 return false;
3672 /// ParseAssert - Parse an assert statement.
3674 /// Assert ::= ASSERT condition , message ;
3675 bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
3676 assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
3677 Lex.Lex(); // Eat the 'assert' token.
3679 SMLoc ConditionLoc = Lex.getLoc();
3680 Init *Condition = ParseValue(CurRec);
3681 if (!Condition)
3682 return true;
3684 if (!consume(tgtok::comma)) {
3685 TokError("expected ',' in assert statement");
3686 return true;
3689 Init *Message = ParseValue(CurRec);
3690 if (!Message)
3691 return true;
3693 if (!consume(tgtok::semi))
3694 return TokError("expected ';'");
3696 if (CurRec)
3697 CurRec->addAssertion(ConditionLoc, Condition, Message);
3698 else
3699 addEntry(std::make_unique<Record::AssertionInfo>(ConditionLoc, Condition,
3700 Message));
3701 return false;
3704 /// ParseClass - Parse a tblgen class definition.
3706 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3708 bool TGParser::ParseClass() {
3709 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3710 Lex.Lex();
3712 if (Lex.getCode() != tgtok::Id)
3713 return TokError("expected class name after 'class' keyword");
3715 Record *CurRec = Records.getClass(Lex.getCurStrVal());
3716 if (CurRec) {
3717 // If the body was previously defined, this is an error.
3718 if (!CurRec->getValues().empty() ||
3719 !CurRec->getSuperClasses().empty() ||
3720 !CurRec->getTemplateArgs().empty())
3721 return TokError("Class '" + CurRec->getNameInitAsString() +
3722 "' already defined");
3724 CurRec->updateClassLoc(Lex.getLoc());
3725 } else {
3726 // If this is the first reference to this class, create and add it.
3727 auto NewRec =
3728 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
3729 /*Class=*/true);
3730 CurRec = NewRec.get();
3731 Records.addClass(std::move(NewRec));
3733 Lex.Lex(); // eat the name.
3735 // If there are template args, parse them.
3736 if (Lex.getCode() == tgtok::less)
3737 if (ParseTemplateArgList(CurRec))
3738 return true;
3740 if (ParseObjectBody(CurRec))
3741 return true;
3743 if (!NoWarnOnUnusedTemplateArgs)
3744 CurRec->checkUnusedTemplateArgs();
3745 return false;
3748 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3749 /// of LetRecords.
3751 /// LetList ::= LetItem (',' LetItem)*
3752 /// LetItem ::= ID OptionalRangeList '=' Value
3754 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3755 do {
3756 if (Lex.getCode() != tgtok::Id) {
3757 TokError("expected identifier in let definition");
3758 Result.clear();
3759 return;
3762 StringInit *Name = StringInit::get(Records, Lex.getCurStrVal());
3763 SMLoc NameLoc = Lex.getLoc();
3764 Lex.Lex(); // Eat the identifier.
3766 // Check for an optional RangeList.
3767 SmallVector<unsigned, 16> Bits;
3768 if (ParseOptionalRangeList(Bits)) {
3769 Result.clear();
3770 return;
3772 std::reverse(Bits.begin(), Bits.end());
3774 if (!consume(tgtok::equal)) {
3775 TokError("expected '=' in let expression");
3776 Result.clear();
3777 return;
3780 Init *Val = ParseValue(nullptr);
3781 if (!Val) {
3782 Result.clear();
3783 return;
3786 // Now that we have everything, add the record.
3787 Result.emplace_back(Name, Bits, Val, NameLoc);
3788 } while (consume(tgtok::comma));
3791 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3792 /// different related productions. This works inside multiclasses too.
3794 /// Object ::= LET LetList IN '{' ObjectList '}'
3795 /// Object ::= LET LetList IN Object
3797 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
3798 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
3799 Lex.Lex();
3801 // Add this entry to the let stack.
3802 SmallVector<LetRecord, 8> LetInfo;
3803 ParseLetList(LetInfo);
3804 if (LetInfo.empty()) return true;
3805 LetStack.push_back(std::move(LetInfo));
3807 if (!consume(tgtok::In))
3808 return TokError("expected 'in' at end of top-level 'let'");
3810 TGLocalVarScope *LetScope = PushLocalScope();
3812 // If this is a scalar let, just handle it now
3813 if (Lex.getCode() != tgtok::l_brace) {
3814 // LET LetList IN Object
3815 if (ParseObject(CurMultiClass))
3816 return true;
3817 } else { // Object ::= LETCommand '{' ObjectList '}'
3818 SMLoc BraceLoc = Lex.getLoc();
3819 // Otherwise, this is a group let.
3820 Lex.Lex(); // eat the '{'.
3822 // Parse the object list.
3823 if (ParseObjectList(CurMultiClass))
3824 return true;
3826 if (!consume(tgtok::r_brace)) {
3827 TokError("expected '}' at end of top level let command");
3828 return Error(BraceLoc, "to match this '{'");
3832 PopLocalScope(LetScope);
3834 // Outside this let scope, this let block is not active.
3835 LetStack.pop_back();
3836 return false;
3839 /// ParseMultiClass - Parse a multiclass definition.
3841 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3842 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3843 /// MultiClassObject ::= Assert
3844 /// MultiClassObject ::= DefInst
3845 /// MultiClassObject ::= DefMInst
3846 /// MultiClassObject ::= Defvar
3847 /// MultiClassObject ::= Foreach
3848 /// MultiClassObject ::= If
3849 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3850 /// MultiClassObject ::= LETCommand Object
3852 bool TGParser::ParseMultiClass() {
3853 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
3854 Lex.Lex(); // Eat the multiclass token.
3856 if (Lex.getCode() != tgtok::Id)
3857 return TokError("expected identifier after multiclass for name");
3858 std::string Name = Lex.getCurStrVal();
3860 auto Result =
3861 MultiClasses.insert(std::make_pair(Name,
3862 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3864 if (!Result.second)
3865 return TokError("multiclass '" + Name + "' already defined");
3867 CurMultiClass = Result.first->second.get();
3868 Lex.Lex(); // Eat the identifier.
3870 // If there are template args, parse them.
3871 if (Lex.getCode() == tgtok::less)
3872 if (ParseTemplateArgList(nullptr))
3873 return true;
3875 bool inherits = false;
3877 // If there are submulticlasses, parse them.
3878 if (consume(tgtok::colon)) {
3879 inherits = true;
3881 // Read all of the submulticlasses.
3882 SubMultiClassReference SubMultiClass =
3883 ParseSubMultiClassReference(CurMultiClass);
3884 while (true) {
3885 // Check for error.
3886 if (!SubMultiClass.MC) return true;
3888 // Add it.
3889 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3890 return true;
3892 if (!consume(tgtok::comma))
3893 break;
3894 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3898 if (Lex.getCode() != tgtok::l_brace) {
3899 if (!inherits)
3900 return TokError("expected '{' in multiclass definition");
3901 if (!consume(tgtok::semi))
3902 return TokError("expected ';' in multiclass definition");
3903 } else {
3904 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3905 return TokError("multiclass must contain at least one def");
3907 // A multiclass body introduces a new scope for local variables.
3908 TGLocalVarScope *MulticlassScope = PushLocalScope();
3910 while (Lex.getCode() != tgtok::r_brace) {
3911 switch (Lex.getCode()) {
3912 default:
3913 return TokError("expected 'assert', 'def', 'defm', 'defvar', "
3914 "'foreach', 'if', or 'let' in multiclass body");
3916 case tgtok::Assert:
3917 case tgtok::Def:
3918 case tgtok::Defm:
3919 case tgtok::Defvar:
3920 case tgtok::Foreach:
3921 case tgtok::If:
3922 case tgtok::Let:
3923 if (ParseObject(CurMultiClass))
3924 return true;
3925 break;
3928 Lex.Lex(); // eat the '}'.
3930 // If we have a semicolon, print a gentle error.
3931 SMLoc SemiLoc = Lex.getLoc();
3932 if (consume(tgtok::semi)) {
3933 PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
3934 PrintNote("Semicolon ignored; remove to eliminate this error");
3937 PopLocalScope(MulticlassScope);
3940 if (!NoWarnOnUnusedTemplateArgs)
3941 CurMultiClass->Rec.checkUnusedTemplateArgs();
3943 CurMultiClass = nullptr;
3944 return false;
3947 /// ParseDefm - Parse the instantiation of a multiclass.
3949 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3951 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3952 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
3953 Lex.Lex(); // eat the defm
3955 Init *DefmName = ParseObjectName(CurMultiClass);
3956 if (!DefmName)
3957 return true;
3958 if (isa<UnsetInit>(DefmName)) {
3959 DefmName = Records.getNewAnonymousName();
3960 if (CurMultiClass)
3961 DefmName = BinOpInit::getStrConcat(
3962 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3963 StringRecTy::get(Records)),
3964 DefmName);
3967 if (Lex.getCode() != tgtok::colon)
3968 return TokError("expected ':' after defm identifier");
3970 // Keep track of the new generated record definitions.
3971 std::vector<RecordsEntry> NewEntries;
3973 // This record also inherits from a regular class (non-multiclass)?
3974 bool InheritFromClass = false;
3976 // eat the colon.
3977 Lex.Lex();
3979 SMLoc SubClassLoc = Lex.getLoc();
3980 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3982 while (true) {
3983 if (!Ref.Rec) return true;
3985 // To instantiate a multiclass, we get the multiclass and then loop
3986 // through its template argument names. Substs contains a substitution
3987 // value for each argument, either the value specified or the default.
3988 // Then we can resolve the template arguments.
3989 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
3990 assert(MC && "Didn't lookup multiclass correctly?");
3992 ArrayRef<Init *> TemplateVals = Ref.TemplateArgs;
3993 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3994 SubstStack Substs;
3996 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3997 if (i < TemplateVals.size()) {
3998 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3999 } else {
4000 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
4001 if (!Default->isComplete())
4002 return Error(SubClassLoc,
4003 "value not specified for template argument '" +
4004 TArgs[i]->getAsUnquotedString() + "' (#" +
4005 Twine(i) + ") of multiclass '" +
4006 MC->Rec.getNameInitAsString() + "'");
4007 Substs.emplace_back(TArgs[i], Default);
4011 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
4013 if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
4014 &NewEntries, &SubClassLoc))
4015 return true;
4017 if (!consume(tgtok::comma))
4018 break;
4020 if (Lex.getCode() != tgtok::Id)
4021 return TokError("expected identifier");
4023 SubClassLoc = Lex.getLoc();
4025 // A defm can inherit from regular classes (non-multiclasses) as
4026 // long as they come in the end of the inheritance list.
4027 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
4029 if (InheritFromClass)
4030 break;
4032 Ref = ParseSubClassReference(nullptr, true);
4035 if (InheritFromClass) {
4036 // Process all the classes to inherit as if they were part of a
4037 // regular 'def' and inherit all record values.
4038 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
4039 while (true) {
4040 // Check for error.
4041 if (!SubClass.Rec) return true;
4043 // Get the expanded definition prototypes and teach them about
4044 // the record values the current class to inherit has
4045 for (auto &E : NewEntries) {
4046 // Add it.
4047 if (AddSubClass(E, SubClass))
4048 return true;
4051 if (!consume(tgtok::comma))
4052 break;
4053 SubClass = ParseSubClassReference(nullptr, false);
4057 for (auto &E : NewEntries) {
4058 if (ApplyLetStack(E))
4059 return true;
4061 addEntry(std::move(E));
4064 if (!consume(tgtok::semi))
4065 return TokError("expected ';' at end of defm");
4067 return false;
4070 /// ParseObject
4071 /// Object ::= ClassInst
4072 /// Object ::= DefInst
4073 /// Object ::= MultiClassInst
4074 /// Object ::= DefMInst
4075 /// Object ::= LETCommand '{' ObjectList '}'
4076 /// Object ::= LETCommand Object
4077 /// Object ::= Defset
4078 /// Object ::= Defvar
4079 /// Object ::= Assert
4080 bool TGParser::ParseObject(MultiClass *MC) {
4081 switch (Lex.getCode()) {
4082 default:
4083 return TokError(
4084 "Expected assert, class, def, defm, defset, foreach, if, or let");
4085 case tgtok::Assert: return ParseAssert(MC);
4086 case tgtok::Def: return ParseDef(MC);
4087 case tgtok::Defm: return ParseDefm(MC);
4088 case tgtok::Defvar: return ParseDefvar();
4089 case tgtok::Foreach: return ParseForeach(MC);
4090 case tgtok::If: return ParseIf(MC);
4091 case tgtok::Let: return ParseTopLevelLet(MC);
4092 case tgtok::Defset:
4093 if (MC)
4094 return TokError("defset is not allowed inside multiclass");
4095 return ParseDefset();
4096 case tgtok::Class:
4097 if (MC)
4098 return TokError("class is not allowed inside multiclass");
4099 if (!Loops.empty())
4100 return TokError("class is not allowed inside foreach loop");
4101 return ParseClass();
4102 case tgtok::MultiClass:
4103 if (!Loops.empty())
4104 return TokError("multiclass is not allowed inside foreach loop");
4105 return ParseMultiClass();
4109 /// ParseObjectList
4110 /// ObjectList :== Object*
4111 bool TGParser::ParseObjectList(MultiClass *MC) {
4112 while (isObjectStart(Lex.getCode())) {
4113 if (ParseObject(MC))
4114 return true;
4116 return false;
4119 bool TGParser::ParseFile() {
4120 Lex.Lex(); // Prime the lexer.
4121 if (ParseObjectList()) return true;
4123 // If we have unread input at the end of the file, report it.
4124 if (Lex.getCode() == tgtok::Eof)
4125 return false;
4127 return TokError("Unexpected token at top level");
4130 // Check the types of the template argument values for a class
4131 // inheritance, multiclass invocation, or anonymous class invocation.
4132 // If necessary, replace an argument with a cast to the required type.
4133 // The argument count has already been checked.
4134 bool TGParser::CheckTemplateArgValues(SmallVectorImpl<llvm::Init *> &Values,
4135 SMLoc Loc, Record *ArgsRec) {
4137 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
4139 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4140 RecordVal *Arg = ArgsRec->getValue(TArgs[I]);
4141 RecTy *ArgType = Arg->getType();
4142 auto *Value = Values[I];
4144 if (TypedInit *ArgValue = dyn_cast<TypedInit>(Value)) {
4145 auto *CastValue = ArgValue->getCastTo(ArgType);
4146 if (CastValue) {
4147 assert((!isa<TypedInit>(CastValue) ||
4148 cast<TypedInit>(CastValue)->getType()->typeIsA(ArgType)) &&
4149 "result of template arg value cast has wrong type");
4150 Values[I] = CastValue;
4151 } else {
4152 PrintFatalError(Loc,
4153 "Value specified for template argument '" +
4154 Arg->getNameInitAsString() + "' (#" + Twine(I) +
4155 ") is of type " + ArgValue->getType()->getAsString() +
4156 "; expected type " + ArgType->getAsString() + ": " +
4157 ArgValue->getAsString());
4162 return false;
4165 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4166 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
4167 if (Loop)
4168 Loop->dump();
4169 if (Rec)
4170 Rec->dump();
4173 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
4174 errs() << "foreach " << IterVar->getAsString() << " = "
4175 << ListValue->getAsString() << " in {\n";
4177 for (const auto &E : Entries)
4178 E.dump();
4180 errs() << "}\n";
4183 LLVM_DUMP_METHOD void MultiClass::dump() const {
4184 errs() << "Record:\n";
4185 Rec.dump();
4187 errs() << "Defs:\n";
4188 for (const auto &E : Entries)
4189 E.dump();
4191 #endif