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