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