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