[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / llvm / lib / TableGen / TGParser.cpp
blobf4a62e6840f923340d56f39ea1a196086db30929
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 = nullptr;
39 SmallVector<ArgumentInit *, 4> TemplateArgs;
41 SubClassReference() = default;
43 bool isInvalid() const { return Rec == nullptr; }
46 struct SubMultiClassReference {
47 SMRange RefRange;
48 MultiClass *MC = nullptr;
49 SmallVector<ArgumentInit *, 4> TemplateArgs;
51 SubMultiClassReference() = default;
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, Init *Name) {
115 RecordKeeper &RK = CurRec.getRecords();
116 Init *NewName = BinOpInit::getStrConcat(
117 CurRec.getNameInit(),
118 StringInit::get(RK, CurRec.isMultiClass() ? "::" : ":"));
119 NewName = BinOpInit::getStrConcat(NewName, Name);
121 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
122 NewName = BinOp->Fold(&CurRec);
123 return NewName;
126 static Init *QualifyName(MultiClass *MC, Init *Name) {
127 return QualifyName(MC->Rec, Name);
130 /// Return the qualified version of the implicit 'NAME' template argument.
131 static Init *QualifiedNameOfImplicitName(Record &Rec) {
132 return QualifyName(Rec, StringInit::get(Rec.getRecords(), "NAME"));
135 static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
136 return QualifiedNameOfImplicitName(MC->Rec);
139 Init *TGVarScope::getVar(RecordKeeper &Records, MultiClass *ParsingMultiClass,
140 StringInit *Name, SMRange NameLoc,
141 bool TrackReferenceLocs) const {
142 // First, we search in local variables.
143 auto It = Vars.find(Name->getValue());
144 if (It != Vars.end())
145 return It->second;
147 auto FindValueInArgs = [&](Record *Rec, StringInit *Name) -> Init * {
148 if (!Rec)
149 return nullptr;
150 Init *ArgName = QualifyName(*Rec, Name);
151 if (Rec->isTemplateArg(ArgName)) {
152 RecordVal *RV = Rec->getValue(ArgName);
153 assert(RV && "Template arg doesn't exist??");
154 RV->setUsed(true);
155 if (TrackReferenceLocs)
156 RV->addReferenceLoc(NameLoc);
157 return VarInit::get(ArgName, RV->getType());
159 return Name->getValue() == "NAME"
160 ? VarInit::get(ArgName, StringRecTy::get(Records))
161 : nullptr;
164 // If not found, we try to find the variable in additional variables like
165 // arguments, loop iterator, etc.
166 switch (Kind) {
167 case SK_Local:
168 break; /* do nothing. */
169 case SK_Record: {
170 if (CurRec) {
171 // The variable is a record field?
172 if (RecordVal *RV = CurRec->getValue(Name)) {
173 if (TrackReferenceLocs)
174 RV->addReferenceLoc(NameLoc);
175 return VarInit::get(Name, RV->getType());
178 // The variable is a class template argument?
179 if (CurRec->isClass())
180 if (auto *V = FindValueInArgs(CurRec, Name))
181 return V;
183 break;
185 case SK_ForeachLoop: {
186 // The variable is a loop iterator?
187 if (CurLoop->IterVar) {
188 VarInit *IterVar = dyn_cast<VarInit>(CurLoop->IterVar);
189 if (IterVar && IterVar->getNameInit() == Name)
190 return IterVar;
192 break;
194 case SK_MultiClass: {
195 // The variable is a multiclass template argument?
196 if (CurMultiClass)
197 if (auto *V = FindValueInArgs(&CurMultiClass->Rec, Name))
198 return V;
199 break;
203 // Then, we try to find the name in parent scope.
204 if (Parent)
205 return Parent->getVar(Records, ParsingMultiClass, Name, NameLoc,
206 TrackReferenceLocs);
208 return nullptr;
211 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
212 if (!CurRec)
213 CurRec = &CurMultiClass->Rec;
215 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
216 // The value already exists in the class, treat this as a set.
217 if (ERV->setValue(RV.getValue()))
218 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
219 RV.getType()->getAsString() + "' is incompatible with " +
220 "previous definition of type '" +
221 ERV->getType()->getAsString() + "'");
222 } else {
223 CurRec->addValue(RV);
225 return false;
228 /// SetValue -
229 /// Return true on error, false on success.
230 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
231 ArrayRef<unsigned> BitList, Init *V,
232 bool AllowSelfAssignment, bool OverrideDefLoc) {
233 if (!V) return false;
235 if (!CurRec) CurRec = &CurMultiClass->Rec;
237 RecordVal *RV = CurRec->getValue(ValName);
238 if (!RV)
239 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
240 "' unknown!");
242 // Do not allow assignments like 'X = X'. This will just cause infinite loops
243 // in the resolution machinery.
244 if (BitList.empty())
245 if (VarInit *VI = dyn_cast<VarInit>(V))
246 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
247 return Error(Loc, "Recursion / self-assignment forbidden");
249 // If we are assigning to a subset of the bits in the value... then we must be
250 // assigning to a field of BitsRecTy, which must have a BitsInit
251 // initializer.
253 if (!BitList.empty()) {
254 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
255 if (!CurVal)
256 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
257 "' is not a bits type");
259 // Convert the incoming value to a bits type of the appropriate size...
260 Init *BI = V->getCastTo(BitsRecTy::get(Records, BitList.size()));
261 if (!BI)
262 return Error(Loc, "Initializer is not compatible with bit range");
264 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
266 // Loop over bits, assigning values as appropriate.
267 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
268 unsigned Bit = BitList[i];
269 if (NewBits[Bit])
270 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
271 ValName->getAsUnquotedString() + "' more than once");
272 NewBits[Bit] = BI->getBit(i);
275 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
276 if (!NewBits[i])
277 NewBits[i] = CurVal->getBit(i);
279 V = BitsInit::get(Records, NewBits);
282 if (OverrideDefLoc ? RV->setValue(V, Loc) : RV->setValue(V)) {
283 std::string InitType;
284 if (BitsInit *BI = dyn_cast<BitsInit>(V))
285 InitType = (Twine("' of type bit initializer with length ") +
286 Twine(BI->getNumBits())).str();
287 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
288 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
289 return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
290 "' of type '" + RV->getType()->getAsString() +
291 "' is incompatible with value '" +
292 V->getAsString() + InitType + "'");
294 return false;
297 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
298 /// args as SubClass's template arguments.
299 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
300 Record *SC = SubClass.Rec;
301 MapResolver R(CurRec);
303 // Loop over all the subclass record's fields. Add regular fields to the new
304 // record.
305 for (const RecordVal &Field : SC->getValues())
306 if (!Field.isTemplateArg())
307 if (AddValue(CurRec, SubClass.RefRange.Start, Field))
308 return true;
310 if (resolveArgumentsOfClass(R, SC, SubClass.TemplateArgs,
311 SubClass.RefRange.Start))
312 return true;
314 // Copy the subclass record's assertions to the new record.
315 CurRec->appendAssertions(SC);
317 // Copy the subclass record's dumps to the new record.
318 CurRec->appendDumps(SC);
320 Init *Name;
321 if (CurRec->isClass())
322 Name = VarInit::get(QualifiedNameOfImplicitName(*CurRec),
323 StringRecTy::get(Records));
324 else
325 Name = CurRec->getNameInit();
326 R.set(QualifiedNameOfImplicitName(*SC), Name);
328 CurRec->resolveReferences(R);
330 // Since everything went well, we can now set the "superclass" list for the
331 // current record.
332 ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
333 for (const auto &SCPair : SCs) {
334 if (CurRec->isSubClassOf(SCPair.first))
335 return Error(SubClass.RefRange.Start,
336 "Already subclass of '" + SCPair.first->getName() + "'!\n");
337 CurRec->addSuperClass(SCPair.first, SCPair.second);
340 if (CurRec->isSubClassOf(SC))
341 return Error(SubClass.RefRange.Start,
342 "Already subclass of '" + SC->getName() + "'!\n");
343 CurRec->addSuperClass(SC, SubClass.RefRange);
344 return false;
347 bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
348 if (Entry.Rec)
349 return AddSubClass(Entry.Rec.get(), SubClass);
351 if (Entry.Assertion)
352 return false;
354 for (auto &E : Entry.Loop->Entries) {
355 if (AddSubClass(E, SubClass))
356 return true;
359 return false;
362 /// AddSubMultiClass - Add SubMultiClass as a subclass to
363 /// CurMC, resolving its template args as SubMultiClass's
364 /// template arguments.
365 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
366 SubMultiClassReference &SubMultiClass) {
367 MultiClass *SMC = SubMultiClass.MC;
369 SubstStack Substs;
370 if (resolveArgumentsOfMultiClass(
371 Substs, SMC, SubMultiClass.TemplateArgs,
372 VarInit::get(QualifiedNameOfImplicitName(CurMC),
373 StringRecTy::get(Records)),
374 SubMultiClass.RefRange.Start))
375 return true;
377 // Add all of the defs in the subclass into the current multiclass.
378 return resolve(SMC->Entries, Substs, false, &CurMC->Entries);
381 /// Add a record, foreach loop, or assertion to the current context.
382 bool TGParser::addEntry(RecordsEntry E) {
383 assert((!!E.Rec + !!E.Loop + !!E.Assertion + !!E.Dump) == 1 &&
384 "RecordsEntry has invalid number of items");
386 // If we are parsing a loop, add it to the loop's entries.
387 if (!Loops.empty()) {
388 Loops.back()->Entries.push_back(std::move(E));
389 return false;
392 // If it is a loop, then resolve and perform the loop.
393 if (E.Loop) {
394 SubstStack Stack;
395 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
396 CurMultiClass ? &CurMultiClass->Entries : nullptr);
399 // If we are parsing a multiclass, add it to the multiclass's entries.
400 if (CurMultiClass) {
401 CurMultiClass->Entries.push_back(std::move(E));
402 return false;
405 // If it is an assertion, then it's a top-level one, so check it.
406 if (E.Assertion) {
407 CheckAssert(E.Assertion->Loc, E.Assertion->Condition, E.Assertion->Message);
408 return false;
411 if (E.Dump) {
412 dumpMessage(E.Dump->Loc, E.Dump->Message);
413 return false;
416 // It must be a record, so finish it off.
417 return addDefOne(std::move(E.Rec));
420 /// Resolve the entries in \p Loop, going over inner loops recursively
421 /// and making the given subsitutions of (name, value) pairs.
423 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
424 /// are added to the global record keeper.
425 bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
426 bool Final, std::vector<RecordsEntry> *Dest,
427 SMLoc *Loc) {
429 MapResolver R;
430 for (const auto &S : Substs)
431 R.set(S.first, S.second);
432 Init *List = Loop.ListValue->resolveReferences(R);
434 // For if-then-else blocks, we lower to a foreach loop whose list is a
435 // ternary selection between lists of different length. Since we don't
436 // have a means to track variable length record lists, we *must* resolve
437 // the condition here. We want to defer final resolution of the arms
438 // until the resulting records are finalized.
439 // e.g. !if(!exists<SchedWrite>("__does_not_exist__"), [1], [])
440 if (auto *TI = dyn_cast<TernOpInit>(List);
441 TI && TI->getOpcode() == TernOpInit::IF && Final) {
442 Init *OldLHS = TI->getLHS();
443 R.setFinal(true);
444 Init *LHS = OldLHS->resolveReferences(R);
445 if (LHS == OldLHS) {
446 PrintError(Loop.Loc,
447 Twine("unable to resolve if condition '") +
448 LHS->getAsString() + "' at end of containing scope");
449 return true;
451 Init *MHS = TI->getMHS();
452 Init *RHS = TI->getRHS();
453 List = TernOpInit::get(TernOpInit::IF, LHS, MHS, RHS, TI->getType())
454 ->Fold(nullptr);
457 auto LI = dyn_cast<ListInit>(List);
458 if (!LI) {
459 if (!Final) {
460 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
461 List));
462 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
463 Loc);
466 PrintError(Loop.Loc, Twine("attempting to loop over '") +
467 List->getAsString() + "', expected a list");
468 return true;
471 bool Error = false;
472 for (auto *Elt : *LI) {
473 if (Loop.IterVar)
474 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
475 Error = resolve(Loop.Entries, Substs, Final, Dest);
476 if (Loop.IterVar)
477 Substs.pop_back();
478 if (Error)
479 break;
481 return Error;
484 /// Resolve the entries in \p Source, going over loops recursively and
485 /// making the given substitutions of (name, value) pairs.
487 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
488 /// are added to the global record keeper.
489 bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
490 SubstStack &Substs, bool Final,
491 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
492 bool Error = false;
493 for (auto &E : Source) {
494 if (E.Loop) {
495 Error = resolve(*E.Loop, Substs, Final, Dest);
497 } else if (E.Assertion) {
498 MapResolver R;
499 for (const auto &S : Substs)
500 R.set(S.first, S.second);
501 Init *Condition = E.Assertion->Condition->resolveReferences(R);
502 Init *Message = E.Assertion->Message->resolveReferences(R);
504 if (Dest)
505 Dest->push_back(std::make_unique<Record::AssertionInfo>(
506 E.Assertion->Loc, Condition, Message));
507 else
508 CheckAssert(E.Assertion->Loc, Condition, Message);
510 } else if (E.Dump) {
511 MapResolver R;
512 for (const auto &S : Substs)
513 R.set(S.first, S.second);
514 Init *Message = E.Dump->Message->resolveReferences(R);
516 if (Dest)
517 Dest->push_back(
518 std::make_unique<Record::DumpInfo>(E.Dump->Loc, Message));
519 else
520 dumpMessage(E.Dump->Loc, Message);
522 } else {
523 auto Rec = std::make_unique<Record>(*E.Rec);
524 if (Loc)
525 Rec->appendLoc(*Loc);
527 MapResolver R(Rec.get());
528 for (const auto &S : Substs)
529 R.set(S.first, S.second);
530 Rec->resolveReferences(R);
532 if (Dest)
533 Dest->push_back(std::move(Rec));
534 else
535 Error = addDefOne(std::move(Rec));
537 if (Error)
538 break;
540 return Error;
543 /// Resolve the record fully and add it to the record keeper.
544 bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
545 Init *NewName = nullptr;
546 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
547 if (!Rec->isAnonymous()) {
548 PrintError(Rec->getLoc(),
549 "def already exists: " + Rec->getNameInitAsString());
550 PrintNote(Prev->getLoc(), "location of previous definition");
551 return true;
553 NewName = Records.getNewAnonymousName();
556 Rec->resolveReferences(NewName);
557 checkConcrete(*Rec);
559 if (!isa<StringInit>(Rec->getNameInit())) {
560 PrintError(Rec->getLoc(), Twine("record name '") +
561 Rec->getNameInit()->getAsString() +
562 "' could not be fully resolved");
563 return true;
566 // Check the assertions.
567 Rec->checkRecordAssertions();
569 // Run the dumps.
570 Rec->emitRecordDumps();
572 // If ObjectBody has template arguments, it's an error.
573 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
575 for (DefsetRecord *Defset : Defsets) {
576 DefInit *I = Rec->getDefInit();
577 if (!I->getType()->typeIsA(Defset->EltTy)) {
578 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
579 I->getType()->getAsString() +
580 "' to defset");
581 PrintNote(Defset->Loc, "location of defset declaration");
582 return true;
584 Defset->Elements.push_back(I);
587 Records.addDef(std::move(Rec));
588 return false;
591 bool TGParser::resolveArguments(Record *Rec, ArrayRef<ArgumentInit *> ArgValues,
592 SMLoc Loc, ArgValueHandler ArgValueHandler) {
593 ArrayRef<Init *> ArgNames = Rec->getTemplateArgs();
594 assert(ArgValues.size() <= ArgNames.size() &&
595 "Too many template arguments allowed");
597 // Loop over the template arguments and handle the (name, value) pair.
598 SmallVector<Init *, 2> UnsolvedArgNames(ArgNames);
599 for (auto *Arg : ArgValues) {
600 Init *ArgName = nullptr;
601 Init *ArgValue = Arg->getValue();
602 if (Arg->isPositional())
603 ArgName = ArgNames[Arg->getIndex()];
604 if (Arg->isNamed())
605 ArgName = Arg->getName();
607 // We can only specify the template argument once.
608 if (!is_contained(UnsolvedArgNames, ArgName))
609 return Error(Loc, "We can only specify the template argument '" +
610 ArgName->getAsUnquotedString() + "' once");
612 ArgValueHandler(ArgName, ArgValue);
613 llvm::erase(UnsolvedArgNames, ArgName);
616 // For unsolved arguments, if there is no default value, complain.
617 for (auto *UnsolvedArgName : UnsolvedArgNames) {
618 Init *Default = Rec->getValue(UnsolvedArgName)->getValue();
619 if (!Default->isComplete()) {
620 std::string Name = UnsolvedArgName->getAsUnquotedString();
621 Error(Loc, "value not specified for template argument '" + Name + "'");
622 PrintNote(Rec->getFieldLoc(Name),
623 "declared in '" + Rec->getNameInitAsString() + "'");
624 return true;
626 ArgValueHandler(UnsolvedArgName, Default);
629 return false;
632 /// Resolve the arguments of class and set them to MapResolver.
633 /// Returns true if failed.
634 bool TGParser::resolveArgumentsOfClass(MapResolver &R, Record *Rec,
635 ArrayRef<ArgumentInit *> ArgValues,
636 SMLoc Loc) {
637 return resolveArguments(Rec, ArgValues, Loc,
638 [&](Init *Name, Init *Value) { R.set(Name, Value); });
641 /// Resolve the arguments of multiclass and store them into SubstStack.
642 /// Returns true if failed.
643 bool TGParser::resolveArgumentsOfMultiClass(SubstStack &Substs, MultiClass *MC,
644 ArrayRef<ArgumentInit *> ArgValues,
645 Init *DefmName, SMLoc Loc) {
646 // Add an implicit argument NAME.
647 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
648 return resolveArguments(
649 &MC->Rec, ArgValues, Loc,
650 [&](Init *Name, Init *Value) { Substs.emplace_back(Name, Value); });
653 //===----------------------------------------------------------------------===//
654 // Parser Code
655 //===----------------------------------------------------------------------===//
657 bool TGParser::consume(tgtok::TokKind K) {
658 if (Lex.getCode() == K) {
659 Lex.Lex();
660 return true;
662 return false;
665 /// ParseObjectName - If a valid object name is specified, return it. If no
666 /// name is specified, return the unset initializer. Return nullptr on parse
667 /// error.
668 /// ObjectName ::= Value [ '#' Value ]*
669 /// ObjectName ::= /*empty*/
671 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
672 switch (Lex.getCode()) {
673 case tgtok::colon:
674 case tgtok::semi:
675 case tgtok::l_brace:
676 // These are all of the tokens that can begin an object body.
677 // Some of these can also begin values but we disallow those cases
678 // because they are unlikely to be useful.
679 return UnsetInit::get(Records);
680 default:
681 break;
684 Record *CurRec = nullptr;
685 if (CurMultiClass)
686 CurRec = &CurMultiClass->Rec;
688 Init *Name = ParseValue(CurRec, StringRecTy::get(Records), ParseNameMode);
689 if (!Name)
690 return nullptr;
692 if (CurMultiClass) {
693 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
694 HasReferenceResolver R(NameStr);
695 Name->resolveReferences(R);
696 if (!R.found())
697 Name = BinOpInit::getStrConcat(
698 VarInit::get(NameStr, StringRecTy::get(Records)), Name);
701 return Name;
704 /// ParseClassID - Parse and resolve a reference to a class name. This returns
705 /// null on error.
707 /// ClassID ::= ID
709 Record *TGParser::ParseClassID() {
710 if (Lex.getCode() != tgtok::Id) {
711 TokError("expected name for ClassID");
712 return nullptr;
715 Record *Result = Records.getClass(Lex.getCurStrVal());
716 if (!Result) {
717 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
718 if (MultiClasses[Lex.getCurStrVal()].get())
719 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
720 Lex.getCurStrVal() + "'");
721 else
722 TokError(Msg);
723 } else if (TrackReferenceLocs) {
724 Result->appendReferenceLoc(Lex.getLocRange());
727 Lex.Lex();
728 return Result;
731 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
732 /// This returns null on error.
734 /// MultiClassID ::= ID
736 MultiClass *TGParser::ParseMultiClassID() {
737 if (Lex.getCode() != tgtok::Id) {
738 TokError("expected name for MultiClassID");
739 return nullptr;
742 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
743 if (!Result)
744 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
746 Lex.Lex();
747 return Result;
750 /// ParseSubClassReference - Parse a reference to a subclass or a
751 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
753 /// SubClassRef ::= ClassID
754 /// SubClassRef ::= ClassID '<' ArgValueList '>'
756 SubClassReference TGParser::
757 ParseSubClassReference(Record *CurRec, bool isDefm) {
758 SubClassReference Result;
759 Result.RefRange.Start = Lex.getLoc();
761 if (isDefm) {
762 if (MultiClass *MC = ParseMultiClassID())
763 Result.Rec = &MC->Rec;
764 } else {
765 Result.Rec = ParseClassID();
767 if (!Result.Rec) return Result;
769 // If there is no template arg list, we're done.
770 if (!consume(tgtok::less)) {
771 Result.RefRange.End = Lex.getLoc();
772 return Result;
775 if (ParseTemplateArgValueList(Result.TemplateArgs, CurRec, Result.Rec)) {
776 Result.Rec = nullptr; // Error parsing value list.
777 return Result;
780 if (CheckTemplateArgValues(Result.TemplateArgs, Result.RefRange.Start,
781 Result.Rec)) {
782 Result.Rec = nullptr; // Error checking value list.
783 return Result;
786 Result.RefRange.End = Lex.getLoc();
787 return Result;
790 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
791 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
792 /// Record* on error.
794 /// SubMultiClassRef ::= MultiClassID
795 /// SubMultiClassRef ::= MultiClassID '<' ArgValueList '>'
797 SubMultiClassReference TGParser::
798 ParseSubMultiClassReference(MultiClass *CurMC) {
799 SubMultiClassReference Result;
800 Result.RefRange.Start = Lex.getLoc();
802 Result.MC = ParseMultiClassID();
803 if (!Result.MC) return Result;
805 // If there is no template arg list, we're done.
806 if (!consume(tgtok::less)) {
807 Result.RefRange.End = Lex.getLoc();
808 return Result;
811 if (ParseTemplateArgValueList(Result.TemplateArgs, &CurMC->Rec,
812 &Result.MC->Rec)) {
813 Result.MC = nullptr; // Error parsing value list.
814 return Result;
817 Result.RefRange.End = Lex.getLoc();
819 return Result;
822 /// ParseSliceElement - Parse subscript or range
824 /// SliceElement ::= Value<list<int>>
825 /// SliceElement ::= Value<int>
826 /// SliceElement ::= Value<int> '...' Value<int>
827 /// SliceElement ::= Value<int> '-' Value<int> (deprecated)
828 /// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
830 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
832 TypedInit *TGParser::ParseSliceElement(Record *CurRec) {
833 auto LHSLoc = Lex.getLoc();
834 auto *CurVal = ParseValue(CurRec);
835 if (!CurVal)
836 return nullptr;
837 auto *LHS = cast<TypedInit>(CurVal);
839 TypedInit *RHS = nullptr;
840 switch (Lex.getCode()) {
841 case tgtok::dotdotdot:
842 case tgtok::minus: { // Deprecated
843 Lex.Lex(); // eat
844 auto RHSLoc = Lex.getLoc();
845 CurVal = ParseValue(CurRec);
846 if (!CurVal)
847 return nullptr;
848 RHS = cast<TypedInit>(CurVal);
849 if (!isa<IntRecTy>(RHS->getType())) {
850 Error(RHSLoc,
851 "expected int...int, got " + Twine(RHS->getType()->getAsString()));
852 return nullptr;
854 break;
856 case tgtok::IntVal: { // Deprecated "-num"
857 auto i = -Lex.getCurIntVal();
858 if (i < 0) {
859 TokError("invalid range, cannot be negative");
860 return nullptr;
862 RHS = IntInit::get(Records, i);
863 Lex.Lex(); // eat IntVal
864 break;
866 default: // Single value (IntRecTy or ListRecTy)
867 return LHS;
870 assert(RHS);
871 assert(isa<IntRecTy>(RHS->getType()));
873 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
874 if (!isa<IntRecTy>(LHS->getType())) {
875 Error(LHSLoc,
876 "expected int...int, got " + Twine(LHS->getType()->getAsString()));
877 return nullptr;
880 return cast<TypedInit>(BinOpInit::get(BinOpInit::RANGEC, LHS, RHS,
881 IntRecTy::get(Records)->getListTy())
882 ->Fold(CurRec));
885 /// ParseSliceElements - Parse subscripts in square brackets.
887 /// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
889 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
891 /// Returns ListRecTy by defaut.
892 /// Returns IntRecTy if;
893 /// - Single=true
894 /// - SliceElements is Value<int> w/o trailing comma
896 TypedInit *TGParser::ParseSliceElements(Record *CurRec, bool Single) {
897 TypedInit *CurVal;
898 SmallVector<Init *, 2> Elems; // int
899 SmallVector<TypedInit *, 2> Slices; // list<int>
901 auto FlushElems = [&] {
902 if (!Elems.empty()) {
903 Slices.push_back(ListInit::get(Elems, IntRecTy::get(Records)));
904 Elems.clear();
908 do {
909 auto LHSLoc = Lex.getLoc();
910 CurVal = ParseSliceElement(CurRec);
911 if (!CurVal)
912 return nullptr;
913 auto *CurValTy = CurVal->getType();
915 if (auto *ListValTy = dyn_cast<ListRecTy>(CurValTy)) {
916 if (!isa<IntRecTy>(ListValTy->getElementType())) {
917 Error(LHSLoc,
918 "expected list<int>, got " + Twine(ListValTy->getAsString()));
919 return nullptr;
922 FlushElems();
923 Slices.push_back(CurVal);
924 Single = false;
925 CurVal = nullptr;
926 } else if (!isa<IntRecTy>(CurValTy)) {
927 Error(LHSLoc,
928 "unhandled type " + Twine(CurValTy->getAsString()) + " in range");
929 return nullptr;
932 if (Lex.getCode() != tgtok::comma)
933 break;
935 Lex.Lex(); // eat comma
937 // `[i,]` is not LISTELEM but LISTSLICE
938 Single = false;
939 if (CurVal)
940 Elems.push_back(CurVal);
941 CurVal = nullptr;
942 } while (Lex.getCode() != tgtok::r_square);
944 if (CurVal) {
945 // LISTELEM
946 if (Single)
947 return CurVal;
949 Elems.push_back(CurVal);
952 FlushElems();
954 // Concatenate lists in Slices
955 TypedInit *Result = nullptr;
956 for (auto *Slice : Slices) {
957 Result = (Result ? cast<TypedInit>(BinOpInit::getListConcat(Result, Slice))
958 : Slice);
961 return Result;
964 /// ParseRangePiece - Parse a bit/value range.
965 /// RangePiece ::= INTVAL
966 /// RangePiece ::= INTVAL '...' INTVAL
967 /// RangePiece ::= INTVAL '-' INTVAL
968 /// RangePiece ::= INTVAL INTVAL
969 // The last two forms are deprecated.
970 bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
971 TypedInit *FirstItem) {
972 Init *CurVal = FirstItem;
973 if (!CurVal)
974 CurVal = ParseValue(nullptr);
976 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
977 if (!II)
978 return TokError("expected integer or bitrange");
980 int64_t Start = II->getValue();
981 int64_t End;
983 if (Start < 0)
984 return TokError("invalid range, cannot be negative");
986 switch (Lex.getCode()) {
987 default:
988 Ranges.push_back(Start);
989 return false;
991 case tgtok::dotdotdot:
992 case tgtok::minus: {
993 Lex.Lex(); // eat
995 Init *I_End = ParseValue(nullptr);
996 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
997 if (!II_End) {
998 TokError("expected integer value as end of range");
999 return true;
1002 End = II_End->getValue();
1003 break;
1005 case tgtok::IntVal: {
1006 End = -Lex.getCurIntVal();
1007 Lex.Lex();
1008 break;
1011 if (End < 0)
1012 return TokError("invalid range, cannot be negative");
1014 // Add to the range.
1015 if (Start < End)
1016 for (; Start <= End; ++Start)
1017 Ranges.push_back(Start);
1018 else
1019 for (; Start >= End; --Start)
1020 Ranges.push_back(Start);
1021 return false;
1024 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
1026 /// RangeList ::= RangePiece (',' RangePiece)*
1028 void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
1029 // Parse the first piece.
1030 if (ParseRangePiece(Result)) {
1031 Result.clear();
1032 return;
1034 while (consume(tgtok::comma))
1035 // Parse the next range piece.
1036 if (ParseRangePiece(Result)) {
1037 Result.clear();
1038 return;
1042 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
1043 /// OptionalRangeList ::= '<' RangeList '>'
1044 /// OptionalRangeList ::= /*empty*/
1045 bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
1046 SMLoc StartLoc = Lex.getLoc();
1047 if (!consume(tgtok::less))
1048 return false;
1050 // Parse the range list.
1051 ParseRangeList(Ranges);
1052 if (Ranges.empty()) return true;
1054 if (!consume(tgtok::greater)) {
1055 TokError("expected '>' at end of range list");
1056 return Error(StartLoc, "to match this '<'");
1058 return false;
1061 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
1062 /// OptionalBitList ::= '{' RangeList '}'
1063 /// OptionalBitList ::= /*empty*/
1064 bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
1065 SMLoc StartLoc = Lex.getLoc();
1066 if (!consume(tgtok::l_brace))
1067 return false;
1069 // Parse the range list.
1070 ParseRangeList(Ranges);
1071 if (Ranges.empty()) return true;
1073 if (!consume(tgtok::r_brace)) {
1074 TokError("expected '}' at end of bit list");
1075 return Error(StartLoc, "to match this '{'");
1077 return false;
1080 /// ParseType - Parse and return a tblgen type. This returns null on error.
1082 /// Type ::= STRING // string type
1083 /// Type ::= CODE // code type
1084 /// Type ::= BIT // bit type
1085 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
1086 /// Type ::= INT // int type
1087 /// Type ::= LIST '<' Type '>' // list<x> type
1088 /// Type ::= DAG // dag type
1089 /// Type ::= ClassID // Record Type
1091 RecTy *TGParser::ParseType() {
1092 switch (Lex.getCode()) {
1093 default: TokError("Unknown token when expecting a type"); return nullptr;
1094 case tgtok::String:
1095 case tgtok::Code:
1096 Lex.Lex();
1097 return StringRecTy::get(Records);
1098 case tgtok::Bit:
1099 Lex.Lex();
1100 return BitRecTy::get(Records);
1101 case tgtok::Int:
1102 Lex.Lex();
1103 return IntRecTy::get(Records);
1104 case tgtok::Dag:
1105 Lex.Lex();
1106 return DagRecTy::get(Records);
1107 case tgtok::Id:
1108 if (Record *R = ParseClassID())
1109 return RecordRecTy::get(R);
1110 TokError("unknown class name");
1111 return nullptr;
1112 case tgtok::Bits: {
1113 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1114 TokError("expected '<' after bits type");
1115 return nullptr;
1117 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
1118 TokError("expected integer in bits<n> type");
1119 return nullptr;
1121 uint64_t Val = Lex.getCurIntVal();
1122 if (Lex.Lex() != tgtok::greater) { // Eat count.
1123 TokError("expected '>' at end of bits<n> type");
1124 return nullptr;
1126 Lex.Lex(); // Eat '>'
1127 return BitsRecTy::get(Records, Val);
1129 case tgtok::List: {
1130 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
1131 TokError("expected '<' after list type");
1132 return nullptr;
1134 Lex.Lex(); // Eat '<'
1135 RecTy *SubType = ParseType();
1136 if (!SubType) return nullptr;
1138 if (!consume(tgtok::greater)) {
1139 TokError("expected '>' at end of list<ty> type");
1140 return nullptr;
1142 return ListRecTy::get(SubType);
1147 /// ParseIDValue
1148 Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMRange NameLoc,
1149 IDParseMode Mode) {
1150 if (Init *I = CurScope->getVar(Records, CurMultiClass, Name, NameLoc,
1151 TrackReferenceLocs))
1152 return I;
1154 if (Mode == ParseNameMode)
1155 return Name;
1157 if (Init *I = Records.getGlobal(Name->getValue())) {
1158 // Add a reference to the global if it's a record.
1159 if (TrackReferenceLocs) {
1160 if (auto *Def = dyn_cast<DefInit>(I))
1161 Def->getDef()->appendReferenceLoc(NameLoc);
1163 return I;
1166 // Allow self-references of concrete defs, but delay the lookup so that we
1167 // get the correct type.
1168 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
1169 CurRec->getNameInit() == Name)
1170 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
1172 Error(NameLoc.Start, "Variable not defined: '" + Name->getValue() + "'");
1173 return nullptr;
1176 /// ParseOperation - Parse an operator. This returns null on error.
1178 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1180 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
1181 switch (Lex.getCode()) {
1182 default:
1183 TokError("unknown bang operator");
1184 return nullptr;
1185 case tgtok::XNOT:
1186 case tgtok::XToLower:
1187 case tgtok::XToUpper:
1188 case tgtok::XLOG2:
1189 case tgtok::XHead:
1190 case tgtok::XTail:
1191 case tgtok::XSize:
1192 case tgtok::XEmpty:
1193 case tgtok::XCast:
1194 case tgtok::XRepr:
1195 case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
1196 UnOpInit::UnaryOp Code;
1197 RecTy *Type = nullptr;
1199 switch (Lex.getCode()) {
1200 default: llvm_unreachable("Unhandled code!");
1201 case tgtok::XCast:
1202 Lex.Lex(); // eat the operation
1203 Code = UnOpInit::CAST;
1205 Type = ParseOperatorType();
1207 if (!Type) {
1208 TokError("did not get type for unary operator");
1209 return nullptr;
1212 break;
1213 case tgtok::XRepr:
1214 Lex.Lex(); // eat the operation
1215 Code = UnOpInit::REPR;
1216 Type = StringRecTy::get(Records);
1217 break;
1218 case tgtok::XToLower:
1219 Lex.Lex(); // eat the operation
1220 Code = UnOpInit::TOLOWER;
1221 Type = StringRecTy::get(Records);
1222 break;
1223 case tgtok::XToUpper:
1224 Lex.Lex(); // eat the operation
1225 Code = UnOpInit::TOUPPER;
1226 Type = StringRecTy::get(Records);
1227 break;
1228 case tgtok::XNOT:
1229 Lex.Lex(); // eat the operation
1230 Code = UnOpInit::NOT;
1231 Type = IntRecTy::get(Records);
1232 break;
1233 case tgtok::XLOG2:
1234 Lex.Lex(); // eat the operation
1235 Code = UnOpInit::LOG2;
1236 Type = IntRecTy::get(Records);
1237 break;
1238 case tgtok::XHead:
1239 Lex.Lex(); // eat the operation
1240 Code = UnOpInit::HEAD;
1241 break;
1242 case tgtok::XTail:
1243 Lex.Lex(); // eat the operation
1244 Code = UnOpInit::TAIL;
1245 break;
1246 case tgtok::XSize:
1247 Lex.Lex();
1248 Code = UnOpInit::SIZE;
1249 Type = IntRecTy::get(Records);
1250 break;
1251 case tgtok::XEmpty:
1252 Lex.Lex(); // eat the operation
1253 Code = UnOpInit::EMPTY;
1254 Type = IntRecTy::get(Records);
1255 break;
1256 case tgtok::XGetDagOp:
1257 Lex.Lex(); // eat the operation
1258 if (Lex.getCode() == tgtok::less) {
1259 // Parse an optional type suffix, so that you can say
1260 // !getdagop<BaseClass>(someDag) as a shorthand for
1261 // !cast<BaseClass>(!getdagop(someDag)).
1262 Type = ParseOperatorType();
1264 if (!Type) {
1265 TokError("did not get type for unary operator");
1266 return nullptr;
1269 if (!isa<RecordRecTy>(Type)) {
1270 TokError("type for !getdagop must be a record type");
1271 // but keep parsing, to consume the operand
1273 } else {
1274 Type = RecordRecTy::get(Records, {});
1276 Code = UnOpInit::GETDAGOP;
1277 break;
1279 if (!consume(tgtok::l_paren)) {
1280 TokError("expected '(' after unary operator");
1281 return nullptr;
1284 Init *LHS = ParseValue(CurRec);
1285 if (!LHS) return nullptr;
1287 if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
1288 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1289 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1290 DagInit *LHSd = dyn_cast<DagInit>(LHS);
1291 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1292 if (!LHSl && !LHSs && !LHSd && !LHSt) {
1293 TokError("expected string, list, or dag type argument in unary operator");
1294 return nullptr;
1296 if (LHSt) {
1297 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1298 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
1299 DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
1300 if (!LType && !SType && !DType) {
1301 TokError("expected string, list, or dag type argument in unary operator");
1302 return nullptr;
1307 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1308 ListInit *LHSl = dyn_cast<ListInit>(LHS);
1309 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1310 if (!LHSl && !LHSt) {
1311 TokError("expected list type argument in unary operator");
1312 return nullptr;
1314 if (LHSt) {
1315 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1316 if (!LType) {
1317 TokError("expected list type argument in unary operator");
1318 return nullptr;
1322 if (LHSl && LHSl->empty()) {
1323 TokError("empty list argument in unary operator");
1324 return nullptr;
1326 if (LHSl) {
1327 Init *Item = LHSl->getElement(0);
1328 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1329 if (!Itemt) {
1330 TokError("untyped list element in unary operator");
1331 return nullptr;
1333 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1334 : ListRecTy::get(Itemt->getType());
1335 } else {
1336 assert(LHSt && "expected list type argument in unary operator");
1337 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1338 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1342 if (!consume(tgtok::r_paren)) {
1343 TokError("expected ')' in unary operator");
1344 return nullptr;
1346 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1349 case tgtok::XIsA: {
1350 // Value ::= !isa '<' Type '>' '(' Value ')'
1351 Lex.Lex(); // eat the operation
1353 RecTy *Type = ParseOperatorType();
1354 if (!Type)
1355 return nullptr;
1357 if (!consume(tgtok::l_paren)) {
1358 TokError("expected '(' after type of !isa");
1359 return nullptr;
1362 Init *LHS = ParseValue(CurRec);
1363 if (!LHS)
1364 return nullptr;
1366 if (!consume(tgtok::r_paren)) {
1367 TokError("expected ')' in !isa");
1368 return nullptr;
1371 return (IsAOpInit::get(Type, LHS))->Fold();
1374 case tgtok::XExists: {
1375 // Value ::= !exists '<' Type '>' '(' Value ')'
1376 Lex.Lex(); // eat the operation
1378 RecTy *Type = ParseOperatorType();
1379 if (!Type)
1380 return nullptr;
1382 if (!consume(tgtok::l_paren)) {
1383 TokError("expected '(' after type of !exists");
1384 return nullptr;
1387 SMLoc ExprLoc = Lex.getLoc();
1388 Init *Expr = ParseValue(CurRec);
1389 if (!Expr)
1390 return nullptr;
1392 TypedInit *ExprType = dyn_cast<TypedInit>(Expr);
1393 if (!ExprType) {
1394 Error(ExprLoc, "expected string type argument in !exists operator");
1395 return nullptr;
1398 RecordRecTy *RecType = dyn_cast<RecordRecTy>(ExprType->getType());
1399 if (RecType) {
1400 Error(ExprLoc,
1401 "expected string type argument in !exists operator, please "
1402 "use !isa instead");
1403 return nullptr;
1406 StringRecTy *SType = dyn_cast<StringRecTy>(ExprType->getType());
1407 if (!SType) {
1408 Error(ExprLoc, "expected string type argument in !exists operator");
1409 return nullptr;
1412 if (!consume(tgtok::r_paren)) {
1413 TokError("expected ')' in !exists");
1414 return nullptr;
1417 return (ExistsOpInit::get(Type, Expr))->Fold(CurRec);
1420 case tgtok::XConcat:
1421 case tgtok::XADD:
1422 case tgtok::XSUB:
1423 case tgtok::XMUL:
1424 case tgtok::XDIV:
1425 case tgtok::XAND:
1426 case tgtok::XOR:
1427 case tgtok::XXOR:
1428 case tgtok::XSRA:
1429 case tgtok::XSRL:
1430 case tgtok::XSHL:
1431 case tgtok::XEq:
1432 case tgtok::XNe:
1433 case tgtok::XLe:
1434 case tgtok::XLt:
1435 case tgtok::XGe:
1436 case tgtok::XGt:
1437 case tgtok::XListConcat:
1438 case tgtok::XListSplat:
1439 case tgtok::XListRemove:
1440 case tgtok::XStrConcat:
1441 case tgtok::XInterleave:
1442 case tgtok::XGetDagArg:
1443 case tgtok::XGetDagName:
1444 case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
1445 tgtok::TokKind OpTok = Lex.getCode();
1446 SMLoc OpLoc = Lex.getLoc();
1447 Lex.Lex(); // eat the operation
1449 BinOpInit::BinaryOp Code;
1450 switch (OpTok) {
1451 default: llvm_unreachable("Unhandled code!");
1452 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1453 case tgtok::XADD: Code = BinOpInit::ADD; break;
1454 case tgtok::XSUB: Code = BinOpInit::SUB; break;
1455 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1456 case tgtok::XDIV: Code = BinOpInit::DIV; break;
1457 case tgtok::XAND: Code = BinOpInit::AND; break;
1458 case tgtok::XOR: Code = BinOpInit::OR; break;
1459 case tgtok::XXOR: Code = BinOpInit::XOR; break;
1460 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1461 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1462 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1463 case tgtok::XEq: Code = BinOpInit::EQ; break;
1464 case tgtok::XNe: Code = BinOpInit::NE; break;
1465 case tgtok::XLe: Code = BinOpInit::LE; break;
1466 case tgtok::XLt: Code = BinOpInit::LT; break;
1467 case tgtok::XGe: Code = BinOpInit::GE; break;
1468 case tgtok::XGt: Code = BinOpInit::GT; break;
1469 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1470 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1471 case tgtok::XListRemove:
1472 Code = BinOpInit::LISTREMOVE;
1473 break;
1474 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1475 case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
1476 case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
1477 case tgtok::XGetDagArg:
1478 Code = BinOpInit::GETDAGARG;
1479 break;
1480 case tgtok::XGetDagName:
1481 Code = BinOpInit::GETDAGNAME;
1482 break;
1485 RecTy *Type = nullptr;
1486 RecTy *ArgType = nullptr;
1487 switch (OpTok) {
1488 default:
1489 llvm_unreachable("Unhandled code!");
1490 case tgtok::XConcat:
1491 case tgtok::XSetDagOp:
1492 Type = DagRecTy::get(Records);
1493 ArgType = DagRecTy::get(Records);
1494 break;
1495 case tgtok::XGetDagArg:
1496 Type = ParseOperatorType();
1497 if (!Type) {
1498 TokError("did not get type for !getdagarg operator");
1499 return nullptr;
1501 ArgType = DagRecTy::get(Records);
1502 break;
1503 case tgtok::XGetDagName:
1504 Type = StringRecTy::get(Records);
1505 ArgType = DagRecTy::get(Records);
1506 break;
1507 case tgtok::XAND:
1508 case tgtok::XOR:
1509 case tgtok::XXOR:
1510 case tgtok::XSRA:
1511 case tgtok::XSRL:
1512 case tgtok::XSHL:
1513 case tgtok::XADD:
1514 case tgtok::XSUB:
1515 case tgtok::XMUL:
1516 case tgtok::XDIV:
1517 Type = IntRecTy::get(Records);
1518 ArgType = IntRecTy::get(Records);
1519 break;
1520 case tgtok::XEq:
1521 case tgtok::XNe:
1522 case tgtok::XLe:
1523 case tgtok::XLt:
1524 case tgtok::XGe:
1525 case tgtok::XGt:
1526 Type = BitRecTy::get(Records);
1527 // ArgType for the comparison operators is not yet known.
1528 break;
1529 case tgtok::XListConcat:
1530 // We don't know the list type until we parse the first argument.
1531 ArgType = ItemType;
1532 break;
1533 case tgtok::XListSplat:
1534 // Can't do any typechecking until we parse the first argument.
1535 break;
1536 case tgtok::XListRemove:
1537 // We don't know the list type until we parse the first argument.
1538 ArgType = ItemType;
1539 break;
1540 case tgtok::XStrConcat:
1541 Type = StringRecTy::get(Records);
1542 ArgType = StringRecTy::get(Records);
1543 break;
1544 case tgtok::XInterleave:
1545 Type = StringRecTy::get(Records);
1546 // The first argument type is not yet known.
1549 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1550 Error(OpLoc, Twine("expected value of type '") +
1551 ItemType->getAsString() + "', got '" +
1552 Type->getAsString() + "'");
1553 return nullptr;
1556 if (!consume(tgtok::l_paren)) {
1557 TokError("expected '(' after binary operator");
1558 return nullptr;
1561 SmallVector<Init*, 2> InitList;
1563 // Note that this loop consumes an arbitrary number of arguments.
1564 // The actual count is checked later.
1565 for (;;) {
1566 SMLoc InitLoc = Lex.getLoc();
1567 InitList.push_back(ParseValue(CurRec, ArgType));
1568 if (!InitList.back()) return nullptr;
1570 TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
1571 if (!InitListBack) {
1572 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1573 InitList.back()->getAsString() + "'"));
1574 return nullptr;
1576 RecTy *ListType = InitListBack->getType();
1578 if (!ArgType) {
1579 // Argument type must be determined from the argument itself.
1580 ArgType = ListType;
1582 switch (Code) {
1583 case BinOpInit::LISTCONCAT:
1584 if (!isa<ListRecTy>(ArgType)) {
1585 Error(InitLoc, Twine("expected a list, got value of type '") +
1586 ArgType->getAsString() + "'");
1587 return nullptr;
1589 break;
1590 case BinOpInit::LISTSPLAT:
1591 if (ItemType && InitList.size() == 1) {
1592 if (!isa<ListRecTy>(ItemType)) {
1593 Error(OpLoc,
1594 Twine("expected output type to be a list, got type '") +
1595 ItemType->getAsString() + "'");
1596 return nullptr;
1598 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1599 Error(OpLoc, Twine("expected first arg type to be '") +
1600 ArgType->getAsString() +
1601 "', got value of type '" +
1602 cast<ListRecTy>(ItemType)
1603 ->getElementType()
1604 ->getAsString() +
1605 "'");
1606 return nullptr;
1609 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1610 Error(InitLoc, Twine("expected second parameter to be an int, got "
1611 "value of type '") +
1612 ArgType->getAsString() + "'");
1613 return nullptr;
1615 ArgType = nullptr; // Broken invariant: types not identical.
1616 break;
1617 case BinOpInit::LISTREMOVE:
1618 if (!isa<ListRecTy>(ArgType)) {
1619 Error(InitLoc, Twine("expected a list, got value of type '") +
1620 ArgType->getAsString() + "'");
1621 return nullptr;
1623 break;
1624 case BinOpInit::EQ:
1625 case BinOpInit::NE:
1626 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1627 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records)) &&
1628 !ArgType->typeIsConvertibleTo(RecordRecTy::get(Records, {}))) {
1629 Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
1630 "got value of type '") + ArgType->getAsString() +
1631 "'");
1632 return nullptr;
1634 break;
1635 case BinOpInit::GETDAGARG: // The 2nd argument of !getdagarg could be
1636 // index or name.
1637 case BinOpInit::LE:
1638 case BinOpInit::LT:
1639 case BinOpInit::GE:
1640 case BinOpInit::GT:
1641 if (!ArgType->typeIsConvertibleTo(IntRecTy::get(Records)) &&
1642 !ArgType->typeIsConvertibleTo(StringRecTy::get(Records))) {
1643 Error(InitLoc, Twine("expected bit, bits, int, or string; "
1644 "got value of type '") + ArgType->getAsString() +
1645 "'");
1646 return nullptr;
1648 break;
1649 case BinOpInit::INTERLEAVE:
1650 switch (InitList.size()) {
1651 case 1: // First argument must be a list of strings or integers.
1652 if (ArgType != StringRecTy::get(Records)->getListTy() &&
1653 !ArgType->typeIsConvertibleTo(
1654 IntRecTy::get(Records)->getListTy())) {
1655 Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
1656 "got value of type '") +
1657 ArgType->getAsString() + "'");
1658 return nullptr;
1660 break;
1661 case 2: // Second argument must be a string.
1662 if (!isa<StringRecTy>(ArgType)) {
1663 Error(InitLoc, Twine("expected second argument to be a string, "
1664 "got value of type '") +
1665 ArgType->getAsString() + "'");
1666 return nullptr;
1668 break;
1669 default: ;
1671 ArgType = nullptr; // Broken invariant: types not identical.
1672 break;
1673 default: llvm_unreachable("other ops have fixed argument types");
1676 } else {
1677 // Desired argument type is a known and in ArgType.
1678 RecTy *Resolved = resolveTypes(ArgType, ListType);
1679 if (!Resolved) {
1680 Error(InitLoc, Twine("expected value of type '") +
1681 ArgType->getAsString() + "', got '" +
1682 ListType->getAsString() + "'");
1683 return nullptr;
1685 if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
1686 Code != BinOpInit::AND && Code != BinOpInit::OR &&
1687 Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
1688 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1689 Code != BinOpInit::MUL && Code != BinOpInit::DIV)
1690 ArgType = Resolved;
1693 // Deal with BinOps whose arguments have different types, by
1694 // rewriting ArgType in between them.
1695 switch (Code) {
1696 case BinOpInit::SETDAGOP:
1697 // After parsing the first dag argument, switch to expecting
1698 // a record, with no restriction on its superclasses.
1699 ArgType = RecordRecTy::get(Records, {});
1700 break;
1701 case BinOpInit::GETDAGARG:
1702 // After parsing the first dag argument, expect an index integer or a
1703 // name string.
1704 ArgType = nullptr;
1705 break;
1706 case BinOpInit::GETDAGNAME:
1707 // After parsing the first dag argument, expect an index integer.
1708 ArgType = IntRecTy::get(Records);
1709 break;
1710 default:
1711 break;
1714 if (!consume(tgtok::comma))
1715 break;
1718 if (!consume(tgtok::r_paren)) {
1719 TokError("expected ')' in operator");
1720 return nullptr;
1723 // listconcat returns a list with type of the argument.
1724 if (Code == BinOpInit::LISTCONCAT)
1725 Type = ArgType;
1726 // listsplat returns a list of type of the *first* argument.
1727 if (Code == BinOpInit::LISTSPLAT)
1728 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1729 // listremove returns a list with type of the argument.
1730 if (Code == BinOpInit::LISTREMOVE)
1731 Type = ArgType;
1733 // We allow multiple operands to associative operators like !strconcat as
1734 // shorthand for nesting them.
1735 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1736 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1737 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1738 Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
1739 while (InitList.size() > 2) {
1740 Init *RHS = InitList.pop_back_val();
1741 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1742 InitList.back() = RHS;
1746 if (InitList.size() == 2)
1747 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1748 ->Fold(CurRec);
1750 Error(OpLoc, "expected two operands to operator");
1751 return nullptr;
1754 case tgtok::XForEach:
1755 case tgtok::XFilter: {
1756 return ParseOperationForEachFilter(CurRec, ItemType);
1759 case tgtok::XRange: {
1760 SMLoc OpLoc = Lex.getLoc();
1761 Lex.Lex(); // eat the operation
1763 if (!consume(tgtok::l_paren)) {
1764 TokError("expected '(' after !range operator");
1765 return nullptr;
1768 SmallVector<Init *, 2> Args;
1769 bool FirstArgIsList = false;
1770 for (;;) {
1771 if (Args.size() >= 3) {
1772 TokError("expected at most three values of integer");
1773 return nullptr;
1776 SMLoc InitLoc = Lex.getLoc();
1777 Args.push_back(ParseValue(CurRec));
1778 if (!Args.back())
1779 return nullptr;
1781 TypedInit *ArgBack = dyn_cast<TypedInit>(Args.back());
1782 if (!ArgBack) {
1783 Error(OpLoc, Twine("expected value to be a typed value, got '" +
1784 Args.back()->getAsString() + "'"));
1785 return nullptr;
1788 RecTy *ArgBackType = ArgBack->getType();
1789 if (!FirstArgIsList || Args.size() == 1) {
1790 if (Args.size() == 1 && isa<ListRecTy>(ArgBackType)) {
1791 FirstArgIsList = true; // Detect error if 2nd arg were present.
1792 } else if (isa<IntRecTy>(ArgBackType)) {
1793 // Assume 2nd arg should be IntRecTy
1794 } else {
1795 if (Args.size() != 1)
1796 Error(InitLoc, Twine("expected value of type 'int', got '" +
1797 ArgBackType->getAsString() + "'"));
1798 else
1799 Error(InitLoc, Twine("expected list or int, got value of type '") +
1800 ArgBackType->getAsString() + "'");
1801 return nullptr;
1803 } else {
1804 // Don't come here unless 1st arg is ListRecTy.
1805 assert(isa<ListRecTy>(cast<TypedInit>(Args[0])->getType()));
1806 Error(InitLoc, Twine("expected one list, got extra value of type '") +
1807 ArgBackType->getAsString() + "'");
1808 return nullptr;
1810 if (!consume(tgtok::comma))
1811 break;
1814 if (!consume(tgtok::r_paren)) {
1815 TokError("expected ')' in operator");
1816 return nullptr;
1819 Init *LHS, *MHS, *RHS;
1820 auto ArgCount = Args.size();
1821 assert(ArgCount >= 1);
1822 auto *Arg0 = cast<TypedInit>(Args[0]);
1823 auto *Arg0Ty = Arg0->getType();
1824 if (ArgCount == 1) {
1825 if (isa<ListRecTy>(Arg0Ty)) {
1826 // (0, !size(arg), 1)
1827 LHS = IntInit::get(Records, 0);
1828 MHS = UnOpInit::get(UnOpInit::SIZE, Arg0, IntRecTy::get(Records))
1829 ->Fold(CurRec);
1830 RHS = IntInit::get(Records, 1);
1831 } else {
1832 assert(isa<IntRecTy>(Arg0Ty));
1833 // (0, arg, 1)
1834 LHS = IntInit::get(Records, 0);
1835 MHS = Arg0;
1836 RHS = IntInit::get(Records, 1);
1838 } else {
1839 assert(isa<IntRecTy>(Arg0Ty));
1840 auto *Arg1 = cast<TypedInit>(Args[1]);
1841 assert(isa<IntRecTy>(Arg1->getType()));
1842 LHS = Arg0;
1843 MHS = Arg1;
1844 if (ArgCount == 3) {
1845 // (start, end, step)
1846 auto *Arg2 = cast<TypedInit>(Args[2]);
1847 assert(isa<IntRecTy>(Arg2->getType()));
1848 RHS = Arg2;
1849 } else
1850 // (start, end, 1)
1851 RHS = IntInit::get(Records, 1);
1853 return TernOpInit::get(TernOpInit::RANGE, LHS, MHS, RHS,
1854 IntRecTy::get(Records)->getListTy())
1855 ->Fold(CurRec);
1858 case tgtok::XSetDagArg:
1859 case tgtok::XSetDagName:
1860 case tgtok::XDag:
1861 case tgtok::XIf:
1862 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1863 TernOpInit::TernaryOp Code;
1864 RecTy *Type = nullptr;
1866 tgtok::TokKind LexCode = Lex.getCode();
1867 Lex.Lex(); // eat the operation
1868 switch (LexCode) {
1869 default: llvm_unreachable("Unhandled code!");
1870 case tgtok::XDag:
1871 Code = TernOpInit::DAG;
1872 Type = DagRecTy::get(Records);
1873 ItemType = nullptr;
1874 break;
1875 case tgtok::XIf:
1876 Code = TernOpInit::IF;
1877 break;
1878 case tgtok::XSubst:
1879 Code = TernOpInit::SUBST;
1880 break;
1881 case tgtok::XSetDagArg:
1882 Code = TernOpInit::SETDAGARG;
1883 Type = DagRecTy::get(Records);
1884 ItemType = nullptr;
1885 break;
1886 case tgtok::XSetDagName:
1887 Code = TernOpInit::SETDAGNAME;
1888 Type = DagRecTy::get(Records);
1889 ItemType = nullptr;
1890 break;
1892 if (!consume(tgtok::l_paren)) {
1893 TokError("expected '(' after ternary operator");
1894 return nullptr;
1897 Init *LHS = ParseValue(CurRec);
1898 if (!LHS) return nullptr;
1900 if (!consume(tgtok::comma)) {
1901 TokError("expected ',' in ternary operator");
1902 return nullptr;
1905 SMLoc MHSLoc = Lex.getLoc();
1906 Init *MHS = ParseValue(CurRec, ItemType);
1907 if (!MHS)
1908 return nullptr;
1910 if (!consume(tgtok::comma)) {
1911 TokError("expected ',' in ternary operator");
1912 return nullptr;
1915 SMLoc RHSLoc = Lex.getLoc();
1916 Init *RHS = ParseValue(CurRec, ItemType);
1917 if (!RHS)
1918 return nullptr;
1920 if (!consume(tgtok::r_paren)) {
1921 TokError("expected ')' in binary operator");
1922 return nullptr;
1925 switch (LexCode) {
1926 default: llvm_unreachable("Unhandled code!");
1927 case tgtok::XDag: {
1928 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1929 if (!MHSt && !isa<UnsetInit>(MHS)) {
1930 Error(MHSLoc, "could not determine type of the child list in !dag");
1931 return nullptr;
1933 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1934 Error(MHSLoc, Twine("expected list of children, got type '") +
1935 MHSt->getType()->getAsString() + "'");
1936 return nullptr;
1939 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1940 if (!RHSt && !isa<UnsetInit>(RHS)) {
1941 Error(RHSLoc, "could not determine type of the name list in !dag");
1942 return nullptr;
1944 if (RHSt && StringRecTy::get(Records)->getListTy() != RHSt->getType()) {
1945 Error(RHSLoc, Twine("expected list<string>, got type '") +
1946 RHSt->getType()->getAsString() + "'");
1947 return nullptr;
1950 if (!MHSt && !RHSt) {
1951 Error(MHSLoc,
1952 "cannot have both unset children and unset names in !dag");
1953 return nullptr;
1955 break;
1957 case tgtok::XIf: {
1958 RecTy *MHSTy = nullptr;
1959 RecTy *RHSTy = nullptr;
1961 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1962 MHSTy = MHSt->getType();
1963 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1964 MHSTy = BitsRecTy::get(Records, MHSbits->getNumBits());
1965 if (isa<BitInit>(MHS))
1966 MHSTy = BitRecTy::get(Records);
1968 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1969 RHSTy = RHSt->getType();
1970 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1971 RHSTy = BitsRecTy::get(Records, RHSbits->getNumBits());
1972 if (isa<BitInit>(RHS))
1973 RHSTy = BitRecTy::get(Records);
1975 // For UnsetInit, it's typed from the other hand.
1976 if (isa<UnsetInit>(MHS))
1977 MHSTy = RHSTy;
1978 if (isa<UnsetInit>(RHS))
1979 RHSTy = MHSTy;
1981 if (!MHSTy || !RHSTy) {
1982 TokError("could not get type for !if");
1983 return nullptr;
1986 Type = resolveTypes(MHSTy, RHSTy);
1987 if (!Type) {
1988 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1989 "' and '" + RHSTy->getAsString() + "' for !if");
1990 return nullptr;
1992 break;
1994 case tgtok::XSubst: {
1995 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1996 if (!RHSt) {
1997 TokError("could not get type for !subst");
1998 return nullptr;
2000 Type = RHSt->getType();
2001 break;
2003 case tgtok::XSetDagArg: {
2004 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2005 if (!MHSt || !isa<IntRecTy, StringRecTy>(MHSt->getType())) {
2006 Error(MHSLoc, Twine("expected integer index or string name, got ") +
2007 (MHSt ? ("type '" + MHSt->getType()->getAsString())
2008 : ("'" + MHS->getAsString())) +
2009 "'");
2010 return nullptr;
2012 break;
2014 case tgtok::XSetDagName: {
2015 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2016 if (!MHSt || !isa<IntRecTy, StringRecTy>(MHSt->getType())) {
2017 Error(MHSLoc, Twine("expected integer index or string name, got ") +
2018 (MHSt ? ("type '" + MHSt->getType()->getAsString())
2019 : ("'" + MHS->getAsString())) +
2020 "'");
2021 return nullptr;
2023 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2024 // The name could be a string or unset.
2025 if (RHSt && !isa<StringRecTy>(RHSt->getType())) {
2026 Error(RHSLoc, Twine("expected string or unset name, got type '") +
2027 RHSt->getType()->getAsString() + "'");
2028 return nullptr;
2030 break;
2033 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2036 case tgtok::XSubstr:
2037 return ParseOperationSubstr(CurRec, ItemType);
2039 case tgtok::XFind:
2040 return ParseOperationFind(CurRec, ItemType);
2042 case tgtok::XCond:
2043 return ParseOperationCond(CurRec, ItemType);
2045 case tgtok::XFoldl: {
2046 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
2047 Lex.Lex(); // eat the operation
2048 if (!consume(tgtok::l_paren)) {
2049 TokError("expected '(' after !foldl");
2050 return nullptr;
2053 Init *StartUntyped = ParseValue(CurRec);
2054 if (!StartUntyped)
2055 return nullptr;
2057 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
2058 if (!Start) {
2059 TokError(Twine("could not get type of !foldl start: '") +
2060 StartUntyped->getAsString() + "'");
2061 return nullptr;
2064 if (!consume(tgtok::comma)) {
2065 TokError("expected ',' in !foldl");
2066 return nullptr;
2069 Init *ListUntyped = ParseValue(CurRec);
2070 if (!ListUntyped)
2071 return nullptr;
2073 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
2074 if (!List) {
2075 TokError(Twine("could not get type of !foldl list: '") +
2076 ListUntyped->getAsString() + "'");
2077 return nullptr;
2080 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
2081 if (!ListType) {
2082 TokError(Twine("!foldl list must be a list, but is of type '") +
2083 List->getType()->getAsString());
2084 return nullptr;
2087 if (Lex.getCode() != tgtok::comma) {
2088 TokError("expected ',' in !foldl");
2089 return nullptr;
2092 if (Lex.Lex() != tgtok::Id) { // eat the ','
2093 TokError("third argument of !foldl must be an identifier");
2094 return nullptr;
2097 Init *A = StringInit::get(Records, Lex.getCurStrVal());
2098 if (CurRec && CurRec->getValue(A)) {
2099 TokError((Twine("left !foldl variable '") + A->getAsString() +
2100 "' already defined")
2101 .str());
2102 return nullptr;
2105 if (Lex.Lex() != tgtok::comma) { // eat the id
2106 TokError("expected ',' in !foldl");
2107 return nullptr;
2110 if (Lex.Lex() != tgtok::Id) { // eat the ','
2111 TokError("fourth argument of !foldl must be an identifier");
2112 return nullptr;
2115 Init *B = StringInit::get(Records, Lex.getCurStrVal());
2116 if (CurRec && CurRec->getValue(B)) {
2117 TokError((Twine("right !foldl variable '") + B->getAsString() +
2118 "' already defined")
2119 .str());
2120 return nullptr;
2123 if (Lex.Lex() != tgtok::comma) { // eat the id
2124 TokError("expected ',' in !foldl");
2125 return nullptr;
2127 Lex.Lex(); // eat the ','
2129 // We need to create a temporary record to provide a scope for the
2130 // two variables.
2131 std::unique_ptr<Record> ParseRecTmp;
2132 Record *ParseRec = CurRec;
2133 if (!ParseRec) {
2134 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
2135 ParseRec = ParseRecTmp.get();
2138 TGVarScope *FoldScope = PushScope(ParseRec);
2139 ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
2140 ParseRec->addValue(
2141 RecordVal(B, ListType->getElementType(), RecordVal::FK_Normal));
2142 Init *ExprUntyped = ParseValue(ParseRec);
2143 ParseRec->removeValue(A);
2144 ParseRec->removeValue(B);
2145 PopScope(FoldScope);
2146 if (!ExprUntyped)
2147 return nullptr;
2149 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
2150 if (!Expr) {
2151 TokError("could not get type of !foldl expression");
2152 return nullptr;
2155 if (Expr->getType() != Start->getType()) {
2156 TokError(Twine("!foldl expression must be of same type as start (") +
2157 Start->getType()->getAsString() + "), but is of type " +
2158 Expr->getType()->getAsString());
2159 return nullptr;
2162 if (!consume(tgtok::r_paren)) {
2163 TokError("expected ')' in fold operator");
2164 return nullptr;
2167 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
2168 ->Fold(CurRec);
2173 /// ParseOperatorType - Parse a type for an operator. This returns
2174 /// null on error.
2176 /// OperatorType ::= '<' Type '>'
2178 RecTy *TGParser::ParseOperatorType() {
2179 RecTy *Type = nullptr;
2181 if (!consume(tgtok::less)) {
2182 TokError("expected type name for operator");
2183 return nullptr;
2186 if (Lex.getCode() == tgtok::Code)
2187 TokError("the 'code' type is not allowed in bang operators; use 'string'");
2189 Type = ParseType();
2191 if (!Type) {
2192 TokError("expected type name for operator");
2193 return nullptr;
2196 if (!consume(tgtok::greater)) {
2197 TokError("expected type name for operator");
2198 return nullptr;
2201 return Type;
2204 /// Parse the !substr operation. Return null on error.
2206 /// Substr ::= !substr(string, start-int [, length-int]) => string
2207 Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
2208 TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
2209 RecTy *Type = StringRecTy::get(Records);
2211 Lex.Lex(); // eat the operation
2213 if (!consume(tgtok::l_paren)) {
2214 TokError("expected '(' after !substr operator");
2215 return nullptr;
2218 Init *LHS = ParseValue(CurRec);
2219 if (!LHS)
2220 return nullptr;
2222 if (!consume(tgtok::comma)) {
2223 TokError("expected ',' in !substr operator");
2224 return nullptr;
2227 SMLoc MHSLoc = Lex.getLoc();
2228 Init *MHS = ParseValue(CurRec);
2229 if (!MHS)
2230 return nullptr;
2232 SMLoc RHSLoc = Lex.getLoc();
2233 Init *RHS;
2234 if (consume(tgtok::comma)) {
2235 RHSLoc = Lex.getLoc();
2236 RHS = ParseValue(CurRec);
2237 if (!RHS)
2238 return nullptr;
2239 } else {
2240 RHS = IntInit::get(Records, std::numeric_limits<int64_t>::max());
2243 if (!consume(tgtok::r_paren)) {
2244 TokError("expected ')' in !substr operator");
2245 return nullptr;
2248 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2249 Error(RHSLoc, Twine("expected value of type '") +
2250 ItemType->getAsString() + "', got '" +
2251 Type->getAsString() + "'");
2254 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
2255 if (!LHSt && !isa<UnsetInit>(LHS)) {
2256 TokError("could not determine type of the string in !substr");
2257 return nullptr;
2259 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2260 TokError(Twine("expected string, got type '") +
2261 LHSt->getType()->getAsString() + "'");
2262 return nullptr;
2265 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2266 if (!MHSt && !isa<UnsetInit>(MHS)) {
2267 TokError("could not determine type of the start position in !substr");
2268 return nullptr;
2270 if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
2271 Error(MHSLoc, Twine("expected int, got type '") +
2272 MHSt->getType()->getAsString() + "'");
2273 return nullptr;
2276 if (RHS) {
2277 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2278 if (!RHSt && !isa<UnsetInit>(RHS)) {
2279 TokError("could not determine type of the length in !substr");
2280 return nullptr;
2282 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2283 TokError(Twine("expected int, got type '") +
2284 RHSt->getType()->getAsString() + "'");
2285 return nullptr;
2289 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2292 /// Parse the !find operation. Return null on error.
2294 /// Substr ::= !find(string, string [, start-int]) => int
2295 Init *TGParser::ParseOperationFind(Record *CurRec, RecTy *ItemType) {
2296 TernOpInit::TernaryOp Code = TernOpInit::FIND;
2297 RecTy *Type = IntRecTy::get(Records);
2299 Lex.Lex(); // eat the operation
2301 if (!consume(tgtok::l_paren)) {
2302 TokError("expected '(' after !find operator");
2303 return nullptr;
2306 Init *LHS = ParseValue(CurRec);
2307 if (!LHS)
2308 return nullptr;
2310 if (!consume(tgtok::comma)) {
2311 TokError("expected ',' in !find operator");
2312 return nullptr;
2315 SMLoc MHSLoc = Lex.getLoc();
2316 Init *MHS = ParseValue(CurRec);
2317 if (!MHS)
2318 return nullptr;
2320 SMLoc RHSLoc = Lex.getLoc();
2321 Init *RHS;
2322 if (consume(tgtok::comma)) {
2323 RHSLoc = Lex.getLoc();
2324 RHS = ParseValue(CurRec);
2325 if (!RHS)
2326 return nullptr;
2327 } else {
2328 RHS = IntInit::get(Records, 0);
2331 if (!consume(tgtok::r_paren)) {
2332 TokError("expected ')' in !find operator");
2333 return nullptr;
2336 if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
2337 Error(RHSLoc, Twine("expected value of type '") +
2338 ItemType->getAsString() + "', got '" +
2339 Type->getAsString() + "'");
2342 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
2343 if (!LHSt && !isa<UnsetInit>(LHS)) {
2344 TokError("could not determine type of the source string in !find");
2345 return nullptr;
2347 if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
2348 TokError(Twine("expected string, got type '") +
2349 LHSt->getType()->getAsString() + "'");
2350 return nullptr;
2353 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2354 if (!MHSt && !isa<UnsetInit>(MHS)) {
2355 TokError("could not determine type of the target string in !find");
2356 return nullptr;
2358 if (MHSt && !isa<StringRecTy>(MHSt->getType())) {
2359 Error(MHSLoc, Twine("expected string, got type '") +
2360 MHSt->getType()->getAsString() + "'");
2361 return nullptr;
2364 if (RHS) {
2365 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2366 if (!RHSt && !isa<UnsetInit>(RHS)) {
2367 TokError("could not determine type of the start position in !find");
2368 return nullptr;
2370 if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
2371 TokError(Twine("expected int, got type '") +
2372 RHSt->getType()->getAsString() + "'");
2373 return nullptr;
2377 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
2380 /// Parse the !foreach and !filter operations. Return null on error.
2382 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2383 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
2384 Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
2385 SMLoc OpLoc = Lex.getLoc();
2386 tgtok::TokKind Operation = Lex.getCode();
2387 Lex.Lex(); // eat the operation
2388 if (Lex.getCode() != tgtok::l_paren) {
2389 TokError("expected '(' after !foreach/!filter");
2390 return nullptr;
2393 if (Lex.Lex() != tgtok::Id) { // eat the '('
2394 TokError("first argument of !foreach/!filter must be an identifier");
2395 return nullptr;
2398 Init *LHS = StringInit::get(Records, Lex.getCurStrVal());
2399 Lex.Lex(); // eat the ID.
2401 if (CurRec && CurRec->getValue(LHS)) {
2402 TokError((Twine("iteration variable '") + LHS->getAsString() +
2403 "' is already defined")
2404 .str());
2405 return nullptr;
2408 if (!consume(tgtok::comma)) {
2409 TokError("expected ',' in !foreach/!filter");
2410 return nullptr;
2413 Init *MHS = ParseValue(CurRec);
2414 if (!MHS)
2415 return nullptr;
2417 if (!consume(tgtok::comma)) {
2418 TokError("expected ',' in !foreach/!filter");
2419 return nullptr;
2422 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
2423 if (!MHSt) {
2424 TokError("could not get type of !foreach/!filter list or dag");
2425 return nullptr;
2428 RecTy *InEltType = nullptr;
2429 RecTy *ExprEltType = nullptr;
2430 bool IsDAG = false;
2432 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
2433 InEltType = InListTy->getElementType();
2434 if (ItemType) {
2435 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
2436 ExprEltType = (Operation == tgtok::XForEach)
2437 ? OutListTy->getElementType()
2438 : IntRecTy::get(Records);
2439 } else {
2440 Error(OpLoc,
2441 "expected value of type '" +
2442 Twine(ItemType->getAsString()) +
2443 "', but got list type");
2444 return nullptr;
2447 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
2448 if (Operation == tgtok::XFilter) {
2449 TokError("!filter must have a list argument");
2450 return nullptr;
2452 InEltType = InDagTy;
2453 if (ItemType && !isa<DagRecTy>(ItemType)) {
2454 Error(OpLoc,
2455 "expected value of type '" + Twine(ItemType->getAsString()) +
2456 "', but got dag type");
2457 return nullptr;
2459 IsDAG = true;
2460 } else {
2461 if (Operation == tgtok::XForEach)
2462 TokError("!foreach must have a list or dag argument");
2463 else
2464 TokError("!filter must have a list argument");
2465 return nullptr;
2468 // We need to create a temporary record to provide a scope for the
2469 // iteration variable.
2470 std::unique_ptr<Record> ParseRecTmp;
2471 Record *ParseRec = CurRec;
2472 if (!ParseRec) {
2473 ParseRecTmp =
2474 std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
2475 ParseRec = ParseRecTmp.get();
2477 TGVarScope *TempScope = PushScope(ParseRec);
2478 ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
2479 Init *RHS = ParseValue(ParseRec, ExprEltType);
2480 ParseRec->removeValue(LHS);
2481 PopScope(TempScope);
2482 if (!RHS)
2483 return nullptr;
2485 if (!consume(tgtok::r_paren)) {
2486 TokError("expected ')' in !foreach/!filter");
2487 return nullptr;
2490 RecTy *OutType = InEltType;
2491 if (Operation == tgtok::XForEach && !IsDAG) {
2492 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
2493 if (!RHSt) {
2494 TokError("could not get type of !foreach result expression");
2495 return nullptr;
2497 OutType = RHSt->getType()->getListTy();
2498 } else if (Operation == tgtok::XFilter) {
2499 OutType = InEltType->getListTy();
2502 return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
2503 : TernOpInit::FILTER,
2504 LHS, MHS, RHS, OutType))
2505 ->Fold(CurRec);
2508 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
2509 Lex.Lex(); // eat the operation 'cond'
2511 if (!consume(tgtok::l_paren)) {
2512 TokError("expected '(' after !cond operator");
2513 return nullptr;
2516 // Parse through '[Case: Val,]+'
2517 SmallVector<Init *, 4> Case;
2518 SmallVector<Init *, 4> Val;
2519 while (true) {
2520 if (consume(tgtok::r_paren))
2521 break;
2523 Init *V = ParseValue(CurRec);
2524 if (!V)
2525 return nullptr;
2526 Case.push_back(V);
2528 if (!consume(tgtok::colon)) {
2529 TokError("expected ':' following a condition in !cond operator");
2530 return nullptr;
2533 V = ParseValue(CurRec, ItemType);
2534 if (!V)
2535 return nullptr;
2536 Val.push_back(V);
2538 if (consume(tgtok::r_paren))
2539 break;
2541 if (!consume(tgtok::comma)) {
2542 TokError("expected ',' or ')' following a value in !cond operator");
2543 return nullptr;
2547 if (Case.size() < 1) {
2548 TokError("there should be at least 1 'condition : value' in the !cond operator");
2549 return nullptr;
2552 // resolve type
2553 RecTy *Type = nullptr;
2554 for (Init *V : Val) {
2555 RecTy *VTy = nullptr;
2556 if (TypedInit *Vt = dyn_cast<TypedInit>(V))
2557 VTy = Vt->getType();
2558 if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
2559 VTy = BitsRecTy::get(Records, Vbits->getNumBits());
2560 if (isa<BitInit>(V))
2561 VTy = BitRecTy::get(Records);
2563 if (Type == nullptr) {
2564 if (!isa<UnsetInit>(V))
2565 Type = VTy;
2566 } else {
2567 if (!isa<UnsetInit>(V)) {
2568 RecTy *RType = resolveTypes(Type, VTy);
2569 if (!RType) {
2570 TokError(Twine("inconsistent types '") + Type->getAsString() +
2571 "' and '" + VTy->getAsString() + "' for !cond");
2572 return nullptr;
2574 Type = RType;
2579 if (!Type) {
2580 TokError("could not determine type for !cond from its arguments");
2581 return nullptr;
2583 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
2586 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2588 /// SimpleValue ::= IDValue
2589 /// SimpleValue ::= INTVAL
2590 /// SimpleValue ::= STRVAL+
2591 /// SimpleValue ::= CODEFRAGMENT
2592 /// SimpleValue ::= '?'
2593 /// SimpleValue ::= '{' ValueList '}'
2594 /// SimpleValue ::= ID '<' ValueListNE '>'
2595 /// SimpleValue ::= '[' ValueList ']'
2596 /// SimpleValue ::= '(' IDValue DagArgList ')'
2597 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2598 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2599 /// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2600 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2601 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2602 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2603 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2604 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2605 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2606 /// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2607 /// SimpleValue ::= RANGE '(' Value ')'
2608 /// SimpleValue ::= RANGE '(' Value ',' Value ')'
2609 /// SimpleValue ::= RANGE '(' Value ',' Value ',' Value ')'
2610 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2611 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2613 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
2614 IDParseMode Mode) {
2615 Init *R = nullptr;
2616 tgtok::TokKind Code = Lex.getCode();
2618 // Parse bang operators.
2619 if (tgtok::isBangOperator(Code))
2620 return ParseOperation(CurRec, ItemType);
2622 switch (Code) {
2623 default: TokError("Unknown or reserved token when parsing a value"); break;
2625 case tgtok::TrueVal:
2626 R = IntInit::get(Records, 1);
2627 Lex.Lex();
2628 break;
2629 case tgtok::FalseVal:
2630 R = IntInit::get(Records, 0);
2631 Lex.Lex();
2632 break;
2633 case tgtok::IntVal:
2634 R = IntInit::get(Records, Lex.getCurIntVal());
2635 Lex.Lex();
2636 break;
2637 case tgtok::BinaryIntVal: {
2638 auto BinaryVal = Lex.getCurBinaryIntVal();
2639 SmallVector<Init*, 16> Bits(BinaryVal.second);
2640 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
2641 Bits[i] = BitInit::get(Records, BinaryVal.first & (1LL << i));
2642 R = BitsInit::get(Records, Bits);
2643 Lex.Lex();
2644 break;
2646 case tgtok::StrVal: {
2647 std::string Val = Lex.getCurStrVal();
2648 Lex.Lex();
2650 // Handle multiple consecutive concatenated strings.
2651 while (Lex.getCode() == tgtok::StrVal) {
2652 Val += Lex.getCurStrVal();
2653 Lex.Lex();
2656 R = StringInit::get(Records, Val);
2657 break;
2659 case tgtok::CodeFragment:
2660 R = StringInit::get(Records, Lex.getCurStrVal(), StringInit::SF_Code);
2661 Lex.Lex();
2662 break;
2663 case tgtok::question:
2664 R = UnsetInit::get(Records);
2665 Lex.Lex();
2666 break;
2667 case tgtok::Id: {
2668 SMRange NameLoc = Lex.getLocRange();
2669 StringInit *Name = StringInit::get(Records, Lex.getCurStrVal());
2670 tgtok::TokKind Next = Lex.Lex();
2671 if (Next == tgtok::equal) // Named argument.
2672 return Name;
2673 if (Next != tgtok::less) // consume the Id.
2674 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
2676 // Value ::= CLASSID '<' ArgValueList '>' (CLASSID has been consumed)
2677 // This is supposed to synthesize a new anonymous definition, deriving
2678 // from the class with the template arguments, but no body.
2679 Record *Class = Records.getClass(Name->getValue());
2680 if (!Class) {
2681 Error(NameLoc.Start,
2682 "Expected a class name, got '" + Name->getValue() + "'");
2683 return nullptr;
2686 SmallVector<ArgumentInit *, 8> Args;
2687 Lex.Lex(); // consume the <
2688 if (ParseTemplateArgValueList(Args, CurRec, Class))
2689 return nullptr; // Error parsing value list.
2691 if (CheckTemplateArgValues(Args, NameLoc.Start, Class))
2692 return nullptr; // Error checking template argument values.
2694 if (resolveArguments(Class, Args, NameLoc.Start))
2695 return nullptr;
2697 if (TrackReferenceLocs)
2698 Class->appendReferenceLoc(NameLoc);
2699 return VarDefInit::get(Class, Args)->Fold();
2701 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
2702 SMLoc BraceLoc = Lex.getLoc();
2703 Lex.Lex(); // eat the '{'
2704 SmallVector<Init*, 16> Vals;
2706 if (Lex.getCode() != tgtok::r_brace) {
2707 ParseValueList(Vals, CurRec);
2708 if (Vals.empty()) return nullptr;
2710 if (!consume(tgtok::r_brace)) {
2711 TokError("expected '}' at end of bit list value");
2712 return nullptr;
2715 SmallVector<Init *, 16> NewBits;
2717 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2718 // first. We'll first read everything in to a vector, then we can reverse
2719 // it to get the bits in the correct order for the BitsInit value.
2720 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2721 // FIXME: The following two loops would not be duplicated
2722 // if the API was a little more orthogonal.
2724 // bits<n> values are allowed to initialize n bits.
2725 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
2726 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
2727 NewBits.push_back(BI->getBit((e - i) - 1));
2728 continue;
2730 // bits<n> can also come from variable initializers.
2731 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
2732 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
2733 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
2734 NewBits.push_back(VI->getBit((e - i) - 1));
2735 continue;
2737 // Fallthrough to try convert this to a bit.
2739 // All other values must be convertible to just a single bit.
2740 Init *Bit = Vals[i]->getCastTo(BitRecTy::get(Records));
2741 if (!Bit) {
2742 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
2743 ") is not convertable to a bit");
2744 return nullptr;
2746 NewBits.push_back(Bit);
2748 std::reverse(NewBits.begin(), NewBits.end());
2749 return BitsInit::get(Records, NewBits);
2751 case tgtok::l_square: { // Value ::= '[' ValueList ']'
2752 Lex.Lex(); // eat the '['
2753 SmallVector<Init*, 16> Vals;
2755 RecTy *DeducedEltTy = nullptr;
2756 ListRecTy *GivenListTy = nullptr;
2758 if (ItemType) {
2759 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
2760 if (!ListType) {
2761 TokError(Twine("Encountered a list when expecting a ") +
2762 ItemType->getAsString());
2763 return nullptr;
2765 GivenListTy = ListType;
2768 if (Lex.getCode() != tgtok::r_square) {
2769 ParseValueList(Vals, CurRec,
2770 GivenListTy ? GivenListTy->getElementType() : nullptr);
2771 if (Vals.empty()) return nullptr;
2773 if (!consume(tgtok::r_square)) {
2774 TokError("expected ']' at end of list value");
2775 return nullptr;
2778 RecTy *GivenEltTy = nullptr;
2779 if (consume(tgtok::less)) {
2780 // Optional list element type
2781 GivenEltTy = ParseType();
2782 if (!GivenEltTy) {
2783 // Couldn't parse element type
2784 return nullptr;
2787 if (!consume(tgtok::greater)) {
2788 TokError("expected '>' at end of list element type");
2789 return nullptr;
2793 // Check elements
2794 RecTy *EltTy = nullptr;
2795 for (Init *V : Vals) {
2796 TypedInit *TArg = dyn_cast<TypedInit>(V);
2797 if (TArg) {
2798 if (EltTy) {
2799 EltTy = resolveTypes(EltTy, TArg->getType());
2800 if (!EltTy) {
2801 TokError("Incompatible types in list elements");
2802 return nullptr;
2804 } else {
2805 EltTy = TArg->getType();
2810 if (GivenEltTy) {
2811 if (EltTy) {
2812 // Verify consistency
2813 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2814 TokError("Incompatible types in list elements");
2815 return nullptr;
2818 EltTy = GivenEltTy;
2821 if (!EltTy) {
2822 if (!ItemType) {
2823 TokError("No type for list");
2824 return nullptr;
2826 DeducedEltTy = GivenListTy->getElementType();
2827 } else {
2828 // Make sure the deduced type is compatible with the given type
2829 if (GivenListTy) {
2830 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2831 TokError(Twine("Element type mismatch for list: element type '") +
2832 EltTy->getAsString() + "' not convertible to '" +
2833 GivenListTy->getElementType()->getAsString());
2834 return nullptr;
2837 DeducedEltTy = EltTy;
2840 return ListInit::get(Vals, DeducedEltTy);
2842 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2843 Lex.Lex(); // eat the '('
2844 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2845 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
2846 TokError("expected identifier in dag init");
2847 return nullptr;
2850 Init *Operator = ParseValue(CurRec);
2851 if (!Operator) return nullptr;
2853 // If the operator name is present, parse it.
2854 StringInit *OperatorName = nullptr;
2855 if (consume(tgtok::colon)) {
2856 if (Lex.getCode() != tgtok::VarName) { // eat the ':'
2857 TokError("expected variable name in dag operator");
2858 return nullptr;
2860 OperatorName = StringInit::get(Records, Lex.getCurStrVal());
2861 Lex.Lex(); // eat the VarName.
2864 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2865 if (Lex.getCode() != tgtok::r_paren) {
2866 ParseDagArgList(DagArgs, CurRec);
2867 if (DagArgs.empty()) return nullptr;
2870 if (!consume(tgtok::r_paren)) {
2871 TokError("expected ')' in dag init");
2872 return nullptr;
2875 return DagInit::get(Operator, OperatorName, DagArgs);
2879 return R;
2882 /// ParseValue - Parse a TableGen value. This returns null on error.
2884 /// Value ::= SimpleValue ValueSuffix*
2885 /// ValueSuffix ::= '{' BitList '}'
2886 /// ValueSuffix ::= '[' SliceElements ']'
2887 /// ValueSuffix ::= '.' ID
2889 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2890 SMLoc LHSLoc = Lex.getLoc();
2891 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2892 if (!Result) return nullptr;
2894 // Parse the suffixes now if present.
2895 while (true) {
2896 switch (Lex.getCode()) {
2897 default: return Result;
2898 case tgtok::l_brace: {
2899 if (Mode == ParseNameMode)
2900 // This is the beginning of the object body.
2901 return Result;
2903 SMLoc CurlyLoc = Lex.getLoc();
2904 Lex.Lex(); // eat the '{'
2905 SmallVector<unsigned, 16> Ranges;
2906 ParseRangeList(Ranges);
2907 if (Ranges.empty()) return nullptr;
2909 // Reverse the bitlist.
2910 std::reverse(Ranges.begin(), Ranges.end());
2911 Result = Result->convertInitializerBitRange(Ranges);
2912 if (!Result) {
2913 Error(CurlyLoc, "Invalid bit range for value");
2914 return nullptr;
2917 // Eat the '}'.
2918 if (!consume(tgtok::r_brace)) {
2919 TokError("expected '}' at end of bit range list");
2920 return nullptr;
2922 break;
2924 case tgtok::l_square: {
2925 auto *LHS = dyn_cast<TypedInit>(Result);
2926 if (!LHS) {
2927 Error(LHSLoc, "Invalid value, list expected");
2928 return nullptr;
2931 auto *LHSTy = dyn_cast<ListRecTy>(LHS->getType());
2932 if (!LHSTy) {
2933 Error(LHSLoc, "Type '" + Twine(LHS->getType()->getAsString()) +
2934 "' is invalid, list expected");
2935 return nullptr;
2938 Lex.Lex(); // eat the '['
2939 TypedInit *RHS = ParseSliceElements(CurRec, /*Single=*/true);
2940 if (!RHS)
2941 return nullptr;
2943 if (isa<ListRecTy>(RHS->getType())) {
2944 Result =
2945 BinOpInit::get(BinOpInit::LISTSLICE, LHS, RHS, LHSTy)->Fold(CurRec);
2946 } else {
2947 Result = BinOpInit::get(BinOpInit::LISTELEM, LHS, RHS,
2948 LHSTy->getElementType())
2949 ->Fold(CurRec);
2952 assert(Result);
2954 // Eat the ']'.
2955 if (!consume(tgtok::r_square)) {
2956 TokError("expected ']' at end of list slice");
2957 return nullptr;
2959 break;
2961 case tgtok::dot: {
2962 if (Lex.Lex() != tgtok::Id) { // eat the .
2963 TokError("expected field identifier after '.'");
2964 return nullptr;
2966 SMRange FieldNameLoc = Lex.getLocRange();
2967 StringInit *FieldName = StringInit::get(Records, Lex.getCurStrVal());
2968 if (!Result->getFieldType(FieldName)) {
2969 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2970 Result->getAsString() + "'");
2971 return nullptr;
2974 // Add a reference to this field if we know the record class.
2975 if (TrackReferenceLocs) {
2976 if (auto *DI = dyn_cast<DefInit>(Result)) {
2977 DI->getDef()->getValue(FieldName)->addReferenceLoc(FieldNameLoc);
2978 } else if (auto *TI = dyn_cast<TypedInit>(Result)) {
2979 if (auto *RecTy = dyn_cast<RecordRecTy>(TI->getType())) {
2980 for (Record *R : RecTy->getClasses())
2981 if (auto *RV = R->getValue(FieldName))
2982 RV->addReferenceLoc(FieldNameLoc);
2987 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2988 Lex.Lex(); // eat field name
2989 break;
2992 case tgtok::paste:
2993 SMLoc PasteLoc = Lex.getLoc();
2994 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2995 if (!LHS) {
2996 Error(PasteLoc, "LHS of paste is not typed!");
2997 return nullptr;
3000 // Check if it's a 'listA # listB'
3001 if (isa<ListRecTy>(LHS->getType())) {
3002 Lex.Lex(); // Eat the '#'.
3004 assert(Mode == ParseValueMode && "encountered paste of lists in name");
3006 switch (Lex.getCode()) {
3007 case tgtok::colon:
3008 case tgtok::semi:
3009 case tgtok::l_brace:
3010 Result = LHS; // trailing paste, ignore.
3011 break;
3012 default:
3013 Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
3014 if (!RHSResult)
3015 return nullptr;
3016 Result = BinOpInit::getListConcat(LHS, RHSResult);
3017 break;
3019 break;
3022 // Create a !strconcat() operation, first casting each operand to
3023 // a string if necessary.
3024 if (LHS->getType() != StringRecTy::get(Records)) {
3025 auto CastLHS = dyn_cast<TypedInit>(
3026 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get(Records))
3027 ->Fold(CurRec));
3028 if (!CastLHS) {
3029 Error(PasteLoc,
3030 Twine("can't cast '") + LHS->getAsString() + "' to string");
3031 return nullptr;
3033 LHS = CastLHS;
3036 TypedInit *RHS = nullptr;
3038 Lex.Lex(); // Eat the '#'.
3039 switch (Lex.getCode()) {
3040 case tgtok::colon:
3041 case tgtok::semi:
3042 case tgtok::l_brace:
3043 // These are all of the tokens that can begin an object body.
3044 // Some of these can also begin values but we disallow those cases
3045 // because they are unlikely to be useful.
3047 // Trailing paste, concat with an empty string.
3048 RHS = StringInit::get(Records, "");
3049 break;
3051 default:
3052 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
3053 if (!RHSResult)
3054 return nullptr;
3055 RHS = dyn_cast<TypedInit>(RHSResult);
3056 if (!RHS) {
3057 Error(PasteLoc, "RHS of paste is not typed!");
3058 return nullptr;
3061 if (RHS->getType() != StringRecTy::get(Records)) {
3062 auto CastRHS = dyn_cast<TypedInit>(
3063 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get(Records))
3064 ->Fold(CurRec));
3065 if (!CastRHS) {
3066 Error(PasteLoc,
3067 Twine("can't cast '") + RHS->getAsString() + "' to string");
3068 return nullptr;
3070 RHS = CastRHS;
3073 break;
3076 Result = BinOpInit::getStrConcat(LHS, RHS);
3077 break;
3082 /// ParseDagArgList - Parse the argument list for a dag literal expression.
3084 /// DagArg ::= Value (':' VARNAME)?
3085 /// DagArg ::= VARNAME
3086 /// DagArgList ::= DagArg
3087 /// DagArgList ::= DagArgList ',' DagArg
3088 void TGParser::ParseDagArgList(
3089 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
3090 Record *CurRec) {
3092 while (true) {
3093 // DagArg ::= VARNAME
3094 if (Lex.getCode() == tgtok::VarName) {
3095 // A missing value is treated like '?'.
3096 StringInit *VarName = StringInit::get(Records, Lex.getCurStrVal());
3097 Result.emplace_back(UnsetInit::get(Records), VarName);
3098 Lex.Lex();
3099 } else {
3100 // DagArg ::= Value (':' VARNAME)?
3101 Init *Val = ParseValue(CurRec);
3102 if (!Val) {
3103 Result.clear();
3104 return;
3107 // If the variable name is present, add it.
3108 StringInit *VarName = nullptr;
3109 if (Lex.getCode() == tgtok::colon) {
3110 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
3111 TokError("expected variable name in dag literal");
3112 Result.clear();
3113 return;
3115 VarName = StringInit::get(Records, Lex.getCurStrVal());
3116 Lex.Lex(); // eat the VarName.
3119 Result.push_back(std::make_pair(Val, VarName));
3121 if (!consume(tgtok::comma))
3122 break;
3126 /// ParseValueList - Parse a comma separated list of values, returning them
3127 /// in a vector. Note that this always expects to be able to parse at least one
3128 /// value. It returns an empty list if this is not possible.
3130 /// ValueList ::= Value (',' Value)
3132 void TGParser::ParseValueList(SmallVectorImpl<Init *> &Result, Record *CurRec,
3133 RecTy *ItemType) {
3135 Result.push_back(ParseValue(CurRec, ItemType));
3136 if (!Result.back()) {
3137 Result.clear();
3138 return;
3141 while (consume(tgtok::comma)) {
3142 // ignore trailing comma for lists
3143 if (Lex.getCode() == tgtok::r_square)
3144 return;
3145 Result.push_back(ParseValue(CurRec, ItemType));
3146 if (!Result.back()) {
3147 Result.clear();
3148 return;
3153 // ParseTemplateArgValueList - Parse a template argument list with the syntax
3154 // shown, filling in the Result vector. The open angle has been consumed.
3155 // An empty argument list is allowed. Return false if okay, true if an
3156 // error was detected.
3158 // ArgValueList ::= '<' PostionalArgValueList [','] NamedArgValueList '>'
3159 // PostionalArgValueList ::= [Value {',' Value}*]
3160 // NamedArgValueList ::= [NameValue '=' Value {',' NameValue '=' Value}*]
3161 bool TGParser::ParseTemplateArgValueList(
3162 SmallVectorImpl<ArgumentInit *> &Result, Record *CurRec, Record *ArgsRec) {
3163 assert(Result.empty() && "Result vector is not empty");
3164 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
3166 if (consume(tgtok::greater)) // empty value list
3167 return false;
3169 bool HasNamedArg = false;
3170 unsigned ArgIndex = 0;
3171 while (true) {
3172 if (ArgIndex >= TArgs.size()) {
3173 TokError("Too many template arguments: " + utostr(ArgIndex + 1));
3174 return true;
3177 SMLoc ValueLoc = Lex.getLoc();
3178 // If we are parsing named argument, we don't need to know the argument name
3179 // and argument type will be resolved after we know the name.
3180 Init *Value = ParseValue(
3181 CurRec,
3182 HasNamedArg ? nullptr : ArgsRec->getValue(TArgs[ArgIndex])->getType());
3183 if (!Value)
3184 return true;
3186 // If we meet '=', then we are parsing named arguments.
3187 if (Lex.getCode() == tgtok::equal) {
3188 if (!isa<StringInit>(Value))
3189 return Error(ValueLoc,
3190 "The name of named argument should be a valid identifier");
3192 auto *Name = cast<StringInit>(Value);
3193 Init *QualifiedName = QualifyName(*ArgsRec, Name);
3194 auto *NamedArg = ArgsRec->getValue(QualifiedName);
3195 if (!NamedArg)
3196 return Error(ValueLoc,
3197 "Argument " + Name->getAsString() + " doesn't exist");
3199 Lex.Lex(); // eat the '='.
3200 ValueLoc = Lex.getLoc();
3201 Value = ParseValue(CurRec, NamedArg->getType());
3202 // Named value can't be uninitialized.
3203 if (isa<UnsetInit>(Value))
3204 return Error(ValueLoc,
3205 "The value of named argument should be initialized, "
3206 "but we got '" +
3207 Value->getAsString() + "'");
3209 Result.push_back(ArgumentInit::get(Value, QualifiedName));
3210 HasNamedArg = true;
3211 } else {
3212 // Positional arguments should be put before named arguments.
3213 if (HasNamedArg)
3214 return Error(ValueLoc,
3215 "Positional argument should be put before named argument");
3217 Result.push_back(ArgumentInit::get(Value, ArgIndex));
3220 if (consume(tgtok::greater)) // end of argument list?
3221 return false;
3222 if (!consume(tgtok::comma))
3223 return TokError("Expected comma before next argument");
3224 ++ArgIndex;
3228 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3229 /// empty string on error. This can happen in a number of different contexts,
3230 /// including within a def or in the template args for a class (in which case
3231 /// CurRec will be non-null) and within the template args for a multiclass (in
3232 /// which case CurRec will be null, but CurMultiClass will be set). This can
3233 /// also happen within a def that is within a multiclass, which will set both
3234 /// CurRec and CurMultiClass.
3236 /// Declaration ::= FIELD? Type ID ('=' Value)?
3238 Init *TGParser::ParseDeclaration(Record *CurRec,
3239 bool ParsingTemplateArgs) {
3240 // Read the field prefix if present.
3241 bool HasField = consume(tgtok::Field);
3243 RecTy *Type = ParseType();
3244 if (!Type) return nullptr;
3246 if (Lex.getCode() != tgtok::Id) {
3247 TokError("Expected identifier in declaration");
3248 return nullptr;
3251 std::string Str = Lex.getCurStrVal();
3252 if (Str == "NAME") {
3253 TokError("'" + Str + "' is a reserved variable name");
3254 return nullptr;
3257 if (!ParsingTemplateArgs && CurScope->varAlreadyDefined(Str)) {
3258 TokError("local variable of this name already exists");
3259 return nullptr;
3262 SMLoc IdLoc = Lex.getLoc();
3263 Init *DeclName = StringInit::get(Records, Str);
3264 Lex.Lex();
3266 bool BadField;
3267 if (!ParsingTemplateArgs) { // def, possibly in a multiclass
3268 BadField = AddValue(CurRec, IdLoc,
3269 RecordVal(DeclName, IdLoc, Type,
3270 HasField ? RecordVal::FK_NonconcreteOK
3271 : RecordVal::FK_Normal));
3272 } else if (CurRec) { // class template argument
3273 DeclName = QualifyName(*CurRec, DeclName);
3274 BadField =
3275 AddValue(CurRec, IdLoc,
3276 RecordVal(DeclName, IdLoc, Type, RecordVal::FK_TemplateArg));
3277 } else { // multiclass template argument
3278 assert(CurMultiClass && "invalid context for template argument");
3279 DeclName = QualifyName(CurMultiClass, DeclName);
3280 BadField =
3281 AddValue(CurRec, IdLoc,
3282 RecordVal(DeclName, IdLoc, Type, RecordVal::FK_TemplateArg));
3284 if (BadField)
3285 return nullptr;
3287 // If a value is present, parse it and set new field's value.
3288 if (consume(tgtok::equal)) {
3289 SMLoc ValLoc = Lex.getLoc();
3290 Init *Val = ParseValue(CurRec, Type);
3291 if (!Val ||
3292 SetValue(CurRec, ValLoc, DeclName, std::nullopt, Val,
3293 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3294 // Return the name, even if an error is thrown. This is so that we can
3295 // continue to make some progress, even without the value having been
3296 // initialized.
3297 return DeclName;
3301 return DeclName;
3304 /// ParseForeachDeclaration - Read a foreach declaration, returning
3305 /// the name of the declared object or a NULL Init on error. Return
3306 /// the name of the parsed initializer list through ForeachListName.
3308 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3309 /// ForeachDeclaration ::= ID '=' RangePiece
3310 /// ForeachDeclaration ::= ID '=' Value
3312 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
3313 if (Lex.getCode() != tgtok::Id) {
3314 TokError("Expected identifier in foreach declaration");
3315 return nullptr;
3318 Init *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3319 Lex.Lex();
3321 // If a value is present, parse it.
3322 if (!consume(tgtok::equal)) {
3323 TokError("Expected '=' in foreach declaration");
3324 return nullptr;
3327 RecTy *IterType = nullptr;
3328 SmallVector<unsigned, 16> Ranges;
3330 switch (Lex.getCode()) {
3331 case tgtok::l_brace: { // '{' RangeList '}'
3332 Lex.Lex(); // eat the '{'
3333 ParseRangeList(Ranges);
3334 if (!consume(tgtok::r_brace)) {
3335 TokError("expected '}' at end of bit range list");
3336 return nullptr;
3338 break;
3341 default: {
3342 SMLoc ValueLoc = Lex.getLoc();
3343 Init *I = ParseValue(nullptr);
3344 if (!I)
3345 return nullptr;
3347 TypedInit *TI = dyn_cast<TypedInit>(I);
3348 if (TI && isa<ListRecTy>(TI->getType())) {
3349 ForeachListValue = I;
3350 IterType = cast<ListRecTy>(TI->getType())->getElementType();
3351 break;
3354 if (TI) {
3355 if (ParseRangePiece(Ranges, TI))
3356 return nullptr;
3357 break;
3360 Error(ValueLoc, "expected a list, got '" + I->getAsString() + "'");
3361 if (CurMultiClass) {
3362 PrintNote({}, "references to multiclass template arguments cannot be "
3363 "resolved at this time");
3365 return nullptr;
3370 if (!Ranges.empty()) {
3371 assert(!IterType && "Type already initialized?");
3372 IterType = IntRecTy::get(Records);
3373 std::vector<Init *> Values;
3374 for (unsigned R : Ranges)
3375 Values.push_back(IntInit::get(Records, R));
3376 ForeachListValue = ListInit::get(Values, IterType);
3379 if (!IterType)
3380 return nullptr;
3382 return VarInit::get(DeclName, IterType);
3385 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
3386 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3387 /// template args for a class. If null, these are the template args for a
3388 /// multiclass.
3390 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3392 bool TGParser::ParseTemplateArgList(Record *CurRec) {
3393 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
3394 Lex.Lex(); // eat the '<'
3396 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
3398 // Read the first declaration.
3399 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
3400 if (!TemplArg)
3401 return true;
3403 TheRecToAddTo->addTemplateArg(TemplArg);
3405 while (consume(tgtok::comma)) {
3406 // Read the following declarations.
3407 SMLoc Loc = Lex.getLoc();
3408 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
3409 if (!TemplArg)
3410 return true;
3412 if (TheRecToAddTo->isTemplateArg(TemplArg))
3413 return Error(Loc, "template argument with the same name has already been "
3414 "defined");
3416 TheRecToAddTo->addTemplateArg(TemplArg);
3419 if (!consume(tgtok::greater))
3420 return TokError("expected '>' at end of template argument list");
3421 return false;
3424 /// ParseBodyItem - Parse a single item within the body of a def or class.
3426 /// BodyItem ::= Declaration ';'
3427 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
3428 /// BodyItem ::= Defvar
3429 /// BodyItem ::= Dump
3430 /// BodyItem ::= Assert
3432 bool TGParser::ParseBodyItem(Record *CurRec) {
3433 if (Lex.getCode() == tgtok::Assert)
3434 return ParseAssert(nullptr, CurRec);
3436 if (Lex.getCode() == tgtok::Defvar)
3437 return ParseDefvar(CurRec);
3439 if (Lex.getCode() == tgtok::Dump)
3440 return ParseDump(nullptr, CurRec);
3442 if (Lex.getCode() != tgtok::Let) {
3443 if (!ParseDeclaration(CurRec, false))
3444 return true;
3446 if (!consume(tgtok::semi))
3447 return TokError("expected ';' after declaration");
3448 return false;
3451 // LET ID OptionalRangeList '=' Value ';'
3452 if (Lex.Lex() != tgtok::Id)
3453 return TokError("expected field identifier after let");
3455 SMLoc IdLoc = Lex.getLoc();
3456 StringInit *FieldName = StringInit::get(Records, Lex.getCurStrVal());
3457 Lex.Lex(); // eat the field name.
3459 SmallVector<unsigned, 16> BitList;
3460 if (ParseOptionalBitList(BitList))
3461 return true;
3462 std::reverse(BitList.begin(), BitList.end());
3464 if (!consume(tgtok::equal))
3465 return TokError("expected '=' in let expression");
3467 RecordVal *Field = CurRec->getValue(FieldName);
3468 if (!Field)
3469 return TokError("Value '" + FieldName->getValue() + "' unknown!");
3471 RecTy *Type = Field->getType();
3472 if (!BitList.empty() && isa<BitsRecTy>(Type)) {
3473 // When assigning to a subset of a 'bits' object, expect the RHS to have
3474 // the type of that subset instead of the type of the whole object.
3475 Type = BitsRecTy::get(Records, BitList.size());
3478 Init *Val = ParseValue(CurRec, Type);
3479 if (!Val) return true;
3481 if (!consume(tgtok::semi))
3482 return TokError("expected ';' after let expression");
3484 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
3487 /// ParseBody - Read the body of a class or def. Return true on error, false on
3488 /// success.
3490 /// Body ::= ';'
3491 /// Body ::= '{' BodyList '}'
3492 /// BodyList BodyItem*
3494 bool TGParser::ParseBody(Record *CurRec) {
3495 // If this is a null definition, just eat the semi and return.
3496 if (consume(tgtok::semi))
3497 return false;
3499 if (!consume(tgtok::l_brace))
3500 return TokError("Expected '{' to start body or ';' for declaration only");
3502 while (Lex.getCode() != tgtok::r_brace)
3503 if (ParseBodyItem(CurRec))
3504 return true;
3506 // Eat the '}'.
3507 Lex.Lex();
3509 // If we have a semicolon, print a gentle error.
3510 SMLoc SemiLoc = Lex.getLoc();
3511 if (consume(tgtok::semi)) {
3512 PrintError(SemiLoc, "A class or def body should not end with a semicolon");
3513 PrintNote("Semicolon ignored; remove to eliminate this error");
3516 return false;
3519 /// Apply the current let bindings to \a CurRec.
3520 /// \returns true on error, false otherwise.
3521 bool TGParser::ApplyLetStack(Record *CurRec) {
3522 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
3523 for (LetRecord &LR : LetInfo)
3524 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
3525 return true;
3526 return false;
3529 /// Apply the current let bindings to the RecordsEntry.
3530 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
3531 if (Entry.Rec)
3532 return ApplyLetStack(Entry.Rec.get());
3534 // Let bindings are not applied to assertions.
3535 if (Entry.Assertion)
3536 return false;
3538 // Let bindings are not applied to dumps.
3539 if (Entry.Dump)
3540 return false;
3542 for (auto &E : Entry.Loop->Entries) {
3543 if (ApplyLetStack(E))
3544 return true;
3547 return false;
3550 /// ParseObjectBody - Parse the body of a def or class. This consists of an
3551 /// optional ClassList followed by a Body. CurRec is the current def or class
3552 /// that is being parsed.
3554 /// ObjectBody ::= BaseClassList Body
3555 /// BaseClassList ::= /*empty*/
3556 /// BaseClassList ::= ':' BaseClassListNE
3557 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3559 bool TGParser::ParseObjectBody(Record *CurRec) {
3560 // An object body introduces a new scope for local variables.
3561 TGVarScope *ObjectScope = PushScope(CurRec);
3562 // If there is a baseclass list, read it.
3563 if (consume(tgtok::colon)) {
3565 // Read all of the subclasses.
3566 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
3567 while (true) {
3568 // Check for error.
3569 if (!SubClass.Rec) return true;
3571 // Add it.
3572 if (AddSubClass(CurRec, SubClass))
3573 return true;
3575 if (!consume(tgtok::comma))
3576 break;
3577 SubClass = ParseSubClassReference(CurRec, false);
3581 if (ApplyLetStack(CurRec))
3582 return true;
3584 bool Result = ParseBody(CurRec);
3585 PopScope(ObjectScope);
3586 return Result;
3589 /// ParseDef - Parse and return a top level or multiclass record definition.
3590 /// Return false if okay, true if error.
3592 /// DefInst ::= DEF ObjectName ObjectBody
3594 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
3595 SMLoc DefLoc = Lex.getLoc();
3596 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
3597 Lex.Lex(); // Eat the 'def' token.
3599 // If the name of the def is an Id token, use that for the location.
3600 // Otherwise, the name is more complex and we use the location of the 'def'
3601 // token.
3602 SMLoc NameLoc = Lex.getCode() == tgtok::Id ? Lex.getLoc() : DefLoc;
3604 // Parse ObjectName and make a record for it.
3605 std::unique_ptr<Record> CurRec;
3606 Init *Name = ParseObjectName(CurMultiClass);
3607 if (!Name)
3608 return true;
3610 if (isa<UnsetInit>(Name)) {
3611 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc,
3612 Records, Record::RK_AnonymousDef);
3613 } else {
3614 CurRec = std::make_unique<Record>(Name, NameLoc, Records);
3617 if (ParseObjectBody(CurRec.get()))
3618 return true;
3620 return addEntry(std::move(CurRec));
3623 /// ParseDefset - Parse a defset statement.
3625 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3627 bool TGParser::ParseDefset() {
3628 assert(Lex.getCode() == tgtok::Defset);
3629 Lex.Lex(); // Eat the 'defset' token
3631 DefsetRecord Defset;
3632 Defset.Loc = Lex.getLoc();
3633 RecTy *Type = ParseType();
3634 if (!Type)
3635 return true;
3636 if (!isa<ListRecTy>(Type))
3637 return Error(Defset.Loc, "expected list type");
3638 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
3640 if (Lex.getCode() != tgtok::Id)
3641 return TokError("expected identifier");
3642 StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3643 if (Records.getGlobal(DeclName->getValue()))
3644 return TokError("def or global variable of this name already exists");
3646 if (Lex.Lex() != tgtok::equal) // Eat the identifier
3647 return TokError("expected '='");
3648 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
3649 return TokError("expected '{'");
3650 SMLoc BraceLoc = Lex.getLoc();
3651 Lex.Lex(); // Eat the '{'
3653 Defsets.push_back(&Defset);
3654 bool Err = ParseObjectList(nullptr);
3655 Defsets.pop_back();
3656 if (Err)
3657 return true;
3659 if (!consume(tgtok::r_brace)) {
3660 TokError("expected '}' at end of defset");
3661 return Error(BraceLoc, "to match this '{'");
3664 Records.addExtraGlobal(DeclName->getValue(),
3665 ListInit::get(Defset.Elements, Defset.EltTy));
3666 return false;
3669 /// ParseDefvar - Parse a defvar statement.
3671 /// Defvar ::= DEFVAR Id '=' Value ';'
3673 bool TGParser::ParseDefvar(Record *CurRec) {
3674 assert(Lex.getCode() == tgtok::Defvar);
3675 Lex.Lex(); // Eat the 'defvar' token
3677 if (Lex.getCode() != tgtok::Id)
3678 return TokError("expected identifier");
3679 StringInit *DeclName = StringInit::get(Records, Lex.getCurStrVal());
3680 if (CurScope->varAlreadyDefined(DeclName->getValue()))
3681 return TokError("local variable of this name already exists");
3683 // The name should not be conflicted with existed field names.
3684 if (CurRec) {
3685 auto *V = CurRec->getValue(DeclName->getValue());
3686 if (V && !V->isTemplateArg())
3687 return TokError("field of this name already exists");
3690 // If this defvar is in the top level, the name should not be conflicted
3691 // with existed global names.
3692 if (CurScope->isOutermost() && Records.getGlobal(DeclName->getValue()))
3693 return TokError("def or global variable of this name already exists");
3695 Lex.Lex();
3696 if (!consume(tgtok::equal))
3697 return TokError("expected '='");
3699 Init *Value = ParseValue(CurRec);
3700 if (!Value)
3701 return true;
3703 if (!consume(tgtok::semi))
3704 return TokError("expected ';'");
3706 if (!CurScope->isOutermost())
3707 CurScope->addVar(DeclName->getValue(), Value);
3708 else
3709 Records.addExtraGlobal(DeclName->getValue(), Value);
3711 return false;
3714 /// ParseForeach - Parse a for statement. Return the record corresponding
3715 /// to it. This returns true on error.
3717 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3718 /// Foreach ::= FOREACH Declaration IN Object
3720 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
3721 SMLoc Loc = Lex.getLoc();
3722 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
3723 Lex.Lex(); // Eat the 'for' token.
3725 // Make a temporary object to record items associated with the for
3726 // loop.
3727 Init *ListValue = nullptr;
3728 VarInit *IterName = ParseForeachDeclaration(ListValue);
3729 if (!IterName)
3730 return TokError("expected declaration in for");
3732 if (!consume(tgtok::In))
3733 return TokError("Unknown tok");
3735 // Create a loop object and remember it.
3736 auto TheLoop = std::make_unique<ForeachLoop>(Loc, IterName, ListValue);
3737 // A foreach loop introduces a new scope for local variables.
3738 TGVarScope *ForeachScope = PushScope(TheLoop.get());
3739 Loops.push_back(std::move(TheLoop));
3741 if (Lex.getCode() != tgtok::l_brace) {
3742 // FOREACH Declaration IN Object
3743 if (ParseObject(CurMultiClass))
3744 return true;
3745 } else {
3746 SMLoc BraceLoc = Lex.getLoc();
3747 // Otherwise, this is a group foreach.
3748 Lex.Lex(); // eat the '{'.
3750 // Parse the object list.
3751 if (ParseObjectList(CurMultiClass))
3752 return true;
3754 if (!consume(tgtok::r_brace)) {
3755 TokError("expected '}' at end of foreach command");
3756 return Error(BraceLoc, "to match this '{'");
3760 PopScope(ForeachScope);
3762 // Resolve the loop or store it for later resolution.
3763 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3764 Loops.pop_back();
3766 return addEntry(std::move(Loop));
3769 /// ParseIf - Parse an if statement.
3771 /// If ::= IF Value THEN IfBody
3772 /// If ::= IF Value THEN IfBody ELSE IfBody
3774 bool TGParser::ParseIf(MultiClass *CurMultiClass) {
3775 SMLoc Loc = Lex.getLoc();
3776 assert(Lex.getCode() == tgtok::If && "Unknown tok");
3777 Lex.Lex(); // Eat the 'if' token.
3779 // Make a temporary object to record items associated with the for
3780 // loop.
3781 Init *Condition = ParseValue(nullptr);
3782 if (!Condition)
3783 return true;
3785 if (!consume(tgtok::Then))
3786 return TokError("Unknown tok");
3788 // We have to be able to save if statements to execute later, and they have
3789 // to live on the same stack as foreach loops. The simplest implementation
3790 // technique is to convert each 'then' or 'else' clause *into* a foreach
3791 // loop, over a list of length 0 or 1 depending on the condition, and with no
3792 // iteration variable being assigned.
3794 ListInit *EmptyList = ListInit::get({}, BitRecTy::get(Records));
3795 ListInit *SingletonList =
3796 ListInit::get({BitInit::get(Records, true)}, BitRecTy::get(Records));
3797 RecTy *BitListTy = ListRecTy::get(BitRecTy::get(Records));
3799 // The foreach containing the then-clause selects SingletonList if
3800 // the condition is true.
3801 Init *ThenClauseList =
3802 TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
3803 BitListTy)
3804 ->Fold(nullptr);
3805 Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
3807 if (ParseIfBody(CurMultiClass, "then"))
3808 return true;
3810 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
3811 Loops.pop_back();
3813 if (addEntry(std::move(Loop)))
3814 return true;
3816 // Now look for an optional else clause. The if-else syntax has the usual
3817 // dangling-else ambiguity, and by greedily matching an else here if we can,
3818 // we implement the usual resolution of pairing with the innermost unmatched
3819 // if.
3820 if (consume(tgtok::ElseKW)) {
3821 // The foreach containing the else-clause uses the same pair of lists as
3822 // above, but this time, selects SingletonList if the condition is *false*.
3823 Init *ElseClauseList =
3824 TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
3825 BitListTy)
3826 ->Fold(nullptr);
3827 Loops.push_back(
3828 std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
3830 if (ParseIfBody(CurMultiClass, "else"))
3831 return true;
3833 Loop = std::move(Loops.back());
3834 Loops.pop_back();
3836 if (addEntry(std::move(Loop)))
3837 return true;
3840 return false;
3843 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3845 /// IfBody ::= Object
3846 /// IfBody ::= '{' ObjectList '}'
3848 bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
3849 // An if-statement introduces a new scope for local variables.
3850 TGVarScope *BodyScope = PushScope();
3852 if (Lex.getCode() != tgtok::l_brace) {
3853 // A single object.
3854 if (ParseObject(CurMultiClass))
3855 return true;
3856 } else {
3857 SMLoc BraceLoc = Lex.getLoc();
3858 // A braced block.
3859 Lex.Lex(); // eat the '{'.
3861 // Parse the object list.
3862 if (ParseObjectList(CurMultiClass))
3863 return true;
3865 if (!consume(tgtok::r_brace)) {
3866 TokError("expected '}' at end of '" + Kind + "' clause");
3867 return Error(BraceLoc, "to match this '{'");
3871 PopScope(BodyScope);
3872 return false;
3875 /// ParseAssert - Parse an assert statement.
3877 /// Assert ::= ASSERT condition , message ;
3878 bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
3879 assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
3880 Lex.Lex(); // Eat the 'assert' token.
3882 SMLoc ConditionLoc = Lex.getLoc();
3883 Init *Condition = ParseValue(CurRec);
3884 if (!Condition)
3885 return true;
3887 if (!consume(tgtok::comma)) {
3888 TokError("expected ',' in assert statement");
3889 return true;
3892 Init *Message = ParseValue(CurRec);
3893 if (!Message)
3894 return true;
3896 if (!consume(tgtok::semi))
3897 return TokError("expected ';'");
3899 if (CurRec)
3900 CurRec->addAssertion(ConditionLoc, Condition, Message);
3901 else
3902 addEntry(std::make_unique<Record::AssertionInfo>(ConditionLoc, Condition,
3903 Message));
3904 return false;
3907 /// ParseClass - Parse a tblgen class definition.
3909 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3911 bool TGParser::ParseClass() {
3912 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
3913 Lex.Lex();
3915 if (Lex.getCode() != tgtok::Id)
3916 return TokError("expected class name after 'class' keyword");
3918 Record *CurRec = Records.getClass(Lex.getCurStrVal());
3919 if (CurRec) {
3920 // If the body was previously defined, this is an error.
3921 if (!CurRec->getValues().empty() ||
3922 !CurRec->getSuperClasses().empty() ||
3923 !CurRec->getTemplateArgs().empty())
3924 return TokError("Class '" + CurRec->getNameInitAsString() +
3925 "' already defined");
3927 CurRec->updateClassLoc(Lex.getLoc());
3928 } else {
3929 // If this is the first reference to this class, create and add it.
3930 auto NewRec = std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(),
3931 Records, Record::RK_Class);
3932 CurRec = NewRec.get();
3933 Records.addClass(std::move(NewRec));
3935 Lex.Lex(); // eat the name.
3937 // A class definition introduces a new scope.
3938 TGVarScope *ClassScope = PushScope(CurRec);
3939 // If there are template args, parse them.
3940 if (Lex.getCode() == tgtok::less)
3941 if (ParseTemplateArgList(CurRec))
3942 return true;
3944 if (ParseObjectBody(CurRec))
3945 return true;
3947 if (!NoWarnOnUnusedTemplateArgs)
3948 CurRec->checkUnusedTemplateArgs();
3950 PopScope(ClassScope);
3951 return false;
3954 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3955 /// of LetRecords.
3957 /// LetList ::= LetItem (',' LetItem)*
3958 /// LetItem ::= ID OptionalRangeList '=' Value
3960 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
3961 do {
3962 if (Lex.getCode() != tgtok::Id) {
3963 TokError("expected identifier in let definition");
3964 Result.clear();
3965 return;
3968 StringInit *Name = StringInit::get(Records, Lex.getCurStrVal());
3969 SMLoc NameLoc = Lex.getLoc();
3970 Lex.Lex(); // Eat the identifier.
3972 // Check for an optional RangeList.
3973 SmallVector<unsigned, 16> Bits;
3974 if (ParseOptionalRangeList(Bits)) {
3975 Result.clear();
3976 return;
3978 std::reverse(Bits.begin(), Bits.end());
3980 if (!consume(tgtok::equal)) {
3981 TokError("expected '=' in let expression");
3982 Result.clear();
3983 return;
3986 Init *Val = ParseValue(nullptr);
3987 if (!Val) {
3988 Result.clear();
3989 return;
3992 // Now that we have everything, add the record.
3993 Result.emplace_back(Name, Bits, Val, NameLoc);
3994 } while (consume(tgtok::comma));
3997 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3998 /// different related productions. This works inside multiclasses too.
4000 /// Object ::= LET LetList IN '{' ObjectList '}'
4001 /// Object ::= LET LetList IN Object
4003 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
4004 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
4005 Lex.Lex();
4007 // Add this entry to the let stack.
4008 SmallVector<LetRecord, 8> LetInfo;
4009 ParseLetList(LetInfo);
4010 if (LetInfo.empty()) return true;
4011 LetStack.push_back(std::move(LetInfo));
4013 if (!consume(tgtok::In))
4014 return TokError("expected 'in' at end of top-level 'let'");
4016 // If this is a scalar let, just handle it now
4017 if (Lex.getCode() != tgtok::l_brace) {
4018 // LET LetList IN Object
4019 if (ParseObject(CurMultiClass))
4020 return true;
4021 } else { // Object ::= LETCommand '{' ObjectList '}'
4022 SMLoc BraceLoc = Lex.getLoc();
4023 // Otherwise, this is a group let.
4024 Lex.Lex(); // eat the '{'.
4026 // A group let introduces a new scope for local variables.
4027 TGVarScope *LetScope = PushScope();
4029 // Parse the object list.
4030 if (ParseObjectList(CurMultiClass))
4031 return true;
4033 if (!consume(tgtok::r_brace)) {
4034 TokError("expected '}' at end of top level let command");
4035 return Error(BraceLoc, "to match this '{'");
4038 PopScope(LetScope);
4041 // Outside this let scope, this let block is not active.
4042 LetStack.pop_back();
4043 return false;
4046 /// ParseMultiClass - Parse a multiclass definition.
4048 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
4049 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
4050 /// MultiClassObject ::= Assert
4051 /// MultiClassObject ::= DefInst
4052 /// MultiClassObject ::= DefMInst
4053 /// MultiClassObject ::= Defvar
4054 /// MultiClassObject ::= Foreach
4055 /// MultiClassObject ::= If
4056 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
4057 /// MultiClassObject ::= LETCommand Object
4059 bool TGParser::ParseMultiClass() {
4060 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
4061 Lex.Lex(); // Eat the multiclass token.
4063 if (Lex.getCode() != tgtok::Id)
4064 return TokError("expected identifier after multiclass for name");
4065 std::string Name = Lex.getCurStrVal();
4067 auto Result =
4068 MultiClasses.insert(std::make_pair(Name,
4069 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
4071 if (!Result.second)
4072 return TokError("multiclass '" + Name + "' already defined");
4074 CurMultiClass = Result.first->second.get();
4075 Lex.Lex(); // Eat the identifier.
4077 // A multiclass body introduces a new scope for local variables.
4078 TGVarScope *MulticlassScope = PushScope(CurMultiClass);
4080 // If there are template args, parse them.
4081 if (Lex.getCode() == tgtok::less)
4082 if (ParseTemplateArgList(nullptr))
4083 return true;
4085 bool inherits = false;
4087 // If there are submulticlasses, parse them.
4088 if (consume(tgtok::colon)) {
4089 inherits = true;
4091 // Read all of the submulticlasses.
4092 SubMultiClassReference SubMultiClass =
4093 ParseSubMultiClassReference(CurMultiClass);
4094 while (true) {
4095 // Check for error.
4096 if (!SubMultiClass.MC) return true;
4098 // Add it.
4099 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
4100 return true;
4102 if (!consume(tgtok::comma))
4103 break;
4104 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
4108 if (Lex.getCode() != tgtok::l_brace) {
4109 if (!inherits)
4110 return TokError("expected '{' in multiclass definition");
4111 if (!consume(tgtok::semi))
4112 return TokError("expected ';' in multiclass definition");
4113 } else {
4114 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
4115 return TokError("multiclass must contain at least one def");
4117 while (Lex.getCode() != tgtok::r_brace) {
4118 switch (Lex.getCode()) {
4119 default:
4120 return TokError("expected 'assert', 'def', 'defm', 'defvar', 'dump', "
4121 "'foreach', 'if', or 'let' in multiclass body");
4123 case tgtok::Assert:
4124 case tgtok::Def:
4125 case tgtok::Defm:
4126 case tgtok::Defvar:
4127 case tgtok::Dump:
4128 case tgtok::Foreach:
4129 case tgtok::If:
4130 case tgtok::Let:
4131 if (ParseObject(CurMultiClass))
4132 return true;
4133 break;
4136 Lex.Lex(); // eat the '}'.
4138 // If we have a semicolon, print a gentle error.
4139 SMLoc SemiLoc = Lex.getLoc();
4140 if (consume(tgtok::semi)) {
4141 PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
4142 PrintNote("Semicolon ignored; remove to eliminate this error");
4146 if (!NoWarnOnUnusedTemplateArgs)
4147 CurMultiClass->Rec.checkUnusedTemplateArgs();
4149 PopScope(MulticlassScope);
4150 CurMultiClass = nullptr;
4151 return false;
4154 /// ParseDefm - Parse the instantiation of a multiclass.
4156 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
4158 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
4159 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
4160 Lex.Lex(); // eat the defm
4162 Init *DefmName = ParseObjectName(CurMultiClass);
4163 if (!DefmName)
4164 return true;
4165 if (isa<UnsetInit>(DefmName)) {
4166 DefmName = Records.getNewAnonymousName();
4167 if (CurMultiClass)
4168 DefmName = BinOpInit::getStrConcat(
4169 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
4170 StringRecTy::get(Records)),
4171 DefmName);
4174 if (Lex.getCode() != tgtok::colon)
4175 return TokError("expected ':' after defm identifier");
4177 // Keep track of the new generated record definitions.
4178 std::vector<RecordsEntry> NewEntries;
4180 // This record also inherits from a regular class (non-multiclass)?
4181 bool InheritFromClass = false;
4183 // eat the colon.
4184 Lex.Lex();
4186 SMLoc SubClassLoc = Lex.getLoc();
4187 SubClassReference Ref = ParseSubClassReference(nullptr, true);
4189 while (true) {
4190 if (!Ref.Rec) return true;
4192 // To instantiate a multiclass, we get the multiclass and then loop
4193 // through its template argument names. Substs contains a substitution
4194 // value for each argument, either the value specified or the default.
4195 // Then we can resolve the template arguments.
4196 MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
4197 assert(MC && "Didn't lookup multiclass correctly?");
4199 SubstStack Substs;
4200 if (resolveArgumentsOfMultiClass(Substs, MC, Ref.TemplateArgs, DefmName,
4201 SubClassLoc))
4202 return true;
4204 if (resolve(MC->Entries, Substs, !CurMultiClass && Loops.empty(),
4205 &NewEntries, &SubClassLoc))
4206 return true;
4208 if (!consume(tgtok::comma))
4209 break;
4211 if (Lex.getCode() != tgtok::Id)
4212 return TokError("expected identifier");
4214 SubClassLoc = Lex.getLoc();
4216 // A defm can inherit from regular classes (non-multiclasses) as
4217 // long as they come in the end of the inheritance list.
4218 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
4220 if (InheritFromClass)
4221 break;
4223 Ref = ParseSubClassReference(nullptr, true);
4226 if (InheritFromClass) {
4227 // Process all the classes to inherit as if they were part of a
4228 // regular 'def' and inherit all record values.
4229 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
4230 while (true) {
4231 // Check for error.
4232 if (!SubClass.Rec) return true;
4234 // Get the expanded definition prototypes and teach them about
4235 // the record values the current class to inherit has
4236 for (auto &E : NewEntries) {
4237 // Add it.
4238 if (AddSubClass(E, SubClass))
4239 return true;
4242 if (!consume(tgtok::comma))
4243 break;
4244 SubClass = ParseSubClassReference(nullptr, false);
4248 for (auto &E : NewEntries) {
4249 if (ApplyLetStack(E))
4250 return true;
4252 addEntry(std::move(E));
4255 if (!consume(tgtok::semi))
4256 return TokError("expected ';' at end of defm");
4258 return false;
4261 /// ParseObject
4262 /// Object ::= ClassInst
4263 /// Object ::= DefInst
4264 /// Object ::= MultiClassInst
4265 /// Object ::= DefMInst
4266 /// Object ::= LETCommand '{' ObjectList '}'
4267 /// Object ::= LETCommand Object
4268 /// Object ::= Defset
4269 /// Object ::= Defvar
4270 /// Object ::= Assert
4271 /// Object ::= Dump
4272 bool TGParser::ParseObject(MultiClass *MC) {
4273 switch (Lex.getCode()) {
4274 default:
4275 return TokError(
4276 "Expected assert, class, def, defm, defset, dump, foreach, if, or let");
4277 case tgtok::Assert: return ParseAssert(MC);
4278 case tgtok::Def: return ParseDef(MC);
4279 case tgtok::Defm: return ParseDefm(MC);
4280 case tgtok::Defvar: return ParseDefvar();
4281 case tgtok::Dump:
4282 return ParseDump(MC);
4283 case tgtok::Foreach: return ParseForeach(MC);
4284 case tgtok::If: return ParseIf(MC);
4285 case tgtok::Let: return ParseTopLevelLet(MC);
4286 case tgtok::Defset:
4287 if (MC)
4288 return TokError("defset is not allowed inside multiclass");
4289 return ParseDefset();
4290 case tgtok::Class:
4291 if (MC)
4292 return TokError("class is not allowed inside multiclass");
4293 if (!Loops.empty())
4294 return TokError("class is not allowed inside foreach loop");
4295 return ParseClass();
4296 case tgtok::MultiClass:
4297 if (!Loops.empty())
4298 return TokError("multiclass is not allowed inside foreach loop");
4299 return ParseMultiClass();
4303 /// ParseObjectList
4304 /// ObjectList :== Object*
4305 bool TGParser::ParseObjectList(MultiClass *MC) {
4306 while (tgtok::isObjectStart(Lex.getCode())) {
4307 if (ParseObject(MC))
4308 return true;
4310 return false;
4313 bool TGParser::ParseFile() {
4314 Lex.Lex(); // Prime the lexer.
4315 TGVarScope *GlobalScope = PushScope();
4316 if (ParseObjectList())
4317 return true;
4318 PopScope(GlobalScope);
4320 // If we have unread input at the end of the file, report it.
4321 if (Lex.getCode() == tgtok::Eof)
4322 return false;
4324 return TokError("Unexpected token at top level");
4327 // Check the types of the template argument values for a class
4328 // inheritance, multiclass invocation, or anonymous class invocation.
4329 // If necessary, replace an argument with a cast to the required type.
4330 // The argument count has already been checked.
4331 bool TGParser::CheckTemplateArgValues(
4332 SmallVectorImpl<llvm::ArgumentInit *> &Values, SMLoc Loc, Record *ArgsRec) {
4333 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
4335 for (unsigned I = 0, E = Values.size(); I < E; ++I) {
4336 auto *Value = Values[I];
4337 Init *ArgName = nullptr;
4338 if (Value->isPositional())
4339 ArgName = TArgs[Value->getIndex()];
4340 if (Value->isNamed())
4341 ArgName = Value->getName();
4343 RecordVal *Arg = ArgsRec->getValue(ArgName);
4344 RecTy *ArgType = Arg->getType();
4346 if (TypedInit *ArgValue = dyn_cast<TypedInit>(Value->getValue())) {
4347 auto *CastValue = ArgValue->getCastTo(ArgType);
4348 if (CastValue) {
4349 assert((!isa<TypedInit>(CastValue) ||
4350 cast<TypedInit>(CastValue)->getType()->typeIsA(ArgType)) &&
4351 "result of template arg value cast has wrong type");
4352 Values[I] = Value->cloneWithValue(CastValue);
4353 } else {
4354 PrintFatalError(Loc, "Value specified for template argument '" +
4355 Arg->getNameInitAsString() + "' is of type " +
4356 ArgValue->getType()->getAsString() +
4357 "; expected type " + ArgType->getAsString() +
4358 ": " + ArgValue->getAsString());
4363 return false;
4366 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4367 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
4368 if (Loop)
4369 Loop->dump();
4370 if (Rec)
4371 Rec->dump();
4374 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
4375 errs() << "foreach " << IterVar->getAsString() << " = "
4376 << ListValue->getAsString() << " in {\n";
4378 for (const auto &E : Entries)
4379 E.dump();
4381 errs() << "}\n";
4384 LLVM_DUMP_METHOD void MultiClass::dump() const {
4385 errs() << "Record:\n";
4386 Rec.dump();
4388 errs() << "Defs:\n";
4389 for (const auto &E : Entries)
4390 E.dump();
4392 #endif
4394 bool TGParser::ParseDump(MultiClass *CurMultiClass, Record *CurRec) {
4395 // Location of the `dump` statement.
4396 SMLoc Loc = Lex.getLoc();
4397 assert(Lex.getCode() == tgtok::Dump && "Unknown tok");
4398 Lex.Lex(); // eat the operation
4400 Init *Message = ParseValue(CurRec);
4401 if (!Message)
4402 return true;
4404 // Allow to use dump directly on `defvar` and `def`, by wrapping
4405 // them with a `!repl`.
4406 if (isa<DefInit>(Message))
4407 Message = UnOpInit::get(UnOpInit::REPR, Message, StringRecTy::get(Records))
4408 ->Fold(CurRec);
4410 if (!consume(tgtok::semi))
4411 return TokError("expected ';'");
4413 if (CurRec)
4414 CurRec->addDump(Loc, Message);
4415 else
4416 addEntry(std::make_unique<Record::DumpInfo>(Loc, Message));
4418 return false;