Bug Summary

File:llvm/lib/TableGen/TGParser.cpp
Warning:line 1774, column 38
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name TGParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/TableGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp
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/None.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringExtras.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 "llvm/TableGen/Record.h"
24#include <algorithm>
25#include <cassert>
26#include <cstdint>
27
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// Support Code for the Semantic Actions.
32//===----------------------------------------------------------------------===//
33
34namespace llvm {
35
36struct SubClassReference {
37 SMRange RefRange;
38 Record *Rec;
39 SmallVector<Init*, 4> TemplateArgs;
40
41 SubClassReference() : Rec(nullptr) {}
42
43 bool isInvalid() const { return Rec == nullptr; }
44};
45
46struct SubMultiClassReference {
47 SMRange RefRange;
48 MultiClass *MC;
49 SmallVector<Init*, 4> TemplateArgs;
50
51 SubMultiClassReference() : MC(nullptr) {}
52
53 bool isInvalid() const { return MC == nullptr; }
54 void dump() const;
55};
56
57#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) 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
71static 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
90static 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.getPrefix())
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.
114static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
115 Init *Name, StringRef Scoper) {
116 Init *NewName =
117 BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
118 NewName = BinOpInit::getStrConcat(NewName, Name);
119 if (CurMultiClass && Scoper != "::") {
120 Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
121 StringInit::get("::"));
122 NewName = BinOpInit::getStrConcat(Prefix, NewName);
123 }
124
125 if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
126 NewName = BinOp->Fold(&CurRec);
127 return NewName;
128}
129
130/// Return the qualified version of the implicit 'NAME' template argument.
131static Init *QualifiedNameOfImplicitName(Record &Rec,
132 MultiClass *MC = nullptr) {
133 return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
134}
135
136static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
137 return QualifiedNameOfImplicitName(MC->Rec, MC);
138}
139
140bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
141 if (!CurRec)
142 CurRec = &CurMultiClass->Rec;
143
144 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
145 // The value already exists in the class, treat this as a set.
146 if (ERV->setValue(RV.getValue()))
147 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
148 RV.getType()->getAsString() + "' is incompatible with " +
149 "previous definition of type '" +
150 ERV->getType()->getAsString() + "'");
151 } else {
152 CurRec->addValue(RV);
153 }
154 return false;
155}
156
157/// SetValue -
158/// Return true on error, false on success.
159bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
160 ArrayRef<unsigned> BitList, Init *V,
161 bool AllowSelfAssignment) {
162 if (!V) return false;
163
164 if (!CurRec) CurRec = &CurMultiClass->Rec;
165
166 RecordVal *RV = CurRec->getValue(ValName);
167 if (!RV)
168 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
169 "' unknown!");
170
171 // Do not allow assignments like 'X = X'. This will just cause infinite loops
172 // in the resolution machinery.
173 if (BitList.empty())
174 if (VarInit *VI = dyn_cast<VarInit>(V))
175 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
176 return Error(Loc, "Recursion / self-assignment forbidden");
177
178 // If we are assigning to a subset of the bits in the value... then we must be
179 // assigning to a field of BitsRecTy, which must have a BitsInit
180 // initializer.
181 //
182 if (!BitList.empty()) {
183 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
184 if (!CurVal)
185 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
186 "' is not a bits type");
187
188 // Convert the incoming value to a bits type of the appropriate size...
189 Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
190 if (!BI)
191 return Error(Loc, "Initializer is not compatible with bit range");
192
193 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
194
195 // Loop over bits, assigning values as appropriate.
196 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
197 unsigned Bit = BitList[i];
198 if (NewBits[Bit])
199 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
200 ValName->getAsUnquotedString() + "' more than once");
201 NewBits[Bit] = BI->getBit(i);
202 }
203
204 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
205 if (!NewBits[i])
206 NewBits[i] = CurVal->getBit(i);
207
208 V = BitsInit::get(NewBits);
209 }
210
211 if (RV->setValue(V)) {
212 std::string InitType;
213 if (BitsInit *BI = dyn_cast<BitsInit>(V))
214 InitType = (Twine("' of type bit initializer with length ") +
215 Twine(BI->getNumBits())).str();
216 else if (TypedInit *TI = dyn_cast<TypedInit>(V))
217 InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
218 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
219 "' of type '" + RV->getType()->getAsString() +
220 "' is incompatible with initializer '" +
221 V->getAsString() + InitType + "'");
222 }
223 return false;
224}
225
226/// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
227/// args as SubClass's template arguments.
228bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
229 Record *SC = SubClass.Rec;
230 // Add all of the values in the subclass into the current class.
231 for (const RecordVal &Val : SC->getValues())
232 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
233 return true;
234
235 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
236
237 // Ensure that an appropriate number of template arguments are specified.
238 if (TArgs.size() < SubClass.TemplateArgs.size())
239 return Error(SubClass.RefRange.Start,
240 "More template args specified than expected");
241
242 // Loop over all of the template arguments, setting them to the specified
243 // value or leaving them as the default if necessary.
244 MapResolver R(CurRec);
245
246 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
247 if (i < SubClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it now.
249 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
250 None, SubClass.TemplateArgs[i]))
251 return true;
252 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
253 return Error(SubClass.RefRange.Start,
254 "Value not specified for template argument #" +
255 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
256 ") of subclass '" + SC->getNameInitAsString() + "'!");
257 }
258
259 R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
260
261 CurRec->removeValue(TArgs[i]);
262 }
263
264 Init *Name;
265 if (CurRec->isClass())
266 Name =
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
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
291bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
292 if (Entry.Rec)
293 return AddSubClass(Entry.Rec.get(), SubClass);
294
295 for (auto &E : Entry.Loop->Entries) {
296 if (AddSubClass(E, SubClass))
297 return true;
298 }
299
300 return false;
301}
302
303/// AddSubMultiClass - Add SubMultiClass as a subclass to
304/// CurMC, resolving its template args as SubMultiClass's
305/// template arguments.
306bool TGParser::AddSubMultiClass(MultiClass *CurMC,
307 SubMultiClassReference &SubMultiClass) {
308 MultiClass *SMC = SubMultiClass.MC;
309
310 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
311 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
312 return Error(SubMultiClass.RefRange.Start,
313 "More template args specified than expected");
314
315 // Prepare the mapping of template argument name to value, filling in default
316 // values if necessary.
317 SubstStack TemplateArgs;
318 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
319 if (i < SubMultiClass.TemplateArgs.size()) {
320 TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
321 } else {
322 Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
323 if (!Default->isComplete()) {
324 return Error(SubMultiClass.RefRange.Start,
325 "value not specified for template argument #" + Twine(i) +
326 " (" + SMCTArgs[i]->getAsUnquotedString() +
327 ") of multiclass '" + SMC->Rec.getNameInitAsString() +
328 "'");
329 }
330 TemplateArgs.emplace_back(SMCTArgs[i], Default);
331 }
332 }
333
334 TemplateArgs.emplace_back(
335 QualifiedNameOfImplicitName(SMC),
336 VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
337
338 // Add all of the defs in the subclass into the current multiclass.
339 return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
340}
341
342/// Add a record or foreach loop to the current context (global record keeper,
343/// current inner-most foreach loop, or multiclass).
344bool TGParser::addEntry(RecordsEntry E) {
345 assert(!E.Rec || !E.Loop)((!E.Rec || !E.Loop) ? static_cast<void> (0) : __assert_fail
("!E.Rec || !E.Loop", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 345, __PRETTY_FUNCTION__))
;
346
347 if (!Loops.empty()) {
348 Loops.back()->Entries.push_back(std::move(E));
349 return false;
350 }
351
352 if (E.Loop) {
353 SubstStack Stack;
354 return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
355 CurMultiClass ? &CurMultiClass->Entries : nullptr);
356 }
357
358 if (CurMultiClass) {
359 CurMultiClass->Entries.push_back(std::move(E));
360 return false;
361 }
362
363 return addDefOne(std::move(E.Rec));
364}
365
366/// Resolve the entries in \p Loop, going over inner loops recursively
367/// and making the given subsitutions of (name, value) pairs.
368///
369/// The resulting records are stored in \p Dest if non-null. Otherwise, they
370/// are added to the global record keeper.
371bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
372 bool Final, std::vector<RecordsEntry> *Dest,
373 SMLoc *Loc) {
374 MapResolver R;
375 for (const auto &S : Substs)
376 R.set(S.first, S.second);
377 Init *List = Loop.ListValue->resolveReferences(R);
378 auto LI = dyn_cast<ListInit>(List);
379 if (!LI) {
380 if (!Final) {
381 Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
382 List));
383 return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
384 Loc);
385 }
386
387 PrintError(Loop.Loc, Twine("attempting to loop over '") +
388 List->getAsString() + "', expected a list");
389 return true;
390 }
391
392 bool Error = false;
393 for (auto Elt : *LI) {
394 Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
395 Error = resolve(Loop.Entries, Substs, Final, Dest);
396 Substs.pop_back();
397 if (Error)
398 break;
399 }
400 return Error;
401}
402
403/// Resolve the entries in \p Source, going over loops recursively and
404/// making the given substitutions of (name, value) pairs.
405///
406/// The resulting records are stored in \p Dest if non-null. Otherwise, they
407/// are added to the global record keeper.
408bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
409 SubstStack &Substs, bool Final,
410 std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
411 bool Error = false;
412 for (auto &E : Source) {
413 if (E.Loop) {
414 Error = resolve(*E.Loop, Substs, Final, Dest);
415 } else {
416 auto Rec = std::make_unique<Record>(*E.Rec);
417 if (Loc)
418 Rec->appendLoc(*Loc);
419
420 MapResolver R(Rec.get());
421 for (const auto &S : Substs)
422 R.set(S.first, S.second);
423 Rec->resolveReferences(R);
424
425 if (Dest)
426 Dest->push_back(std::move(Rec));
427 else
428 Error = addDefOne(std::move(Rec));
429 }
430 if (Error)
431 break;
432 }
433 return Error;
434}
435
436/// Resolve the record fully and add it to the record keeper.
437bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
438 if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
439 if (!Rec->isAnonymous()) {
440 PrintError(Rec->getLoc(),
441 "def already exists: " + Rec->getNameInitAsString());
442 PrintNote(Prev->getLoc(), "location of previous definition");
443 return true;
444 }
445 Rec->setName(Records.getNewAnonymousName());
446 }
447
448 Rec->resolveReferences();
449 checkConcrete(*Rec);
450
451 if (!isa<StringInit>(Rec->getNameInit())) {
452 PrintError(Rec->getLoc(), Twine("record name '") +
453 Rec->getNameInit()->getAsString() +
454 "' could not be fully resolved");
455 return true;
456 }
457
458 // If ObjectBody has template arguments, it's an error.
459 assert(Rec->getTemplateArgs().empty() && "How'd this get template args?")((Rec->getTemplateArgs().empty() && "How'd this get template args?"
) ? static_cast<void> (0) : __assert_fail ("Rec->getTemplateArgs().empty() && \"How'd this get template args?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 459, __PRETTY_FUNCTION__))
;
460
461 for (DefsetRecord *Defset : Defsets) {
462 DefInit *I = Rec->getDefInit();
463 if (!I->getType()->typeIsA(Defset->EltTy)) {
464 PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
465 I->getType()->getAsString() +
466 "' to defset");
467 PrintNote(Defset->Loc, "location of defset declaration");
468 return true;
469 }
470 Defset->Elements.push_back(I);
471 }
472
473 Records.addDef(std::move(Rec));
474 return false;
475}
476
477//===----------------------------------------------------------------------===//
478// Parser Code
479//===----------------------------------------------------------------------===//
480
481/// isObjectStart - Return true if this is a valid first token for an Object.
482static bool isObjectStart(tgtok::TokKind K) {
483 return K == tgtok::Class || K == tgtok::Def || K == tgtok::Defm ||
484 K == tgtok::Let || K == tgtok::MultiClass || K == tgtok::Foreach ||
485 K == tgtok::Defset;
486}
487
488/// ParseObjectName - If a valid object name is specified, return it. If no
489/// name is specified, return the unset initializer. Return nullptr on parse
490/// error.
491/// ObjectName ::= Value [ '#' Value ]*
492/// ObjectName ::= /*empty*/
493///
494Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
495 switch (Lex.getCode()) {
496 case tgtok::colon:
497 case tgtok::semi:
498 case tgtok::l_brace:
499 // These are all of the tokens that can begin an object body.
500 // Some of these can also begin values but we disallow those cases
501 // because they are unlikely to be useful.
502 return UnsetInit::get();
503 default:
504 break;
505 }
506
507 Record *CurRec = nullptr;
508 if (CurMultiClass)
509 CurRec = &CurMultiClass->Rec;
510
511 Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
512 if (!Name)
513 return nullptr;
514
515 if (CurMultiClass) {
516 Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
517 HasReferenceResolver R(NameStr);
518 Name->resolveReferences(R);
519 if (!R.found())
520 Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
521 Name);
522 }
523
524 return Name;
525}
526
527/// ParseClassID - Parse and resolve a reference to a class name. This returns
528/// null on error.
529///
530/// ClassID ::= ID
531///
532Record *TGParser::ParseClassID() {
533 if (Lex.getCode() != tgtok::Id) {
534 TokError("expected name for ClassID");
535 return nullptr;
536 }
537
538 Record *Result = Records.getClass(Lex.getCurStrVal());
539 if (!Result) {
540 std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
541 if (MultiClasses[Lex.getCurStrVal()].get())
542 TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
543 Lex.getCurStrVal() + "'");
544 else
545 TokError(Msg);
546 }
547
548 Lex.Lex();
549 return Result;
550}
551
552/// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
553/// This returns null on error.
554///
555/// MultiClassID ::= ID
556///
557MultiClass *TGParser::ParseMultiClassID() {
558 if (Lex.getCode() != tgtok::Id) {
559 TokError("expected name for MultiClassID");
560 return nullptr;
561 }
562
563 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
564 if (!Result)
565 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
566
567 Lex.Lex();
568 return Result;
569}
570
571/// ParseSubClassReference - Parse a reference to a subclass or to a templated
572/// subclass. This returns a SubClassRefTy with a null Record* on error.
573///
574/// SubClassRef ::= ClassID
575/// SubClassRef ::= ClassID '<' ValueList '>'
576///
577SubClassReference TGParser::
578ParseSubClassReference(Record *CurRec, bool isDefm) {
579 SubClassReference Result;
580 Result.RefRange.Start = Lex.getLoc();
581
582 if (isDefm) {
583 if (MultiClass *MC = ParseMultiClassID())
584 Result.Rec = &MC->Rec;
585 } else {
586 Result.Rec = ParseClassID();
587 }
588 if (!Result.Rec) return Result;
589
590 // If there is no template arg list, we're done.
591 if (Lex.getCode() != tgtok::less) {
592 Result.RefRange.End = Lex.getLoc();
593 return Result;
594 }
595 Lex.Lex(); // Eat the '<'
596
597 if (Lex.getCode() == tgtok::greater) {
598 TokError("subclass reference requires a non-empty list of template values");
599 Result.Rec = nullptr;
600 return Result;
601 }
602
603 ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
604 if (Result.TemplateArgs.empty()) {
605 Result.Rec = nullptr; // Error parsing value list.
606 return Result;
607 }
608
609 if (Lex.getCode() != tgtok::greater) {
610 TokError("expected '>' in template value list");
611 Result.Rec = nullptr;
612 return Result;
613 }
614 Lex.Lex();
615 Result.RefRange.End = Lex.getLoc();
616
617 return Result;
618}
619
620/// ParseSubMultiClassReference - Parse a reference to a subclass or to a
621/// templated submulticlass. This returns a SubMultiClassRefTy with a null
622/// Record* on error.
623///
624/// SubMultiClassRef ::= MultiClassID
625/// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
626///
627SubMultiClassReference TGParser::
628ParseSubMultiClassReference(MultiClass *CurMC) {
629 SubMultiClassReference Result;
630 Result.RefRange.Start = Lex.getLoc();
631
632 Result.MC = ParseMultiClassID();
633 if (!Result.MC) return Result;
634
635 // If there is no template arg list, we're done.
636 if (Lex.getCode() != tgtok::less) {
637 Result.RefRange.End = Lex.getLoc();
638 return Result;
639 }
640 Lex.Lex(); // Eat the '<'
641
642 if (Lex.getCode() == tgtok::greater) {
643 TokError("subclass reference requires a non-empty list of template values");
644 Result.MC = nullptr;
645 return Result;
646 }
647
648 ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
649 if (Result.TemplateArgs.empty()) {
650 Result.MC = nullptr; // Error parsing value list.
651 return Result;
652 }
653
654 if (Lex.getCode() != tgtok::greater) {
655 TokError("expected '>' in template value list");
656 Result.MC = nullptr;
657 return Result;
658 }
659 Lex.Lex();
660 Result.RefRange.End = Lex.getLoc();
661
662 return Result;
663}
664
665/// ParseRangePiece - Parse a bit/value range.
666/// RangePiece ::= INTVAL
667/// RangePiece ::= INTVAL '-' INTVAL
668/// RangePiece ::= INTVAL INTVAL
669bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
670 TypedInit *FirstItem) {
671 Init *CurVal = FirstItem;
672 if (!CurVal)
673 CurVal = ParseValue(nullptr);
674
675 IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
676 if (!II)
677 return TokError("expected integer or bitrange");
678
679 int64_t Start = II->getValue();
680 int64_t End;
681
682 if (Start < 0)
683 return TokError("invalid range, cannot be negative");
684
685 switch (Lex.getCode()) {
686 default:
687 Ranges.push_back(Start);
688 return false;
689 case tgtok::minus: {
690 Lex.Lex(); // eat
691
692 Init *I_End = ParseValue(nullptr);
693 IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
694 if (!II_End) {
695 TokError("expected integer value as end of range");
696 return true;
697 }
698
699 End = II_End->getValue();
700 break;
701 }
702 case tgtok::IntVal: {
703 End = -Lex.getCurIntVal();
704 Lex.Lex();
705 break;
706 }
707 }
708 if (End < 0)
709 return TokError("invalid range, cannot be negative");
710
711 // Add to the range.
712 if (Start < End)
713 for (; Start <= End; ++Start)
714 Ranges.push_back(Start);
715 else
716 for (; Start >= End; --Start)
717 Ranges.push_back(Start);
718 return false;
719}
720
721/// ParseRangeList - Parse a list of scalars and ranges into scalar values.
722///
723/// RangeList ::= RangePiece (',' RangePiece)*
724///
725void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
726 // Parse the first piece.
727 if (ParseRangePiece(Result)) {
728 Result.clear();
729 return;
730 }
731 while (Lex.getCode() == tgtok::comma) {
732 Lex.Lex(); // Eat the comma.
733
734 // Parse the next range piece.
735 if (ParseRangePiece(Result)) {
736 Result.clear();
737 return;
738 }
739 }
740}
741
742/// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
743/// OptionalRangeList ::= '<' RangeList '>'
744/// OptionalRangeList ::= /*empty*/
745bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
746 if (Lex.getCode() != tgtok::less)
747 return false;
748
749 SMLoc StartLoc = Lex.getLoc();
750 Lex.Lex(); // eat the '<'
751
752 // Parse the range list.
753 ParseRangeList(Ranges);
754 if (Ranges.empty()) return true;
755
756 if (Lex.getCode() != tgtok::greater) {
757 TokError("expected '>' at end of range list");
758 return Error(StartLoc, "to match this '<'");
759 }
760 Lex.Lex(); // eat the '>'.
761 return false;
762}
763
764/// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
765/// OptionalBitList ::= '{' RangeList '}'
766/// OptionalBitList ::= /*empty*/
767bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
768 if (Lex.getCode() != tgtok::l_brace)
769 return false;
770
771 SMLoc StartLoc = Lex.getLoc();
772 Lex.Lex(); // eat the '{'
773
774 // Parse the range list.
775 ParseRangeList(Ranges);
776 if (Ranges.empty()) return true;
777
778 if (Lex.getCode() != tgtok::r_brace) {
779 TokError("expected '}' at end of bit list");
780 return Error(StartLoc, "to match this '{'");
781 }
782 Lex.Lex(); // eat the '}'.
783 return false;
784}
785
786/// ParseType - Parse and return a tblgen type. This returns null on error.
787///
788/// Type ::= STRING // string type
789/// Type ::= CODE // code type
790/// Type ::= BIT // bit type
791/// Type ::= BITS '<' INTVAL '>' // bits<x> type
792/// Type ::= INT // int type
793/// Type ::= LIST '<' Type '>' // list<x> type
794/// Type ::= DAG // dag type
795/// Type ::= ClassID // Record Type
796///
797RecTy *TGParser::ParseType() {
798 switch (Lex.getCode()) {
799 default: TokError("Unknown token when expecting a type"); return nullptr;
800 case tgtok::String: Lex.Lex(); return StringRecTy::get();
801 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
802 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
803 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
804 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
805 case tgtok::Id:
806 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
807 TokError("unknown class name");
808 return nullptr;
809 case tgtok::Bits: {
810 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
811 TokError("expected '<' after bits type");
812 return nullptr;
813 }
814 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
815 TokError("expected integer in bits<n> type");
816 return nullptr;
817 }
818 uint64_t Val = Lex.getCurIntVal();
819 if (Lex.Lex() != tgtok::greater) { // Eat count.
820 TokError("expected '>' at end of bits<n> type");
821 return nullptr;
822 }
823 Lex.Lex(); // Eat '>'
824 return BitsRecTy::get(Val);
825 }
826 case tgtok::List: {
827 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
828 TokError("expected '<' after list type");
829 return nullptr;
830 }
831 Lex.Lex(); // Eat '<'
832 RecTy *SubType = ParseType();
833 if (!SubType) return nullptr;
834
835 if (Lex.getCode() != tgtok::greater) {
836 TokError("expected '>' at end of list<ty> type");
837 return nullptr;
838 }
839 Lex.Lex(); // Eat '>'
840 return ListRecTy::get(SubType);
841 }
842 }
843}
844
845/// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
846/// has already been read.
847Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
848 IDParseMode Mode) {
849 if (CurRec) {
850 if (const RecordVal *RV = CurRec->getValue(Name))
851 return VarInit::get(Name, RV->getType());
852 }
853
854 if ((CurRec && CurRec->isClass()) || CurMultiClass) {
855 Init *TemplateArgName;
856 if (CurMultiClass) {
857 TemplateArgName =
858 QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
859 } else
860 TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
861
862 Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
863 if (TemplateRec->isTemplateArg(TemplateArgName)) {
864 const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
865 assert(RV && "Template arg doesn't exist??")((RV && "Template arg doesn't exist??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template arg doesn't exist??\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 865, __PRETTY_FUNCTION__))
;
866 return VarInit::get(TemplateArgName, RV->getType());
867 } else if (Name->getValue() == "NAME") {
868 return VarInit::get(TemplateArgName, StringRecTy::get());
869 }
870 }
871
872 // If this is in a foreach loop, make sure it's not a loop iterator
873 for (const auto &L : Loops) {
874 VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
875 if (IterVar && IterVar->getNameInit() == Name)
876 return IterVar;
877 }
878
879 if (Mode == ParseNameMode)
880 return Name;
881
882 if (Init *I = Records.getGlobal(Name->getValue()))
883 return I;
884
885 // Allow self-references of concrete defs, but delay the lookup so that we
886 // get the correct type.
887 if (CurRec && !CurRec->isClass() && !CurMultiClass &&
888 CurRec->getNameInit() == Name)
889 return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
890
891 Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
892 return nullptr;
893}
894
895/// ParseOperation - Parse an operator. This returns null on error.
896///
897/// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
898///
899Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
900 switch (Lex.getCode()) {
1
Control jumps to 'case XCond:' at line 1543
901 default:
902 TokError("unknown operation");
903 return nullptr;
904 case tgtok::XHead:
905 case tgtok::XTail:
906 case tgtok::XSize:
907 case tgtok::XEmpty:
908 case tgtok::XCast:
909 case tgtok::XGetOp: { // Value ::= !unop '(' Value ')'
910 UnOpInit::UnaryOp Code;
911 RecTy *Type = nullptr;
912
913 switch (Lex.getCode()) {
914 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 914)
;
915 case tgtok::XCast:
916 Lex.Lex(); // eat the operation
917 Code = UnOpInit::CAST;
918
919 Type = ParseOperatorType();
920
921 if (!Type) {
922 TokError("did not get type for unary operator");
923 return nullptr;
924 }
925
926 break;
927 case tgtok::XHead:
928 Lex.Lex(); // eat the operation
929 Code = UnOpInit::HEAD;
930 break;
931 case tgtok::XTail:
932 Lex.Lex(); // eat the operation
933 Code = UnOpInit::TAIL;
934 break;
935 case tgtok::XSize:
936 Lex.Lex();
937 Code = UnOpInit::SIZE;
938 Type = IntRecTy::get();
939 break;
940 case tgtok::XEmpty:
941 Lex.Lex(); // eat the operation
942 Code = UnOpInit::EMPTY;
943 Type = IntRecTy::get();
944 break;
945 case tgtok::XGetOp:
946 Lex.Lex(); // eat the operation
947 if (Lex.getCode() == tgtok::less) {
948 // Parse an optional type suffix, so that you can say
949 // !getop<BaseClass>(someDag) as a shorthand for
950 // !cast<BaseClass>(!getop(someDag)).
951 Type = ParseOperatorType();
952
953 if (!Type) {
954 TokError("did not get type for unary operator");
955 return nullptr;
956 }
957
958 if (!isa<RecordRecTy>(Type)) {
959 TokError("type for !getop must be a record type");
960 // but keep parsing, to consume the operand
961 }
962 } else {
963 Type = RecordRecTy::get({});
964 }
965 Code = UnOpInit::GETOP;
966 break;
967 }
968 if (Lex.getCode() != tgtok::l_paren) {
969 TokError("expected '(' after unary operator");
970 return nullptr;
971 }
972 Lex.Lex(); // eat the '('
973
974 Init *LHS = ParseValue(CurRec);
975 if (!LHS) return nullptr;
976
977 if (Code == UnOpInit::HEAD ||
978 Code == UnOpInit::TAIL ||
979 Code == UnOpInit::EMPTY) {
980 ListInit *LHSl = dyn_cast<ListInit>(LHS);
981 StringInit *LHSs = dyn_cast<StringInit>(LHS);
982 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
983 if (!LHSl && !LHSs && !LHSt) {
984 TokError("expected list or string type argument in unary operator");
985 return nullptr;
986 }
987 if (LHSt) {
988 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
989 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
990 if (!LType && !SType) {
991 TokError("expected list or string type argument in unary operator");
992 return nullptr;
993 }
994 }
995
996 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL ||
997 Code == UnOpInit::SIZE) {
998 if (!LHSl && !LHSt) {
999 TokError("expected list type argument in unary operator");
1000 return nullptr;
1001 }
1002 }
1003
1004 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
1005 if (LHSl && LHSl->empty()) {
1006 TokError("empty list argument in unary operator");
1007 return nullptr;
1008 }
1009 if (LHSl) {
1010 Init *Item = LHSl->getElement(0);
1011 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
1012 if (!Itemt) {
1013 TokError("untyped list element in unary operator");
1014 return nullptr;
1015 }
1016 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
1017 : ListRecTy::get(Itemt->getType());
1018 } else {
1019 assert(LHSt && "expected list type argument in unary operator")((LHSt && "expected list type argument in unary operator"
) ? static_cast<void> (0) : __assert_fail ("LHSt && \"expected list type argument in unary operator\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1019, __PRETTY_FUNCTION__))
;
1020 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
1021 if (!LType) {
1022 TokError("expected list type argument in unary operator");
1023 return nullptr;
1024 }
1025 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
1026 }
1027 }
1028 }
1029
1030 if (Lex.getCode() != tgtok::r_paren) {
1031 TokError("expected ')' in unary operator");
1032 return nullptr;
1033 }
1034 Lex.Lex(); // eat the ')'
1035 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
1036 }
1037
1038 case tgtok::XIsA: {
1039 // Value ::= !isa '<' Type '>' '(' Value ')'
1040 Lex.Lex(); // eat the operation
1041
1042 RecTy *Type = ParseOperatorType();
1043 if (!Type)
1044 return nullptr;
1045
1046 if (Lex.getCode() != tgtok::l_paren) {
1047 TokError("expected '(' after type of !isa");
1048 return nullptr;
1049 }
1050 Lex.Lex(); // eat the '('
1051
1052 Init *LHS = ParseValue(CurRec);
1053 if (!LHS)
1054 return nullptr;
1055
1056 if (Lex.getCode() != tgtok::r_paren) {
1057 TokError("expected ')' in !isa");
1058 return nullptr;
1059 }
1060 Lex.Lex(); // eat the ')'
1061
1062 return (IsAOpInit::get(Type, LHS))->Fold();
1063 }
1064
1065 case tgtok::XConcat:
1066 case tgtok::XADD:
1067 case tgtok::XMUL:
1068 case tgtok::XAND:
1069 case tgtok::XOR:
1070 case tgtok::XSRA:
1071 case tgtok::XSRL:
1072 case tgtok::XSHL:
1073 case tgtok::XEq:
1074 case tgtok::XNe:
1075 case tgtok::XLe:
1076 case tgtok::XLt:
1077 case tgtok::XGe:
1078 case tgtok::XGt:
1079 case tgtok::XListConcat:
1080 case tgtok::XListSplat:
1081 case tgtok::XStrConcat:
1082 case tgtok::XSetOp: { // Value ::= !binop '(' Value ',' Value ')'
1083 tgtok::TokKind OpTok = Lex.getCode();
1084 SMLoc OpLoc = Lex.getLoc();
1085 Lex.Lex(); // eat the operation
1086
1087 BinOpInit::BinaryOp Code;
1088 switch (OpTok) {
1089 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1089)
;
1090 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1091 case tgtok::XADD: Code = BinOpInit::ADD; break;
1092 case tgtok::XMUL: Code = BinOpInit::MUL; break;
1093 case tgtok::XAND: Code = BinOpInit::AND; break;
1094 case tgtok::XOR: Code = BinOpInit::OR; break;
1095 case tgtok::XSRA: Code = BinOpInit::SRA; break;
1096 case tgtok::XSRL: Code = BinOpInit::SRL; break;
1097 case tgtok::XSHL: Code = BinOpInit::SHL; break;
1098 case tgtok::XEq: Code = BinOpInit::EQ; break;
1099 case tgtok::XNe: Code = BinOpInit::NE; break;
1100 case tgtok::XLe: Code = BinOpInit::LE; break;
1101 case tgtok::XLt: Code = BinOpInit::LT; break;
1102 case tgtok::XGe: Code = BinOpInit::GE; break;
1103 case tgtok::XGt: Code = BinOpInit::GT; break;
1104 case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1105 case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
1106 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1107 case tgtok::XSetOp: Code = BinOpInit::SETOP; break;
1108 }
1109
1110 RecTy *Type = nullptr;
1111 RecTy *ArgType = nullptr;
1112 switch (OpTok) {
1113 default:
1114 llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1114)
;
1115 case tgtok::XConcat:
1116 case tgtok::XSetOp:
1117 Type = DagRecTy::get();
1118 ArgType = DagRecTy::get();
1119 break;
1120 case tgtok::XAND:
1121 case tgtok::XOR:
1122 case tgtok::XSRA:
1123 case tgtok::XSRL:
1124 case tgtok::XSHL:
1125 case tgtok::XADD:
1126 case tgtok::XMUL:
1127 Type = IntRecTy::get();
1128 ArgType = IntRecTy::get();
1129 break;
1130 case tgtok::XEq:
1131 case tgtok::XNe:
1132 Type = BitRecTy::get();
1133 // ArgType for Eq / Ne is not known at this point
1134 break;
1135 case tgtok::XLe:
1136 case tgtok::XLt:
1137 case tgtok::XGe:
1138 case tgtok::XGt:
1139 Type = BitRecTy::get();
1140 ArgType = IntRecTy::get();
1141 break;
1142 case tgtok::XListConcat:
1143 // We don't know the list type until we parse the first argument
1144 ArgType = ItemType;
1145 break;
1146 case tgtok::XListSplat:
1147 // Can't do any typechecking until we parse the first argument.
1148 break;
1149 case tgtok::XStrConcat:
1150 Type = StringRecTy::get();
1151 ArgType = StringRecTy::get();
1152 break;
1153 }
1154
1155 if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1156 Error(OpLoc, Twine("expected value of type '") +
1157 ItemType->getAsString() + "', got '" +
1158 Type->getAsString() + "'");
1159 return nullptr;
1160 }
1161
1162 if (Lex.getCode() != tgtok::l_paren) {
1163 TokError("expected '(' after binary operator");
1164 return nullptr;
1165 }
1166 Lex.Lex(); // eat the '('
1167
1168 SmallVector<Init*, 2> InitList;
1169
1170 for (;;) {
1171 SMLoc InitLoc = Lex.getLoc();
1172 InitList.push_back(ParseValue(CurRec, ArgType));
1173 if (!InitList.back()) return nullptr;
1174
1175 RecTy *ListType = cast<TypedInit>(InitList.back())->getType();
1176 if (!ArgType) {
1177 ArgType = ListType;
1178
1179 switch (Code) {
1180 case BinOpInit::LISTCONCAT:
1181 if (!isa<ListRecTy>(ArgType)) {
1182 Error(InitLoc, Twine("expected a list, got value of type '") +
1183 ArgType->getAsString() + "'");
1184 return nullptr;
1185 }
1186 break;
1187 case BinOpInit::LISTSPLAT:
1188 if (ItemType && InitList.size() == 1) {
1189 if (!isa<ListRecTy>(ItemType)) {
1190 Error(OpLoc,
1191 Twine("expected output type to be a list, got type '") +
1192 ItemType->getAsString() + "'");
1193 return nullptr;
1194 }
1195 if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
1196 Error(OpLoc, Twine("expected first arg type to be '") +
1197 ArgType->getAsString() +
1198 "', got value of type '" +
1199 cast<ListRecTy>(ItemType)
1200 ->getElementType()
1201 ->getAsString() +
1202 "'");
1203 return nullptr;
1204 }
1205 }
1206 if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
1207 Error(InitLoc, Twine("expected second parameter to be an int, got "
1208 "value of type '") +
1209 ArgType->getAsString() + "'");
1210 return nullptr;
1211 }
1212 ArgType = nullptr; // Broken invariant: types not identical.
1213 break;
1214 case BinOpInit::EQ:
1215 case BinOpInit::NE:
1216 if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1217 !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1218 Error(InitLoc, Twine("expected int, bits, or string; got value of "
1219 "type '") + ArgType->getAsString() + "'");
1220 return nullptr;
1221 }
1222 break;
1223 default: llvm_unreachable("other ops have fixed argument types")::llvm::llvm_unreachable_internal("other ops have fixed argument types"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1223)
;
1224 }
1225 } else {
1226 RecTy *Resolved = resolveTypes(ArgType, ListType);
1227 if (!Resolved) {
1228 Error(InitLoc, Twine("expected value of type '") +
1229 ArgType->getAsString() + "', got '" +
1230 ListType->getAsString() + "'");
1231 return nullptr;
1232 }
1233 if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1234 Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1235 Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1236 Code != BinOpInit::MUL)
1237 ArgType = Resolved;
1238 }
1239
1240 // Deal with BinOps whose arguments have different types, by
1241 // rewriting ArgType in between them.
1242 switch (Code) {
1243 case BinOpInit::SETOP:
1244 // After parsing the first dag argument, switch to expecting
1245 // a record, with no restriction on its superclasses.
1246 ArgType = RecordRecTy::get({});
1247 break;
1248 default:
1249 break;
1250 }
1251
1252 if (Lex.getCode() != tgtok::comma)
1253 break;
1254 Lex.Lex(); // eat the ','
1255 }
1256
1257 if (Lex.getCode() != tgtok::r_paren) {
1258 TokError("expected ')' in operator");
1259 return nullptr;
1260 }
1261 Lex.Lex(); // eat the ')'
1262
1263 // listconcat returns a list with type of the argument.
1264 if (Code == BinOpInit::LISTCONCAT)
1265 Type = ArgType;
1266 // listsplat returns a list of type of the *first* argument.
1267 if (Code == BinOpInit::LISTSPLAT)
1268 Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
1269
1270 // We allow multiple operands to associative operators like !strconcat as
1271 // shorthand for nesting them.
1272 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1273 Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1274 Code == BinOpInit::AND || Code == BinOpInit::OR ||
1275 Code == BinOpInit::MUL) {
1276 while (InitList.size() > 2) {
1277 Init *RHS = InitList.pop_back_val();
1278 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1279 InitList.back() = RHS;
1280 }
1281 }
1282
1283 if (InitList.size() == 2)
1284 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1285 ->Fold(CurRec);
1286
1287 Error(OpLoc, "expected two operands to operator");
1288 return nullptr;
1289 }
1290
1291 case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1292 SMLoc OpLoc = Lex.getLoc();
1293 Lex.Lex(); // eat the operation
1294 if (Lex.getCode() != tgtok::l_paren) {
1295 TokError("expected '(' after !foreach");
1296 return nullptr;
1297 }
1298
1299 if (Lex.Lex() != tgtok::Id) { // eat the '('
1300 TokError("first argument of !foreach must be an identifier");
1301 return nullptr;
1302 }
1303
1304 Init *LHS = StringInit::get(Lex.getCurStrVal());
1305
1306 if (CurRec && CurRec->getValue(LHS)) {
1307 TokError((Twine("iteration variable '") + LHS->getAsString() +
1308 "' already defined")
1309 .str());
1310 return nullptr;
1311 }
1312
1313 if (Lex.Lex() != tgtok::comma) { // eat the id
1314 TokError("expected ',' in ternary operator");
1315 return nullptr;
1316 }
1317 Lex.Lex(); // eat the ','
1318
1319 Init *MHS = ParseValue(CurRec);
1320 if (!MHS)
1321 return nullptr;
1322
1323 if (Lex.getCode() != tgtok::comma) {
1324 TokError("expected ',' in ternary operator");
1325 return nullptr;
1326 }
1327 Lex.Lex(); // eat the ','
1328
1329 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1330 if (!MHSt) {
1331 TokError("could not get type of !foreach input");
1332 return nullptr;
1333 }
1334
1335 RecTy *InEltType = nullptr;
1336 RecTy *OutEltType = nullptr;
1337 bool IsDAG = false;
1338
1339 if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1340 InEltType = InListTy->getElementType();
1341 if (ItemType) {
1342 if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1343 OutEltType = OutListTy->getElementType();
1344 } else {
1345 Error(OpLoc,
1346 "expected value of type '" + Twine(ItemType->getAsString()) +
1347 "', but got !foreach of list type");
1348 return nullptr;
1349 }
1350 }
1351 } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1352 InEltType = InDagTy;
1353 if (ItemType && !isa<DagRecTy>(ItemType)) {
1354 Error(OpLoc,
1355 "expected value of type '" + Twine(ItemType->getAsString()) +
1356 "', but got !foreach of dag type");
1357 return nullptr;
1358 }
1359 IsDAG = true;
1360 } else {
1361 TokError("!foreach must have list or dag input");
1362 return nullptr;
1363 }
1364
1365 // We need to create a temporary record to provide a scope for the iteration
1366 // variable while parsing top-level foreach's.
1367 std::unique_ptr<Record> ParseRecTmp;
1368 Record *ParseRec = CurRec;
1369 if (!ParseRec) {
1370 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1371 ParseRec = ParseRecTmp.get();
1372 }
1373
1374 ParseRec->addValue(RecordVal(LHS, InEltType, false));
1375 Init *RHS = ParseValue(ParseRec, OutEltType);
1376 ParseRec->removeValue(LHS);
1377 if (!RHS)
1378 return nullptr;
1379
1380 if (Lex.getCode() != tgtok::r_paren) {
1381 TokError("expected ')' in binary operator");
1382 return nullptr;
1383 }
1384 Lex.Lex(); // eat the ')'
1385
1386 RecTy *OutType;
1387 if (IsDAG) {
1388 OutType = InEltType;
1389 } else {
1390 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1391 if (!RHSt) {
1392 TokError("could not get type of !foreach result");
1393 return nullptr;
1394 }
1395 OutType = RHSt->getType()->getListTy();
1396 }
1397
1398 return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1399 ->Fold(CurRec);
1400 }
1401
1402 case tgtok::XDag:
1403 case tgtok::XIf:
1404 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1405 TernOpInit::TernaryOp Code;
1406 RecTy *Type = nullptr;
1407
1408 tgtok::TokKind LexCode = Lex.getCode();
1409 Lex.Lex(); // eat the operation
1410 switch (LexCode) {
1411 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1411)
;
1412 case tgtok::XDag:
1413 Code = TernOpInit::DAG;
1414 Type = DagRecTy::get();
1415 ItemType = nullptr;
1416 break;
1417 case tgtok::XIf:
1418 Code = TernOpInit::IF;
1419 break;
1420 case tgtok::XSubst:
1421 Code = TernOpInit::SUBST;
1422 break;
1423 }
1424 if (Lex.getCode() != tgtok::l_paren) {
1425 TokError("expected '(' after ternary operator");
1426 return nullptr;
1427 }
1428 Lex.Lex(); // eat the '('
1429
1430 Init *LHS = ParseValue(CurRec);
1431 if (!LHS) return nullptr;
1432
1433 if (Lex.getCode() != tgtok::comma) {
1434 TokError("expected ',' in ternary operator");
1435 return nullptr;
1436 }
1437 Lex.Lex(); // eat the ','
1438
1439 SMLoc MHSLoc = Lex.getLoc();
1440 Init *MHS = ParseValue(CurRec, ItemType);
1441 if (!MHS)
1442 return nullptr;
1443
1444 if (Lex.getCode() != tgtok::comma) {
1445 TokError("expected ',' in ternary operator");
1446 return nullptr;
1447 }
1448 Lex.Lex(); // eat the ','
1449
1450 SMLoc RHSLoc = Lex.getLoc();
1451 Init *RHS = ParseValue(CurRec, ItemType);
1452 if (!RHS)
1453 return nullptr;
1454
1455 if (Lex.getCode() != tgtok::r_paren) {
1456 TokError("expected ')' in binary operator");
1457 return nullptr;
1458 }
1459 Lex.Lex(); // eat the ')'
1460
1461 switch (LexCode) {
1462 default: llvm_unreachable("Unhandled code!")::llvm::llvm_unreachable_internal("Unhandled code!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 1462)
;
1463 case tgtok::XDag: {
1464 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1465 if (!MHSt && !isa<UnsetInit>(MHS)) {
1466 Error(MHSLoc, "could not determine type of the child list in !dag");
1467 return nullptr;
1468 }
1469 if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1470 Error(MHSLoc, Twine("expected list of children, got type '") +
1471 MHSt->getType()->getAsString() + "'");
1472 return nullptr;
1473 }
1474
1475 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1476 if (!RHSt && !isa<UnsetInit>(RHS)) {
1477 Error(RHSLoc, "could not determine type of the name list in !dag");
1478 return nullptr;
1479 }
1480 if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1481 Error(RHSLoc, Twine("expected list<string>, got type '") +
1482 RHSt->getType()->getAsString() + "'");
1483 return nullptr;
1484 }
1485
1486 if (!MHSt && !RHSt) {
1487 Error(MHSLoc,
1488 "cannot have both unset children and unset names in !dag");
1489 return nullptr;
1490 }
1491 break;
1492 }
1493 case tgtok::XIf: {
1494 RecTy *MHSTy = nullptr;
1495 RecTy *RHSTy = nullptr;
1496
1497 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1498 MHSTy = MHSt->getType();
1499 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1500 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1501 if (isa<BitInit>(MHS))
1502 MHSTy = BitRecTy::get();
1503
1504 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1505 RHSTy = RHSt->getType();
1506 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1507 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1508 if (isa<BitInit>(RHS))
1509 RHSTy = BitRecTy::get();
1510
1511 // For UnsetInit, it's typed from the other hand.
1512 if (isa<UnsetInit>(MHS))
1513 MHSTy = RHSTy;
1514 if (isa<UnsetInit>(RHS))
1515 RHSTy = MHSTy;
1516
1517 if (!MHSTy || !RHSTy) {
1518 TokError("could not get type for !if");
1519 return nullptr;
1520 }
1521
1522 Type = resolveTypes(MHSTy, RHSTy);
1523 if (!Type) {
1524 TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1525 "' and '" + RHSTy->getAsString() + "' for !if");
1526 return nullptr;
1527 }
1528 break;
1529 }
1530 case tgtok::XSubst: {
1531 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1532 if (!RHSt) {
1533 TokError("could not get type for !subst");
1534 return nullptr;
1535 }
1536 Type = RHSt->getType();
1537 break;
1538 }
1539 }
1540 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1541 }
1542
1543 case tgtok::XCond:
1544 return ParseOperationCond(CurRec, ItemType);
2
Calling 'TGParser::ParseOperationCond'
1545
1546 case tgtok::XFoldl: {
1547 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1548 Lex.Lex(); // eat the operation
1549 if (Lex.getCode() != tgtok::l_paren) {
1550 TokError("expected '(' after !foldl");
1551 return nullptr;
1552 }
1553 Lex.Lex(); // eat the '('
1554
1555 Init *StartUntyped = ParseValue(CurRec);
1556 if (!StartUntyped)
1557 return nullptr;
1558
1559 TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1560 if (!Start) {
1561 TokError(Twine("could not get type of !foldl start: '") +
1562 StartUntyped->getAsString() + "'");
1563 return nullptr;
1564 }
1565
1566 if (Lex.getCode() != tgtok::comma) {
1567 TokError("expected ',' in !foldl");
1568 return nullptr;
1569 }
1570 Lex.Lex(); // eat the ','
1571
1572 Init *ListUntyped = ParseValue(CurRec);
1573 if (!ListUntyped)
1574 return nullptr;
1575
1576 TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1577 if (!List) {
1578 TokError(Twine("could not get type of !foldl list: '") +
1579 ListUntyped->getAsString() + "'");
1580 return nullptr;
1581 }
1582
1583 ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1584 if (!ListType) {
1585 TokError(Twine("!foldl list must be a list, but is of type '") +
1586 List->getType()->getAsString());
1587 return nullptr;
1588 }
1589
1590 if (Lex.getCode() != tgtok::comma) {
1591 TokError("expected ',' in !foldl");
1592 return nullptr;
1593 }
1594
1595 if (Lex.Lex() != tgtok::Id) { // eat the ','
1596 TokError("third argument of !foldl must be an identifier");
1597 return nullptr;
1598 }
1599
1600 Init *A = StringInit::get(Lex.getCurStrVal());
1601 if (CurRec && CurRec->getValue(A)) {
1602 TokError((Twine("left !foldl variable '") + A->getAsString() +
1603 "' already defined")
1604 .str());
1605 return nullptr;
1606 }
1607
1608 if (Lex.Lex() != tgtok::comma) { // eat the id
1609 TokError("expected ',' in !foldl");
1610 return nullptr;
1611 }
1612
1613 if (Lex.Lex() != tgtok::Id) { // eat the ','
1614 TokError("fourth argument of !foldl must be an identifier");
1615 return nullptr;
1616 }
1617
1618 Init *B = StringInit::get(Lex.getCurStrVal());
1619 if (CurRec && CurRec->getValue(B)) {
1620 TokError((Twine("right !foldl variable '") + B->getAsString() +
1621 "' already defined")
1622 .str());
1623 return nullptr;
1624 }
1625
1626 if (Lex.Lex() != tgtok::comma) { // eat the id
1627 TokError("expected ',' in !foldl");
1628 return nullptr;
1629 }
1630 Lex.Lex(); // eat the ','
1631
1632 // We need to create a temporary record to provide a scope for the iteration
1633 // variable while parsing top-level foreach's.
1634 std::unique_ptr<Record> ParseRecTmp;
1635 Record *ParseRec = CurRec;
1636 if (!ParseRec) {
1637 ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1638 ParseRec = ParseRecTmp.get();
1639 }
1640
1641 ParseRec->addValue(RecordVal(A, Start->getType(), false));
1642 ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1643 Init *ExprUntyped = ParseValue(ParseRec);
1644 ParseRec->removeValue(A);
1645 ParseRec->removeValue(B);
1646 if (!ExprUntyped)
1647 return nullptr;
1648
1649 TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1650 if (!Expr) {
1651 TokError("could not get type of !foldl expression");
1652 return nullptr;
1653 }
1654
1655 if (Expr->getType() != Start->getType()) {
1656 TokError(Twine("!foldl expression must be of same type as start (") +
1657 Start->getType()->getAsString() + "), but is of type " +
1658 Expr->getType()->getAsString());
1659 return nullptr;
1660 }
1661
1662 if (Lex.getCode() != tgtok::r_paren) {
1663 TokError("expected ')' in fold operator");
1664 return nullptr;
1665 }
1666 Lex.Lex(); // eat the ')'
1667
1668 return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1669 ->Fold(CurRec);
1670 }
1671 }
1672}
1673
1674/// ParseOperatorType - Parse a type for an operator. This returns
1675/// null on error.
1676///
1677/// OperatorType ::= '<' Type '>'
1678///
1679RecTy *TGParser::ParseOperatorType() {
1680 RecTy *Type = nullptr;
1681
1682 if (Lex.getCode() != tgtok::less) {
1683 TokError("expected type name for operator");
1684 return nullptr;
1685 }
1686 Lex.Lex(); // eat the <
1687
1688 Type = ParseType();
1689
1690 if (!Type) {
1691 TokError("expected type name for operator");
1692 return nullptr;
1693 }
1694
1695 if (Lex.getCode() != tgtok::greater) {
1696 TokError("expected type name for operator");
1697 return nullptr;
1698 }
1699 Lex.Lex(); // eat the >
1700
1701 return Type;
1702}
1703
1704Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1705 Lex.Lex(); // eat the operation 'cond'
1706
1707 if (Lex.getCode() != tgtok::l_paren) {
3
Assuming the condition is false
4
Taking false branch
1708 TokError("expected '(' after !cond operator");
1709 return nullptr;
1710 }
1711 Lex.Lex(); // eat the '('
1712
1713 // Parse through '[Case: Val,]+'
1714 SmallVector<Init *, 4> Case;
1715 SmallVector<Init *, 4> Val;
1716 while (true) {
5
Loop condition is true. Entering loop body
1717 if (Lex.getCode() == tgtok::r_paren) {
6
Assuming the condition is false
7
Taking false branch
1718 Lex.Lex(); // eat the ')'
1719 break;
1720 }
1721
1722 Init *V = ParseValue(CurRec);
1723 if (!V)
8
Assuming 'V' is non-null
9
Taking false branch
1724 return nullptr;
1725 Case.push_back(V);
1726
1727 if (Lex.getCode() != tgtok::colon) {
10
Assuming the condition is false
11
Taking false branch
1728 TokError("expected ':' following a condition in !cond operator");
1729 return nullptr;
1730 }
1731 Lex.Lex(); // eat the ':'
1732
1733 V = ParseValue(CurRec, ItemType);
1734 if (!V)
12
Assuming 'V' is non-null
13
Taking false branch
1735 return nullptr;
1736 Val.push_back(V);
1737
1738 if (Lex.getCode() == tgtok::r_paren) {
14
Assuming the condition is true
15
Taking true branch
1739 Lex.Lex(); // eat the ')'
1740 break;
16
Execution continues on line 1750
1741 }
1742
1743 if (Lex.getCode() != tgtok::comma) {
1744 TokError("expected ',' or ')' following a value in !cond operator");
1745 return nullptr;
1746 }
1747 Lex.Lex(); // eat the ','
1748 }
1749
1750 if (Case.size() < 1) {
17
Assuming the condition is false
18
Taking false branch
1751 TokError("there should be at least 1 'condition : value' in the !cond operator");
1752 return nullptr;
1753 }
1754
1755 // resolve type
1756 RecTy *Type = nullptr;
1757 for (Init *V : Val) {
19
Assuming '__begin1' is not equal to '__end1'
1758 RecTy *VTy = nullptr;
29
'VTy' initialized to a null pointer value
1759 if (TypedInit *Vt
20.1
'Vt' is null
30.1
'Vt' is null
= dyn_cast<TypedInit>(V))
20
Assuming 'V' is not a 'TypedInit'
21
Taking false branch
30
Assuming 'V' is not a 'TypedInit'
31
Taking false branch
1760 VTy = Vt->getType();
1761 if (BitsInit *Vbits
22.1
'Vbits' is non-null
32.1
'Vbits' is null
= dyn_cast<BitsInit>(V))
22
Assuming 'V' is a 'BitsInit'
23
Taking true branch
32
Assuming 'V' is not a 'BitsInit'
33
Taking false branch
1762 VTy = BitsRecTy::get(Vbits->getNumBits());
1763 if (isa<BitInit>(V))
24
Assuming 'V' is not a 'BitInit'
25
Taking false branch
34
'V' is not a 'BitInit'
35
Taking false branch
1764 VTy = BitRecTy::get();
1765
1766 if (Type == nullptr) {
26
Taking true branch
36
Assuming the condition is false
37
Taking false branch
1767 if (!isa<UnsetInit>(V))
27
Assuming 'V' is not a 'UnsetInit'
28
Taking true branch
1768 Type = VTy;
1769 } else {
1770 if (!isa<UnsetInit>(V)) {
38
'V' is not a 'UnsetInit'
39
Taking true branch
1771 RecTy *RType = resolveTypes(Type, VTy);
1772 if (!RType) {
40
Assuming 'RType' is null
41
Taking true branch
1773 TokError(Twine("inconsistent types '") + Type->getAsString() +
1774 "' and '" + VTy->getAsString() + "' for !cond");
42
Called C++ object pointer is null
1775 return nullptr;
1776 }
1777 Type = RType;
1778 }
1779 }
1780 }
1781
1782 if (!Type) {
1783 TokError("could not determine type for !cond from its arguments");
1784 return nullptr;
1785 }
1786 return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1787}
1788
1789/// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1790///
1791/// SimpleValue ::= IDValue
1792/// SimpleValue ::= INTVAL
1793/// SimpleValue ::= STRVAL+
1794/// SimpleValue ::= CODEFRAGMENT
1795/// SimpleValue ::= '?'
1796/// SimpleValue ::= '{' ValueList '}'
1797/// SimpleValue ::= ID '<' ValueListNE '>'
1798/// SimpleValue ::= '[' ValueList ']'
1799/// SimpleValue ::= '(' IDValue DagArgList ')'
1800/// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1801/// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1802/// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1803/// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1804/// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1805/// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1806/// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
1807/// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1808/// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1809///
1810Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1811 IDParseMode Mode) {
1812 Init *R = nullptr;
1813 switch (Lex.getCode()) {
1814 default: TokError("Unknown token when parsing a value"); break;
1815 case tgtok::paste:
1816 // This is a leading paste operation. This is deprecated but
1817 // still exists in some .td files. Ignore it.
1818 Lex.Lex(); // Skip '#'.
1819 return ParseSimpleValue(CurRec, ItemType, Mode);
1820 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1821 case tgtok::BinaryIntVal: {
1822 auto BinaryVal = Lex.getCurBinaryIntVal();
1823 SmallVector<Init*, 16> Bits(BinaryVal.second);
1824 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1825 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1826 R = BitsInit::get(Bits);
1827 Lex.Lex();
1828 break;
1829 }
1830 case tgtok::StrVal: {
1831 std::string Val = Lex.getCurStrVal();
1832 Lex.Lex();
1833
1834 // Handle multiple consecutive concatenated strings.
1835 while (Lex.getCode() == tgtok::StrVal) {
1836 Val += Lex.getCurStrVal();
1837 Lex.Lex();
1838 }
1839
1840 R = StringInit::get(Val);
1841 break;
1842 }
1843 case tgtok::CodeFragment:
1844 R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1845 Lex.Lex();
1846 break;
1847 case tgtok::question:
1848 R = UnsetInit::get();
1849 Lex.Lex();
1850 break;
1851 case tgtok::Id: {
1852 SMLoc NameLoc = Lex.getLoc();
1853 StringInit *Name = StringInit::get(Lex.getCurStrVal());
1854 if (Lex.Lex() != tgtok::less) // consume the Id.
1855 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1856
1857 // Value ::= ID '<' ValueListNE '>'
1858 if (Lex.Lex() == tgtok::greater) {
1859 TokError("expected non-empty value list");
1860 return nullptr;
1861 }
1862
1863 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1864 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1865 // body.
1866 Record *Class = Records.getClass(Name->getValue());
1867 if (!Class) {
1868 Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1869 return nullptr;
1870 }
1871
1872 SmallVector<Init *, 8> Args;
1873 ParseValueList(Args, CurRec, Class);
1874 if (Args.empty()) return nullptr;
1875
1876 if (Lex.getCode() != tgtok::greater) {
1877 TokError("expected '>' at end of value list");
1878 return nullptr;
1879 }
1880 Lex.Lex(); // eat the '>'
1881
1882 // Typecheck the template arguments list
1883 ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1884 if (ExpectedArgs.size() < Args.size()) {
1885 Error(NameLoc,
1886 "More template args specified than expected");
1887 return nullptr;
1888 }
1889
1890 for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1891 RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1892 if (i < Args.size()) {
1893 if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1894 RecTy *ExpectedType = ExpectedArg->getType();
1895 if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1896 Error(NameLoc,
1897 "Value specified for template argument #" + Twine(i) + " (" +
1898 ExpectedArg->getNameInitAsString() + ") is of type '" +
1899 TI->getType()->getAsString() + "', expected '" +
1900 ExpectedType->getAsString() + "': " + TI->getAsString());
1901 return nullptr;
1902 }
1903 continue;
1904 }
1905 } else if (ExpectedArg->getValue()->isComplete())
1906 continue;
1907
1908 Error(NameLoc,
1909 "Value not specified for template argument #" + Twine(i) + " (" +
1910 ExpectedArgs[i]->getAsUnquotedString() + ")");
1911 return nullptr;
1912 }
1913
1914 return VarDefInit::get(Class, Args)->Fold();
1915 }
1916 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1917 SMLoc BraceLoc = Lex.getLoc();
1918 Lex.Lex(); // eat the '{'
1919 SmallVector<Init*, 16> Vals;
1920
1921 if (Lex.getCode() != tgtok::r_brace) {
1922 ParseValueList(Vals, CurRec);
1923 if (Vals.empty()) return nullptr;
1924 }
1925 if (Lex.getCode() != tgtok::r_brace) {
1926 TokError("expected '}' at end of bit list value");
1927 return nullptr;
1928 }
1929 Lex.Lex(); // eat the '}'
1930
1931 SmallVector<Init *, 16> NewBits;
1932
1933 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1934 // first. We'll first read everything in to a vector, then we can reverse
1935 // it to get the bits in the correct order for the BitsInit value.
1936 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1937 // FIXME: The following two loops would not be duplicated
1938 // if the API was a little more orthogonal.
1939
1940 // bits<n> values are allowed to initialize n bits.
1941 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1942 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1943 NewBits.push_back(BI->getBit((e - i) - 1));
1944 continue;
1945 }
1946 // bits<n> can also come from variable initializers.
1947 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1948 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1949 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1950 NewBits.push_back(VI->getBit((e - i) - 1));
1951 continue;
1952 }
1953 // Fallthrough to try convert this to a bit.
1954 }
1955 // All other values must be convertible to just a single bit.
1956 Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1957 if (!Bit) {
1958 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1959 ") is not convertable to a bit");
1960 return nullptr;
1961 }
1962 NewBits.push_back(Bit);
1963 }
1964 std::reverse(NewBits.begin(), NewBits.end());
1965 return BitsInit::get(NewBits);
1966 }
1967 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1968 Lex.Lex(); // eat the '['
1969 SmallVector<Init*, 16> Vals;
1970
1971 RecTy *DeducedEltTy = nullptr;
1972 ListRecTy *GivenListTy = nullptr;
1973
1974 if (ItemType) {
1975 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1976 if (!ListType) {
1977 TokError(Twine("Type mismatch for list, expected list type, got ") +
1978 ItemType->getAsString());
1979 return nullptr;
1980 }
1981 GivenListTy = ListType;
1982 }
1983
1984 if (Lex.getCode() != tgtok::r_square) {
1985 ParseValueList(Vals, CurRec, nullptr,
1986 GivenListTy ? GivenListTy->getElementType() : nullptr);
1987 if (Vals.empty()) return nullptr;
1988 }
1989 if (Lex.getCode() != tgtok::r_square) {
1990 TokError("expected ']' at end of list value");
1991 return nullptr;
1992 }
1993 Lex.Lex(); // eat the ']'
1994
1995 RecTy *GivenEltTy = nullptr;
1996 if (Lex.getCode() == tgtok::less) {
1997 // Optional list element type
1998 Lex.Lex(); // eat the '<'
1999
2000 GivenEltTy = ParseType();
2001 if (!GivenEltTy) {
2002 // Couldn't parse element type
2003 return nullptr;
2004 }
2005
2006 if (Lex.getCode() != tgtok::greater) {
2007 TokError("expected '>' at end of list element type");
2008 return nullptr;
2009 }
2010 Lex.Lex(); // eat the '>'
2011 }
2012
2013 // Check elements
2014 RecTy *EltTy = nullptr;
2015 for (Init *V : Vals) {
2016 TypedInit *TArg = dyn_cast<TypedInit>(V);
2017 if (TArg) {
2018 if (EltTy) {
2019 EltTy = resolveTypes(EltTy, TArg->getType());
2020 if (!EltTy) {
2021 TokError("Incompatible types in list elements");
2022 return nullptr;
2023 }
2024 } else {
2025 EltTy = TArg->getType();
2026 }
2027 }
2028 }
2029
2030 if (GivenEltTy) {
2031 if (EltTy) {
2032 // Verify consistency
2033 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
2034 TokError("Incompatible types in list elements");
2035 return nullptr;
2036 }
2037 }
2038 EltTy = GivenEltTy;
2039 }
2040
2041 if (!EltTy) {
2042 if (!ItemType) {
2043 TokError("No type for list");
2044 return nullptr;
2045 }
2046 DeducedEltTy = GivenListTy->getElementType();
2047 } else {
2048 // Make sure the deduced type is compatible with the given type
2049 if (GivenListTy) {
2050 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
2051 TokError(Twine("Element type mismatch for list: element type '") +
2052 EltTy->getAsString() + "' not convertible to '" +
2053 GivenListTy->getElementType()->getAsString());
2054 return nullptr;
2055 }
2056 }
2057 DeducedEltTy = EltTy;
2058 }
2059
2060 return ListInit::get(Vals, DeducedEltTy);
2061 }
2062 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
2063 Lex.Lex(); // eat the '('
2064 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
2065 Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetOp) {
2066 TokError("expected identifier in dag init");
2067 return nullptr;
2068 }
2069
2070 Init *Operator = ParseValue(CurRec);
2071 if (!Operator) return nullptr;
2072
2073 // If the operator name is present, parse it.
2074 StringInit *OperatorName = nullptr;
2075 if (Lex.getCode() == tgtok::colon) {
2076 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2077 TokError("expected variable name in dag operator");
2078 return nullptr;
2079 }
2080 OperatorName = StringInit::get(Lex.getCurStrVal());
2081 Lex.Lex(); // eat the VarName.
2082 }
2083
2084 SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
2085 if (Lex.getCode() != tgtok::r_paren) {
2086 ParseDagArgList(DagArgs, CurRec);
2087 if (DagArgs.empty()) return nullptr;
2088 }
2089
2090 if (Lex.getCode() != tgtok::r_paren) {
2091 TokError("expected ')' in dag init");
2092 return nullptr;
2093 }
2094 Lex.Lex(); // eat the ')'
2095
2096 return DagInit::get(Operator, OperatorName, DagArgs);
2097 }
2098
2099 case tgtok::XHead:
2100 case tgtok::XTail:
2101 case tgtok::XSize:
2102 case tgtok::XEmpty:
2103 case tgtok::XCast:
2104 case tgtok::XGetOp: // Value ::= !unop '(' Value ')'
2105 case tgtok::XIsA:
2106 case tgtok::XConcat:
2107 case tgtok::XDag:
2108 case tgtok::XADD:
2109 case tgtok::XMUL:
2110 case tgtok::XAND:
2111 case tgtok::XOR:
2112 case tgtok::XSRA:
2113 case tgtok::XSRL:
2114 case tgtok::XSHL:
2115 case tgtok::XEq:
2116 case tgtok::XNe:
2117 case tgtok::XLe:
2118 case tgtok::XLt:
2119 case tgtok::XGe:
2120 case tgtok::XGt:
2121 case tgtok::XListConcat:
2122 case tgtok::XListSplat:
2123 case tgtok::XStrConcat:
2124 case tgtok::XSetOp: // Value ::= !binop '(' Value ',' Value ')'
2125 case tgtok::XIf:
2126 case tgtok::XCond:
2127 case tgtok::XFoldl:
2128 case tgtok::XForEach:
2129 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2130 return ParseOperation(CurRec, ItemType);
2131 }
2132 }
2133
2134 return R;
2135}
2136
2137/// ParseValue - Parse a tblgen value. This returns null on error.
2138///
2139/// Value ::= SimpleValue ValueSuffix*
2140/// ValueSuffix ::= '{' BitList '}'
2141/// ValueSuffix ::= '[' BitList ']'
2142/// ValueSuffix ::= '.' ID
2143///
2144Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2145 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2146 if (!Result) return nullptr;
2147
2148 // Parse the suffixes now if present.
2149 while (true) {
2150 switch (Lex.getCode()) {
2151 default: return Result;
2152 case tgtok::l_brace: {
2153 if (Mode == ParseNameMode)
2154 // This is the beginning of the object body.
2155 return Result;
2156
2157 SMLoc CurlyLoc = Lex.getLoc();
2158 Lex.Lex(); // eat the '{'
2159 SmallVector<unsigned, 16> Ranges;
2160 ParseRangeList(Ranges);
2161 if (Ranges.empty()) return nullptr;
2162
2163 // Reverse the bitlist.
2164 std::reverse(Ranges.begin(), Ranges.end());
2165 Result = Result->convertInitializerBitRange(Ranges);
2166 if (!Result) {
2167 Error(CurlyLoc, "Invalid bit range for value");
2168 return nullptr;
2169 }
2170
2171 // Eat the '}'.
2172 if (Lex.getCode() != tgtok::r_brace) {
2173 TokError("expected '}' at end of bit range list");
2174 return nullptr;
2175 }
2176 Lex.Lex();
2177 break;
2178 }
2179 case tgtok::l_square: {
2180 SMLoc SquareLoc = Lex.getLoc();
2181 Lex.Lex(); // eat the '['
2182 SmallVector<unsigned, 16> Ranges;
2183 ParseRangeList(Ranges);
2184 if (Ranges.empty()) return nullptr;
2185
2186 Result = Result->convertInitListSlice(Ranges);
2187 if (!Result) {
2188 Error(SquareLoc, "Invalid range for list slice");
2189 return nullptr;
2190 }
2191
2192 // Eat the ']'.
2193 if (Lex.getCode() != tgtok::r_square) {
2194 TokError("expected ']' at end of list slice");
2195 return nullptr;
2196 }
2197 Lex.Lex();
2198 break;
2199 }
2200 case tgtok::period: {
2201 if (Lex.Lex() != tgtok::Id) { // eat the .
2202 TokError("expected field identifier after '.'");
2203 return nullptr;
2204 }
2205 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2206 if (!Result->getFieldType(FieldName)) {
2207 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2208 Result->getAsString() + "'");
2209 return nullptr;
2210 }
2211 Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2212 Lex.Lex(); // eat field name
2213 break;
2214 }
2215
2216 case tgtok::paste:
2217 SMLoc PasteLoc = Lex.getLoc();
2218 TypedInit *LHS = dyn_cast<TypedInit>(Result);
2219 if (!LHS) {
2220 Error(PasteLoc, "LHS of paste is not typed!");
2221 return nullptr;
2222 }
2223
2224 // Check if it's a 'listA # listB'
2225 if (isa<ListRecTy>(LHS->getType())) {
2226 Lex.Lex(); // Eat the '#'.
2227
2228 switch (Lex.getCode()) {
2229 case tgtok::colon:
2230 case tgtok::semi:
2231 case tgtok::l_brace:
2232 Result = LHS; // trailing paste, ignore.
2233 break;
2234 default:
2235 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2236 Result = BinOpInit::getListConcat(LHS, RHSResult);
2237 }
2238 break;
2239 }
2240
2241 // Create a !strconcat() operation, first casting each operand to
2242 // a string if necessary.
2243 if (LHS->getType() != StringRecTy::get()) {
2244 auto CastLHS = dyn_cast<TypedInit>(
2245 UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2246 ->Fold(CurRec));
2247 if (!CastLHS) {
2248 Error(PasteLoc,
2249 Twine("can't cast '") + LHS->getAsString() + "' to string");
2250 return nullptr;
2251 }
2252 LHS = CastLHS;
2253 }
2254
2255 TypedInit *RHS = nullptr;
2256
2257 Lex.Lex(); // Eat the '#'.
2258 switch (Lex.getCode()) {
2259 case tgtok::colon:
2260 case tgtok::semi:
2261 case tgtok::l_brace:
2262 // These are all of the tokens that can begin an object body.
2263 // Some of these can also begin values but we disallow those cases
2264 // because they are unlikely to be useful.
2265
2266 // Trailing paste, concat with an empty string.
2267 RHS = StringInit::get("");
2268 break;
2269
2270 default:
2271 Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2272 RHS = dyn_cast<TypedInit>(RHSResult);
2273 if (!RHS) {
2274 Error(PasteLoc, "RHS of paste is not typed!");
2275 return nullptr;
2276 }
2277
2278 if (RHS->getType() != StringRecTy::get()) {
2279 auto CastRHS = dyn_cast<TypedInit>(
2280 UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2281 ->Fold(CurRec));
2282 if (!CastRHS) {
2283 Error(PasteLoc,
2284 Twine("can't cast '") + RHS->getAsString() + "' to string");
2285 return nullptr;
2286 }
2287 RHS = CastRHS;
2288 }
2289
2290 break;
2291 }
2292
2293 Result = BinOpInit::getStrConcat(LHS, RHS);
2294 break;
2295 }
2296 }
2297}
2298
2299/// ParseDagArgList - Parse the argument list for a dag literal expression.
2300///
2301/// DagArg ::= Value (':' VARNAME)?
2302/// DagArg ::= VARNAME
2303/// DagArgList ::= DagArg
2304/// DagArgList ::= DagArgList ',' DagArg
2305void TGParser::ParseDagArgList(
2306 SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2307 Record *CurRec) {
2308
2309 while (true) {
2310 // DagArg ::= VARNAME
2311 if (Lex.getCode() == tgtok::VarName) {
2312 // A missing value is treated like '?'.
2313 StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2314 Result.emplace_back(UnsetInit::get(), VarName);
2315 Lex.Lex();
2316 } else {
2317 // DagArg ::= Value (':' VARNAME)?
2318 Init *Val = ParseValue(CurRec);
2319 if (!Val) {
2320 Result.clear();
2321 return;
2322 }
2323
2324 // If the variable name is present, add it.
2325 StringInit *VarName = nullptr;
2326 if (Lex.getCode() == tgtok::colon) {
2327 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2328 TokError("expected variable name in dag literal");
2329 Result.clear();
2330 return;
2331 }
2332 VarName = StringInit::get(Lex.getCurStrVal());
2333 Lex.Lex(); // eat the VarName.
2334 }
2335
2336 Result.push_back(std::make_pair(Val, VarName));
2337 }
2338 if (Lex.getCode() != tgtok::comma) break;
2339 Lex.Lex(); // eat the ','
2340 }
2341}
2342
2343/// ParseValueList - Parse a comma separated list of values, returning them as a
2344/// vector. Note that this always expects to be able to parse at least one
2345/// value. It returns an empty list if this is not possible.
2346///
2347/// ValueList ::= Value (',' Value)
2348///
2349void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2350 Record *ArgsRec, RecTy *EltTy) {
2351 RecTy *ItemType = EltTy;
2352 unsigned int ArgN = 0;
2353 if (ArgsRec && !EltTy) {
2354 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2355 if (TArgs.empty()) {
2356 TokError("template argument provided to non-template class");
2357 Result.clear();
2358 return;
2359 }
2360 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2361 if (!RV) {
2362 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2363 << ")\n";
2364 }
2365 assert(RV && "Template argument record not found??")((RV && "Template argument record not found??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2365, __PRETTY_FUNCTION__))
;
2366 ItemType = RV->getType();
2367 ++ArgN;
2368 }
2369 Result.push_back(ParseValue(CurRec, ItemType));
2370 if (!Result.back()) {
2371 Result.clear();
2372 return;
2373 }
2374
2375 while (Lex.getCode() == tgtok::comma) {
2376 Lex.Lex(); // Eat the comma
2377
2378 // ignore trailing comma for lists
2379 if (Lex.getCode() == tgtok::r_square)
2380 return;
2381
2382 if (ArgsRec && !EltTy) {
2383 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2384 if (ArgN >= TArgs.size()) {
2385 TokError("too many template arguments");
2386 Result.clear();
2387 return;
2388 }
2389 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2390 assert(RV && "Template argument record not found??")((RV && "Template argument record not found??") ? static_cast
<void> (0) : __assert_fail ("RV && \"Template argument record not found??\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2390, __PRETTY_FUNCTION__))
;
2391 ItemType = RV->getType();
2392 ++ArgN;
2393 }
2394 Result.push_back(ParseValue(CurRec, ItemType));
2395 if (!Result.back()) {
2396 Result.clear();
2397 return;
2398 }
2399 }
2400}
2401
2402/// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2403/// empty string on error. This can happen in a number of different context's,
2404/// including within a def or in the template args for a def (which which case
2405/// CurRec will be non-null) and within the template args for a multiclass (in
2406/// which case CurRec will be null, but CurMultiClass will be set). This can
2407/// also happen within a def that is within a multiclass, which will set both
2408/// CurRec and CurMultiClass.
2409///
2410/// Declaration ::= FIELD? Type ID ('=' Value)?
2411///
2412Init *TGParser::ParseDeclaration(Record *CurRec,
2413 bool ParsingTemplateArgs) {
2414 // Read the field prefix if present.
2415 bool HasField = Lex.getCode() == tgtok::Field;
2416 if (HasField) Lex.Lex();
2417
2418 RecTy *Type = ParseType();
2419 if (!Type) return nullptr;
2420
2421 if (Lex.getCode() != tgtok::Id) {
2422 TokError("Expected identifier in declaration");
2423 return nullptr;
2424 }
2425
2426 std::string Str = Lex.getCurStrVal();
2427 if (Str == "NAME") {
2428 TokError("'" + Str + "' is a reserved variable name");
2429 return nullptr;
2430 }
2431
2432 SMLoc IdLoc = Lex.getLoc();
2433 Init *DeclName = StringInit::get(Str);
2434 Lex.Lex();
2435
2436 if (ParsingTemplateArgs) {
2437 if (CurRec)
2438 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2439 else
2440 assert(CurMultiClass)((CurMultiClass) ? static_cast<void> (0) : __assert_fail
("CurMultiClass", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2440, __PRETTY_FUNCTION__))
;
2441 if (CurMultiClass)
2442 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2443 "::");
2444 }
2445
2446 // Add the value.
2447 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2448 return nullptr;
2449
2450 // If a value is present, parse it.
2451 if (Lex.getCode() == tgtok::equal) {
2452 Lex.Lex();
2453 SMLoc ValLoc = Lex.getLoc();
2454 Init *Val = ParseValue(CurRec, Type);
2455 if (!Val ||
2456 SetValue(CurRec, ValLoc, DeclName, None, Val))
2457 // Return the name, even if an error is thrown. This is so that we can
2458 // continue to make some progress, even without the value having been
2459 // initialized.
2460 return DeclName;
2461 }
2462
2463 return DeclName;
2464}
2465
2466/// ParseForeachDeclaration - Read a foreach declaration, returning
2467/// the name of the declared object or a NULL Init on error. Return
2468/// the name of the parsed initializer list through ForeachListName.
2469///
2470/// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2471/// ForeachDeclaration ::= ID '=' RangePiece
2472/// ForeachDeclaration ::= ID '=' Value
2473///
2474VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2475 if (Lex.getCode() != tgtok::Id) {
2476 TokError("Expected identifier in foreach declaration");
2477 return nullptr;
2478 }
2479
2480 Init *DeclName = StringInit::get(Lex.getCurStrVal());
2481 Lex.Lex();
2482
2483 // If a value is present, parse it.
2484 if (Lex.getCode() != tgtok::equal) {
2485 TokError("Expected '=' in foreach declaration");
2486 return nullptr;
2487 }
2488 Lex.Lex(); // Eat the '='
2489
2490 RecTy *IterType = nullptr;
2491 SmallVector<unsigned, 16> Ranges;
2492
2493 switch (Lex.getCode()) {
2494 case tgtok::l_brace: { // '{' RangeList '}'
2495 Lex.Lex(); // eat the '{'
2496 ParseRangeList(Ranges);
2497 if (Lex.getCode() != tgtok::r_brace) {
2498 TokError("expected '}' at end of bit range list");
2499 return nullptr;
2500 }
2501 Lex.Lex();
2502 break;
2503 }
2504
2505 default: {
2506 SMLoc ValueLoc = Lex.getLoc();
2507 Init *I = ParseValue(nullptr);
2508 if (!I)
2509 return nullptr;
2510
2511 TypedInit *TI = dyn_cast<TypedInit>(I);
2512 if (TI && isa<ListRecTy>(TI->getType())) {
2513 ForeachListValue = I;
2514 IterType = cast<ListRecTy>(TI->getType())->getElementType();
2515 break;
2516 }
2517
2518 if (TI) {
2519 if (ParseRangePiece(Ranges, TI))
2520 return nullptr;
2521 break;
2522 }
2523
2524 std::string Type;
2525 if (TI)
2526 Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2527 Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2528 if (CurMultiClass) {
2529 PrintNote({}, "references to multiclass template arguments cannot be "
2530 "resolved at this time");
2531 }
2532 return nullptr;
2533 }
2534 }
2535
2536
2537 if (!Ranges.empty()) {
2538 assert(!IterType && "Type already initialized?")((!IterType && "Type already initialized?") ? static_cast
<void> (0) : __assert_fail ("!IterType && \"Type already initialized?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2538, __PRETTY_FUNCTION__))
;
2539 IterType = IntRecTy::get();
2540 std::vector<Init*> Values;
2541 for (unsigned R : Ranges)
2542 Values.push_back(IntInit::get(R));
2543 ForeachListValue = ListInit::get(Values, IterType);
2544 }
2545
2546 if (!IterType)
2547 return nullptr;
2548
2549 return VarInit::get(DeclName, IterType);
2550}
2551
2552/// ParseTemplateArgList - Read a template argument list, which is a non-empty
2553/// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2554/// template args for a def, which may or may not be in a multiclass. If null,
2555/// these are the template args for a multiclass.
2556///
2557/// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2558///
2559bool TGParser::ParseTemplateArgList(Record *CurRec) {
2560 assert(Lex.getCode() == tgtok::less && "Not a template arg list!")((Lex.getCode() == tgtok::less && "Not a template arg list!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::less && \"Not a template arg list!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2560, __PRETTY_FUNCTION__))
;
2561 Lex.Lex(); // eat the '<'
2562
2563 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2564
2565 // Read the first declaration.
2566 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2567 if (!TemplArg)
2568 return true;
2569
2570 TheRecToAddTo->addTemplateArg(TemplArg);
2571
2572 while (Lex.getCode() == tgtok::comma) {
2573 Lex.Lex(); // eat the ','
2574
2575 // Read the following declarations.
2576 SMLoc Loc = Lex.getLoc();
2577 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2578 if (!TemplArg)
2579 return true;
2580
2581 if (TheRecToAddTo->isTemplateArg(TemplArg))
2582 return Error(Loc, "template argument with the same name has already been "
2583 "defined");
2584
2585 TheRecToAddTo->addTemplateArg(TemplArg);
2586 }
2587
2588 if (Lex.getCode() != tgtok::greater)
2589 return TokError("expected '>' at end of template argument list");
2590 Lex.Lex(); // eat the '>'.
2591 return false;
2592}
2593
2594/// ParseBodyItem - Parse a single item at within the body of a def or class.
2595///
2596/// BodyItem ::= Declaration ';'
2597/// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2598bool TGParser::ParseBodyItem(Record *CurRec) {
2599 if (Lex.getCode() != tgtok::Let) {
2600 if (!ParseDeclaration(CurRec, false))
2601 return true;
2602
2603 if (Lex.getCode() != tgtok::semi)
2604 return TokError("expected ';' after declaration");
2605 Lex.Lex();
2606 return false;
2607 }
2608
2609 // LET ID OptionalRangeList '=' Value ';'
2610 if (Lex.Lex() != tgtok::Id)
2611 return TokError("expected field identifier after let");
2612
2613 SMLoc IdLoc = Lex.getLoc();
2614 StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2615 Lex.Lex(); // eat the field name.
2616
2617 SmallVector<unsigned, 16> BitList;
2618 if (ParseOptionalBitList(BitList))
2619 return true;
2620 std::reverse(BitList.begin(), BitList.end());
2621
2622 if (Lex.getCode() != tgtok::equal)
2623 return TokError("expected '=' in let expression");
2624 Lex.Lex(); // eat the '='.
2625
2626 RecordVal *Field = CurRec->getValue(FieldName);
2627 if (!Field)
2628 return TokError("Value '" + FieldName->getValue() + "' unknown!");
2629
2630 RecTy *Type = Field->getType();
2631
2632 Init *Val = ParseValue(CurRec, Type);
2633 if (!Val) return true;
2634
2635 if (Lex.getCode() != tgtok::semi)
2636 return TokError("expected ';' after let expression");
2637 Lex.Lex();
2638
2639 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2640}
2641
2642/// ParseBody - Read the body of a class or def. Return true on error, false on
2643/// success.
2644///
2645/// Body ::= ';'
2646/// Body ::= '{' BodyList '}'
2647/// BodyList BodyItem*
2648///
2649bool TGParser::ParseBody(Record *CurRec) {
2650 // If this is a null definition, just eat the semi and return.
2651 if (Lex.getCode() == tgtok::semi) {
2652 Lex.Lex();
2653 return false;
2654 }
2655
2656 if (Lex.getCode() != tgtok::l_brace)
2657 return TokError("Expected ';' or '{' to start body");
2658 // Eat the '{'.
2659 Lex.Lex();
2660
2661 while (Lex.getCode() != tgtok::r_brace)
2662 if (ParseBodyItem(CurRec))
2663 return true;
2664
2665 // Eat the '}'.
2666 Lex.Lex();
2667 return false;
2668}
2669
2670/// Apply the current let bindings to \a CurRec.
2671/// \returns true on error, false otherwise.
2672bool TGParser::ApplyLetStack(Record *CurRec) {
2673 for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2674 for (LetRecord &LR : LetInfo)
2675 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2676 return true;
2677 return false;
2678}
2679
2680bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2681 if (Entry.Rec)
2682 return ApplyLetStack(Entry.Rec.get());
2683
2684 for (auto &E : Entry.Loop->Entries) {
2685 if (ApplyLetStack(E))
2686 return true;
2687 }
2688
2689 return false;
2690}
2691
2692/// ParseObjectBody - Parse the body of a def or class. This consists of an
2693/// optional ClassList followed by a Body. CurRec is the current def or class
2694/// that is being parsed.
2695///
2696/// ObjectBody ::= BaseClassList Body
2697/// BaseClassList ::= /*empty*/
2698/// BaseClassList ::= ':' BaseClassListNE
2699/// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2700///
2701bool TGParser::ParseObjectBody(Record *CurRec) {
2702 // If there is a baseclass list, read it.
2703 if (Lex.getCode() == tgtok::colon) {
2704 Lex.Lex();
2705
2706 // Read all of the subclasses.
2707 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2708 while (true) {
2709 // Check for error.
2710 if (!SubClass.Rec) return true;
2711
2712 // Add it.
2713 if (AddSubClass(CurRec, SubClass))
2714 return true;
2715
2716 if (Lex.getCode() != tgtok::comma) break;
2717 Lex.Lex(); // eat ','.
2718 SubClass = ParseSubClassReference(CurRec, false);
2719 }
2720 }
2721
2722 if (ApplyLetStack(CurRec))
2723 return true;
2724
2725 return ParseBody(CurRec);
2726}
2727
2728/// ParseDef - Parse and return a top level or multiclass def, return the record
2729/// corresponding to it. This returns null on error.
2730///
2731/// DefInst ::= DEF ObjectName ObjectBody
2732///
2733bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2734 SMLoc DefLoc = Lex.getLoc();
2735 assert(Lex.getCode() == tgtok::Def && "Unknown tok")((Lex.getCode() == tgtok::Def && "Unknown tok") ? static_cast
<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Def && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2735, __PRETTY_FUNCTION__))
;
2736 Lex.Lex(); // Eat the 'def' token.
2737
2738 // Parse ObjectName and make a record for it.
2739 std::unique_ptr<Record> CurRec;
2740 Init *Name = ParseObjectName(CurMultiClass);
2741 if (!Name)
2742 return true;
2743
2744 if (isa<UnsetInit>(Name))
2745 CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2746 /*Anonymous=*/true);
2747 else
2748 CurRec = std::make_unique<Record>(Name, DefLoc, Records);
2749
2750 if (ParseObjectBody(CurRec.get()))
2751 return true;
2752
2753 return addEntry(std::move(CurRec));
2754}
2755
2756/// ParseDefset - Parse a defset statement.
2757///
2758/// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2759///
2760bool TGParser::ParseDefset() {
2761 assert(Lex.getCode() == tgtok::Defset)((Lex.getCode() == tgtok::Defset) ? static_cast<void> (
0) : __assert_fail ("Lex.getCode() == tgtok::Defset", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2761, __PRETTY_FUNCTION__))
;
2762 Lex.Lex(); // Eat the 'defset' token
2763
2764 DefsetRecord Defset;
2765 Defset.Loc = Lex.getLoc();
2766 RecTy *Type = ParseType();
2767 if (!Type)
2768 return true;
2769 if (!isa<ListRecTy>(Type))
2770 return Error(Defset.Loc, "expected list type");
2771 Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2772
2773 if (Lex.getCode() != tgtok::Id)
2774 return TokError("expected identifier");
2775 StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2776 if (Records.getGlobal(DeclName->getValue()))
2777 return TokError("def or global variable of this name already exists");
2778
2779 if (Lex.Lex() != tgtok::equal) // Eat the identifier
2780 return TokError("expected '='");
2781 if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2782 return TokError("expected '{'");
2783 SMLoc BraceLoc = Lex.getLoc();
2784 Lex.Lex(); // Eat the '{'
2785
2786 Defsets.push_back(&Defset);
2787 bool Err = ParseObjectList(nullptr);
2788 Defsets.pop_back();
2789 if (Err)
2790 return true;
2791
2792 if (Lex.getCode() != tgtok::r_brace) {
2793 TokError("expected '}' at end of defset");
2794 return Error(BraceLoc, "to match this '{'");
2795 }
2796 Lex.Lex(); // Eat the '}'
2797
2798 Records.addExtraGlobal(DeclName->getValue(),
2799 ListInit::get(Defset.Elements, Defset.EltTy));
2800 return false;
2801}
2802
2803/// ParseForeach - Parse a for statement. Return the record corresponding
2804/// to it. This returns true on error.
2805///
2806/// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2807/// Foreach ::= FOREACH Declaration IN Object
2808///
2809bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2810 SMLoc Loc = Lex.getLoc();
2811 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok")((Lex.getCode() == tgtok::Foreach && "Unknown tok") ?
static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Foreach && \"Unknown tok\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2811, __PRETTY_FUNCTION__))
;
2812 Lex.Lex(); // Eat the 'for' token.
2813
2814 // Make a temporary object to record items associated with the for
2815 // loop.
2816 Init *ListValue = nullptr;
2817 VarInit *IterName = ParseForeachDeclaration(ListValue);
2818 if (!IterName)
2819 return TokError("expected declaration in for");
2820
2821 if (Lex.getCode() != tgtok::In)
2822 return TokError("Unknown tok");
2823 Lex.Lex(); // Eat the in
2824
2825 // Create a loop object and remember it.
2826 Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2827
2828 if (Lex.getCode() != tgtok::l_brace) {
2829 // FOREACH Declaration IN Object
2830 if (ParseObject(CurMultiClass))
2831 return true;
2832 } else {
2833 SMLoc BraceLoc = Lex.getLoc();
2834 // Otherwise, this is a group foreach.
2835 Lex.Lex(); // eat the '{'.
2836
2837 // Parse the object list.
2838 if (ParseObjectList(CurMultiClass))
2839 return true;
2840
2841 if (Lex.getCode() != tgtok::r_brace) {
2842 TokError("expected '}' at end of foreach command");
2843 return Error(BraceLoc, "to match this '{'");
2844 }
2845 Lex.Lex(); // Eat the }
2846 }
2847
2848 // Resolve the loop or store it for later resolution.
2849 std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2850 Loops.pop_back();
2851
2852 return addEntry(std::move(Loop));
2853}
2854
2855/// ParseClass - Parse a tblgen class definition.
2856///
2857/// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2858///
2859bool TGParser::ParseClass() {
2860 assert(Lex.getCode() == tgtok::Class && "Unexpected token!")((Lex.getCode() == tgtok::Class && "Unexpected token!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Class && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2860, __PRETTY_FUNCTION__))
;
2861 Lex.Lex();
2862
2863 if (Lex.getCode() != tgtok::Id)
2864 return TokError("expected class name after 'class' keyword");
2865
2866 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2867 if (CurRec) {
2868 // If the body was previously defined, this is an error.
2869 if (!CurRec->getValues().empty() ||
2870 !CurRec->getSuperClasses().empty() ||
2871 !CurRec->getTemplateArgs().empty())
2872 return TokError("Class '" + CurRec->getNameInitAsString() +
2873 "' already defined");
2874 } else {
2875 // If this is the first reference to this class, create and add it.
2876 auto NewRec =
2877 std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2878 /*Class=*/true);
2879 CurRec = NewRec.get();
2880 Records.addClass(std::move(NewRec));
2881 }
2882 Lex.Lex(); // eat the name.
2883
2884 // If there are template args, parse them.
2885 if (Lex.getCode() == tgtok::less)
2886 if (ParseTemplateArgList(CurRec))
2887 return true;
2888
2889 return ParseObjectBody(CurRec);
2890}
2891
2892/// ParseLetList - Parse a non-empty list of assignment expressions into a list
2893/// of LetRecords.
2894///
2895/// LetList ::= LetItem (',' LetItem)*
2896/// LetItem ::= ID OptionalRangeList '=' Value
2897///
2898void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2899 while (true) {
2900 if (Lex.getCode() != tgtok::Id) {
2901 TokError("expected identifier in let definition");
2902 Result.clear();
2903 return;
2904 }
2905
2906 StringInit *Name = StringInit::get(Lex.getCurStrVal());
2907 SMLoc NameLoc = Lex.getLoc();
2908 Lex.Lex(); // Eat the identifier.
2909
2910 // Check for an optional RangeList.
2911 SmallVector<unsigned, 16> Bits;
2912 if (ParseOptionalRangeList(Bits)) {
2913 Result.clear();
2914 return;
2915 }
2916 std::reverse(Bits.begin(), Bits.end());
2917
2918 if (Lex.getCode() != tgtok::equal) {
2919 TokError("expected '=' in let expression");
2920 Result.clear();
2921 return;
2922 }
2923 Lex.Lex(); // eat the '='.
2924
2925 Init *Val = ParseValue(nullptr);
2926 if (!Val) {
2927 Result.clear();
2928 return;
2929 }
2930
2931 // Now that we have everything, add the record.
2932 Result.emplace_back(Name, Bits, Val, NameLoc);
2933
2934 if (Lex.getCode() != tgtok::comma)
2935 return;
2936 Lex.Lex(); // eat the comma.
2937 }
2938}
2939
2940/// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2941/// different related productions. This works inside multiclasses too.
2942///
2943/// Object ::= LET LetList IN '{' ObjectList '}'
2944/// Object ::= LET LetList IN Object
2945///
2946bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2947 assert(Lex.getCode() == tgtok::Let && "Unexpected token")((Lex.getCode() == tgtok::Let && "Unexpected token") ?
static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Let && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2947, __PRETTY_FUNCTION__))
;
2948 Lex.Lex();
2949
2950 // Add this entry to the let stack.
2951 SmallVector<LetRecord, 8> LetInfo;
2952 ParseLetList(LetInfo);
2953 if (LetInfo.empty()) return true;
2954 LetStack.push_back(std::move(LetInfo));
2955
2956 if (Lex.getCode() != tgtok::In)
2957 return TokError("expected 'in' at end of top-level 'let'");
2958 Lex.Lex();
2959
2960 // If this is a scalar let, just handle it now
2961 if (Lex.getCode() != tgtok::l_brace) {
2962 // LET LetList IN Object
2963 if (ParseObject(CurMultiClass))
2964 return true;
2965 } else { // Object ::= LETCommand '{' ObjectList '}'
2966 SMLoc BraceLoc = Lex.getLoc();
2967 // Otherwise, this is a group let.
2968 Lex.Lex(); // eat the '{'.
2969
2970 // Parse the object list.
2971 if (ParseObjectList(CurMultiClass))
2972 return true;
2973
2974 if (Lex.getCode() != tgtok::r_brace) {
2975 TokError("expected '}' at end of top level let command");
2976 return Error(BraceLoc, "to match this '{'");
2977 }
2978 Lex.Lex();
2979 }
2980
2981 // Outside this let scope, this let block is not active.
2982 LetStack.pop_back();
2983 return false;
2984}
2985
2986/// ParseMultiClass - Parse a multiclass definition.
2987///
2988/// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2989/// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2990/// MultiClassObject ::= DefInst
2991/// MultiClassObject ::= MultiClassInst
2992/// MultiClassObject ::= DefMInst
2993/// MultiClassObject ::= LETCommand '{' ObjectList '}'
2994/// MultiClassObject ::= LETCommand Object
2995///
2996bool TGParser::ParseMultiClass() {
2997 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token")((Lex.getCode() == tgtok::MultiClass && "Unexpected token"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::MultiClass && \"Unexpected token\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 2997, __PRETTY_FUNCTION__))
;
2998 Lex.Lex(); // Eat the multiclass token.
2999
3000 if (Lex.getCode() != tgtok::Id)
3001 return TokError("expected identifier after multiclass for name");
3002 std::string Name = Lex.getCurStrVal();
3003
3004 auto Result =
3005 MultiClasses.insert(std::make_pair(Name,
3006 std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
3007
3008 if (!Result.second)
3009 return TokError("multiclass '" + Name + "' already defined");
3010
3011 CurMultiClass = Result.first->second.get();
3012 Lex.Lex(); // Eat the identifier.
3013
3014 // If there are template args, parse them.
3015 if (Lex.getCode() == tgtok::less)
3016 if (ParseTemplateArgList(nullptr))
3017 return true;
3018
3019 bool inherits = false;
3020
3021 // If there are submulticlasses, parse them.
3022 if (Lex.getCode() == tgtok::colon) {
3023 inherits = true;
3024
3025 Lex.Lex();
3026
3027 // Read all of the submulticlasses.
3028 SubMultiClassReference SubMultiClass =
3029 ParseSubMultiClassReference(CurMultiClass);
3030 while (true) {
3031 // Check for error.
3032 if (!SubMultiClass.MC) return true;
3033
3034 // Add it.
3035 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
3036 return true;
3037
3038 if (Lex.getCode() != tgtok::comma) break;
3039 Lex.Lex(); // eat ','.
3040 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
3041 }
3042 }
3043
3044 if (Lex.getCode() != tgtok::l_brace) {
3045 if (!inherits)
3046 return TokError("expected '{' in multiclass definition");
3047 if (Lex.getCode() != tgtok::semi)
3048 return TokError("expected ';' in multiclass definition");
3049 Lex.Lex(); // eat the ';'.
3050 } else {
3051 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
3052 return TokError("multiclass must contain at least one def");
3053
3054 while (Lex.getCode() != tgtok::r_brace) {
3055 switch (Lex.getCode()) {
3056 default:
3057 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
3058 "multiclass body");
3059 case tgtok::Let:
3060 case tgtok::Def:
3061 case tgtok::Defm:
3062 case tgtok::Foreach:
3063 if (ParseObject(CurMultiClass))
3064 return true;
3065 break;
3066 }
3067 }
3068 Lex.Lex(); // eat the '}'.
3069 }
3070
3071 CurMultiClass = nullptr;
3072 return false;
3073}
3074
3075/// ParseDefm - Parse the instantiation of a multiclass.
3076///
3077/// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3078///
3079bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
3080 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!")((Lex.getCode() == tgtok::Defm && "Unexpected token!"
) ? static_cast<void> (0) : __assert_fail ("Lex.getCode() == tgtok::Defm && \"Unexpected token!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 3080, __PRETTY_FUNCTION__))
;
3081 Lex.Lex(); // eat the defm
3082
3083 Init *DefmName = ParseObjectName(CurMultiClass);
3084 if (!DefmName)
3085 return true;
3086 if (isa<UnsetInit>(DefmName)) {
3087 DefmName = Records.getNewAnonymousName();
3088 if (CurMultiClass)
3089 DefmName = BinOpInit::getStrConcat(
3090 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
3091 StringRecTy::get()),
3092 DefmName);
3093 }
3094
3095 if (Lex.getCode() != tgtok::colon)
3096 return TokError("expected ':' after defm identifier");
3097
3098 // Keep track of the new generated record definitions.
3099 std::vector<RecordsEntry> NewEntries;
3100
3101 // This record also inherits from a regular class (non-multiclass)?
3102 bool InheritFromClass = false;
3103
3104 // eat the colon.
3105 Lex.Lex();
3106
3107 SMLoc SubClassLoc = Lex.getLoc();
3108 SubClassReference Ref = ParseSubClassReference(nullptr, true);
3109
3110 while (true) {
3111 if (!Ref.Rec) return true;
3112
3113 // To instantiate a multiclass, we need to first get the multiclass, then
3114 // instantiate each def contained in the multiclass with the SubClassRef
3115 // template parameters.
3116 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
3117 assert(MC && "Didn't lookup multiclass correctly?")((MC && "Didn't lookup multiclass correctly?") ? static_cast
<void> (0) : __assert_fail ("MC && \"Didn't lookup multiclass correctly?\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/TableGen/TGParser.cpp"
, 3117, __PRETTY_FUNCTION__))
;
3118 ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3119
3120 // Verify that the correct number of template arguments were specified.
3121 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3122 if (TArgs.size() < TemplateVals.size())
3123 return Error(SubClassLoc,
3124 "more template args specified than multiclass expects");
3125
3126 SubstStack Substs;
3127 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3128 if (i < TemplateVals.size()) {
3129 Substs.emplace_back(TArgs[i], TemplateVals[i]);
3130 } else {
3131 Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3132 if (!Default->isComplete()) {
3133 return Error(SubClassLoc,
3134 "value not specified for template argument #" +
3135 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3136 ") of multiclass '" + MC->Rec.getNameInitAsString() +
3137 "'");
3138 }
3139 Substs.emplace_back(TArgs[i], Default);
3140 }
3141 }
3142
3143 Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3144
3145 if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3146 &SubClassLoc))
3147 return true;
3148
3149 if (Lex.getCode() != tgtok::comma) break;
3150 Lex.Lex(); // eat ','.
3151
3152 if (Lex.getCode() != tgtok::Id)
3153 return TokError("expected identifier");
3154
3155 SubClassLoc = Lex.getLoc();
3156
3157 // A defm can inherit from regular classes (non-multiclass) as
3158 // long as they come in the end of the inheritance list.
3159 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3160
3161 if (InheritFromClass)
3162 break;
3163
3164 Ref = ParseSubClassReference(nullptr, true);
3165 }
3166
3167 if (InheritFromClass) {
3168 // Process all the classes to inherit as if they were part of a
3169 // regular 'def' and inherit all record values.
3170 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3171 while (true) {
3172 // Check for error.
3173 if (!SubClass.Rec) return true;
3174
3175 // Get the expanded definition prototypes and teach them about
3176 // the record values the current class to inherit has
3177 for (auto &E : NewEntries) {
3178 // Add it.
3179 if (AddSubClass(E, SubClass))
3180 return true;
3181 }
3182
3183 if (Lex.getCode() != tgtok::comma) break;
3184 Lex.Lex(); // eat ','.
3185 SubClass = ParseSubClassReference(nullptr, false);
3186 }
3187 }
3188
3189 for (auto &E : NewEntries) {
3190 if (ApplyLetStack(E))
3191 return true;
3192
3193 addEntry(std::move(E));
3194 }
3195
3196 if (Lex.getCode() != tgtok::semi)
3197 return TokError("expected ';' at end of defm");
3198 Lex.Lex();
3199
3200 return false;
3201}
3202
3203/// ParseObject
3204/// Object ::= ClassInst
3205/// Object ::= DefInst
3206/// Object ::= MultiClassInst
3207/// Object ::= DefMInst
3208/// Object ::= LETCommand '{' ObjectList '}'
3209/// Object ::= LETCommand Object
3210bool TGParser::ParseObject(MultiClass *MC) {
3211 switch (Lex.getCode()) {
3212 default:
3213 return TokError("Expected class, def, defm, defset, multiclass, let or "
3214 "foreach");
3215 case tgtok::Let: return ParseTopLevelLet(MC);
3216 case tgtok::Def: return ParseDef(MC);
3217 case tgtok::Foreach: return ParseForeach(MC);
3218 case tgtok::Defm: return ParseDefm(MC);
3219 case tgtok::Defset:
3220 if (MC)
3221 return TokError("defset is not allowed inside multiclass");
3222 return ParseDefset();
3223 case tgtok::Class:
3224 if (MC)
3225 return TokError("class is not allowed inside multiclass");
3226 if (!Loops.empty())
3227 return TokError("class is not allowed inside foreach loop");
3228 return ParseClass();
3229 case tgtok::MultiClass:
3230 if (!Loops.empty())
3231 return TokError("multiclass is not allowed inside foreach loop");
3232 return ParseMultiClass();
3233 }
3234}
3235
3236/// ParseObjectList
3237/// ObjectList :== Object*
3238bool TGParser::ParseObjectList(MultiClass *MC) {
3239 while (isObjectStart(Lex.getCode())) {
3240 if (ParseObject(MC))
3241 return true;
3242 }
3243 return false;
3244}
3245
3246bool TGParser::ParseFile() {
3247 Lex.Lex(); // Prime the lexer.
3248 if (ParseObjectList()) return true;
3249
3250 // If we have unread input at the end of the file, report it.
3251 if (Lex.getCode() == tgtok::Eof)
3252 return false;
3253
3254 return TokError("Unexpected input at top level");
3255}
3256
3257#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3258LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordsEntry::dump() const {
3259 if (Loop)
3260 Loop->dump();
3261 if (Rec)
3262 Rec->dump();
3263}
3264
3265LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ForeachLoop::dump() const {
3266 errs() << "foreach " << IterVar->getAsString() << " = "
3267 << ListValue->getAsString() << " in {\n";
3268
3269 for (const auto &E : Entries)
3270 E.dump();
3271
3272 errs() << "}\n";
3273}
3274
3275LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void MultiClass::dump() const {
3276 errs() << "Record:\n";
3277 Rec.dump();
3278
3279 errs() << "Defs:\n";
3280 for (const auto &E : Entries)
3281 E.dump();
3282}
3283#endif