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