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