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