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