Bug Summary

File:llvm/lib/TableGen/Record.cpp
Warning:line 434, column 11
Value stored to 'NewBit' during its initialization is never read

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 Record.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-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/TableGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp
1//===- Record.cpp - Record implementation ---------------------------------===//
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 tablegen record classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/FoldingSet.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/StringSet.h"
23#include "llvm/Config/llvm-config.h"
24#include "llvm/Support/Allocator.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/SMLoc.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/TableGen/Error.h"
31#include "llvm/TableGen/Record.h"
32#include <cassert>
33#include <cstdint>
34#include <memory>
35#include <map>
36#include <string>
37#include <utility>
38#include <vector>
39
40using namespace llvm;
41
42#define DEBUG_TYPE"tblgen-records" "tblgen-records"
43
44static BumpPtrAllocator Allocator;
45
46STATISTIC(CodeInitsConstructed,static llvm::Statistic CodeInitsConstructed = {"tblgen-records"
, "CodeInitsConstructed", "The total number of unique CodeInits constructed"
}
47 "The total number of unique CodeInits constructed")static llvm::Statistic CodeInitsConstructed = {"tblgen-records"
, "CodeInitsConstructed", "The total number of unique CodeInits constructed"
}
;
48
49//===----------------------------------------------------------------------===//
50// Type implementations
51//===----------------------------------------------------------------------===//
52
53BitRecTy BitRecTy::Shared;
54CodeRecTy CodeRecTy::Shared;
55IntRecTy IntRecTy::Shared;
56StringRecTy StringRecTy::Shared;
57DagRecTy DagRecTy::Shared;
58
59#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecTy::dump() const { print(errs()); }
61#endif
62
63ListRecTy *RecTy::getListTy() {
64 if (!ListTy)
65 ListTy = new(Allocator) ListRecTy(this);
66 return ListTy;
67}
68
69bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
70 assert(RHS && "NULL pointer")((RHS && "NULL pointer") ? static_cast<void> (0
) : __assert_fail ("RHS && \"NULL pointer\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 70, __PRETTY_FUNCTION__))
;
71 return Kind == RHS->getRecTyKind();
72}
73
74bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
75
76bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
77 if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
78 return true;
79 if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
80 return BitsTy->getNumBits() == 1;
81 return false;
82}
83
84BitsRecTy *BitsRecTy::get(unsigned Sz) {
85 static std::vector<BitsRecTy*> Shared;
86 if (Sz >= Shared.size())
87 Shared.resize(Sz + 1);
88 BitsRecTy *&Ty = Shared[Sz];
89 if (!Ty)
90 Ty = new(Allocator) BitsRecTy(Sz);
91 return Ty;
92}
93
94std::string BitsRecTy::getAsString() const {
95 return "bits<" + utostr(Size) + ">";
96}
97
98bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
99 if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
100 return cast<BitsRecTy>(RHS)->Size == Size;
101 RecTyKind kind = RHS->getRecTyKind();
102 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
103}
104
105bool BitsRecTy::typeIsA(const RecTy *RHS) const {
106 if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
107 return RHSb->Size == Size;
108 return false;
109}
110
111bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
112 RecTyKind kind = RHS->getRecTyKind();
113 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
114}
115
116bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
117 RecTyKind Kind = RHS->getRecTyKind();
118 return Kind == CodeRecTyKind || Kind == StringRecTyKind;
119}
120
121std::string StringRecTy::getAsString() const {
122 return "string";
123}
124
125bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
126 RecTyKind Kind = RHS->getRecTyKind();
127 return Kind == StringRecTyKind || Kind == CodeRecTyKind;
128}
129
130std::string ListRecTy::getAsString() const {
131 return "list<" + Ty->getAsString() + ">";
132}
133
134bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
135 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
136 return Ty->typeIsConvertibleTo(ListTy->getElementType());
137 return false;
138}
139
140bool ListRecTy::typeIsA(const RecTy *RHS) const {
141 if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
142 return getElementType()->typeIsA(RHSl->getElementType());
143 return false;
144}
145
146std::string DagRecTy::getAsString() const {
147 return "dag";
148}
149
150static void ProfileRecordRecTy(FoldingSetNodeID &ID,
151 ArrayRef<Record *> Classes) {
152 ID.AddInteger(Classes.size());
153 for (Record *R : Classes)
154 ID.AddPointer(R);
155}
156
157RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
158 if (UnsortedClasses.empty()) {
159 static RecordRecTy AnyRecord(0);
160 return &AnyRecord;
161 }
162
163 FoldingSet<RecordRecTy> &ThePool =
164 UnsortedClasses[0]->getRecords().RecordTypePool;
165
166 SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
167 UnsortedClasses.end());
168 llvm::sort(Classes, [](Record *LHS, Record *RHS) {
169 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
170 });
171
172 FoldingSetNodeID ID;
173 ProfileRecordRecTy(ID, Classes);
174
175 void *IP = nullptr;
176 if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
177 return Ty;
178
179#ifndef NDEBUG
180 // Check for redundancy.
181 for (unsigned i = 0; i < Classes.size(); ++i) {
182 for (unsigned j = 0; j < Classes.size(); ++j) {
183 assert(i == j || !Classes[i]->isSubClassOf(Classes[j]))((i == j || !Classes[i]->isSubClassOf(Classes[j])) ? static_cast
<void> (0) : __assert_fail ("i == j || !Classes[i]->isSubClassOf(Classes[j])"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 183, __PRETTY_FUNCTION__))
;
184 }
185 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords())((&Classes[0]->getRecords() == &Classes[i]->getRecords
()) ? static_cast<void> (0) : __assert_fail ("&Classes[0]->getRecords() == &Classes[i]->getRecords()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 185, __PRETTY_FUNCTION__))
;
186 }
187#endif
188
189 void *Mem = Allocator.Allocate(totalSizeToAlloc<Record *>(Classes.size()),
190 alignof(RecordRecTy));
191 RecordRecTy *Ty = new(Mem) RecordRecTy(Classes.size());
192 std::uninitialized_copy(Classes.begin(), Classes.end(),
193 Ty->getTrailingObjects<Record *>());
194 ThePool.InsertNode(Ty, IP);
195 return Ty;
196}
197
198void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
199 ProfileRecordRecTy(ID, getClasses());
200}
201
202std::string RecordRecTy::getAsString() const {
203 if (NumClasses == 1)
204 return getClasses()[0]->getNameInitAsString();
205
206 std::string Str = "{";
207 bool First = true;
208 for (Record *R : getClasses()) {
209 if (!First)
210 Str += ", ";
211 First = false;
212 Str += R->getNameInitAsString();
213 }
214 Str += "}";
215 return Str;
216}
217
218bool RecordRecTy::isSubClassOf(Record *Class) const {
219 return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
220 return MySuperClass == Class ||
221 MySuperClass->isSubClassOf(Class);
222 });
223}
224
225bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
226 if (this == RHS)
227 return true;
228
229 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
230 if (!RTy)
231 return false;
232
233 return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
234 return isSubClassOf(TargetClass);
235 });
236}
237
238bool RecordRecTy::typeIsA(const RecTy *RHS) const {
239 return typeIsConvertibleTo(RHS);
240}
241
242static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
243 SmallVector<Record *, 4> CommonSuperClasses;
244 SmallVector<Record *, 4> Stack;
245
246 Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
247
248 while (!Stack.empty()) {
249 Record *R = Stack.back();
250 Stack.pop_back();
251
252 if (T2->isSubClassOf(R)) {
253 CommonSuperClasses.push_back(R);
254 } else {
255 R->getDirectSuperClasses(Stack);
256 }
257 }
258
259 return RecordRecTy::get(CommonSuperClasses);
260}
261
262RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
263 if (T1 == T2)
264 return T1;
265
266 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
267 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
268 return resolveRecordTypes(RecTy1, RecTy2);
269 }
270
271 if (T1->typeIsConvertibleTo(T2))
272 return T2;
273 if (T2->typeIsConvertibleTo(T1))
274 return T1;
275
276 if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
277 if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
278 RecTy* NewType = resolveTypes(ListTy1->getElementType(),
279 ListTy2->getElementType());
280 if (NewType)
281 return NewType->getListTy();
282 }
283 }
284
285 return nullptr;
286}
287
288//===----------------------------------------------------------------------===//
289// Initializer implementations
290//===----------------------------------------------------------------------===//
291
292void Init::anchor() {}
293
294#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Init::dump() const { return print(errs()); }
296#endif
297
298UnsetInit *UnsetInit::get() {
299 static UnsetInit TheInit;
300 return &TheInit;
301}
302
303Init *UnsetInit::getCastTo(RecTy *Ty) const {
304 return const_cast<UnsetInit *>(this);
305}
306
307Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
308 return const_cast<UnsetInit *>(this);
309}
310
311BitInit *BitInit::get(bool V) {
312 static BitInit True(true);
313 static BitInit False(false);
314
315 return V ? &True : &False;
316}
317
318Init *BitInit::convertInitializerTo(RecTy *Ty) const {
319 if (isa<BitRecTy>(Ty))
320 return const_cast<BitInit *>(this);
321
322 if (isa<IntRecTy>(Ty))
323 return IntInit::get(getValue());
324
325 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
326 // Can only convert single bit.
327 if (BRT->getNumBits() == 1)
328 return BitsInit::get(const_cast<BitInit *>(this));
329 }
330
331 return nullptr;
332}
333
334static void
335ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
336 ID.AddInteger(Range.size());
337
338 for (Init *I : Range)
339 ID.AddPointer(I);
340}
341
342BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
343 static FoldingSet<BitsInit> ThePool;
344
345 FoldingSetNodeID ID;
346 ProfileBitsInit(ID, Range);
347
348 void *IP = nullptr;
349 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
350 return I;
351
352 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
353 alignof(BitsInit));
354 BitsInit *I = new(Mem) BitsInit(Range.size());
355 std::uninitialized_copy(Range.begin(), Range.end(),
356 I->getTrailingObjects<Init *>());
357 ThePool.InsertNode(I, IP);
358 return I;
359}
360
361void BitsInit::Profile(FoldingSetNodeID &ID) const {
362 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
363}
364
365Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
366 if (isa<BitRecTy>(Ty)) {
367 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
368 return getBit(0);
369 }
370
371 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
372 // If the number of bits is right, return it. Otherwise we need to expand
373 // or truncate.
374 if (getNumBits() != BRT->getNumBits()) return nullptr;
375 return const_cast<BitsInit *>(this);
376 }
377
378 if (isa<IntRecTy>(Ty)) {
379 int64_t Result = 0;
380 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
381 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
382 Result |= static_cast<int64_t>(Bit->getValue()) << i;
383 else
384 return nullptr;
385 return IntInit::get(Result);
386 }
387
388 return nullptr;
389}
390
391Init *
392BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
393 SmallVector<Init *, 16> NewBits(Bits.size());
394
395 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
396 if (Bits[i] >= getNumBits())
397 return nullptr;
398 NewBits[i] = getBit(Bits[i]);
399 }
400 return BitsInit::get(NewBits);
401}
402
403bool BitsInit::isConcrete() const {
404 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
405 if (!getBit(i)->isConcrete())
406 return false;
407 }
408 return true;
409}
410
411std::string BitsInit::getAsString() const {
412 std::string Result = "{ ";
413 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
414 if (i) Result += ", ";
415 if (Init *Bit = getBit(e-i-1))
416 Result += Bit->getAsString();
417 else
418 Result += "*";
419 }
420 return Result + " }";
421}
422
423// resolveReferences - If there are any field references that refer to fields
424// that have been filled in, we can propagate the values now.
425Init *BitsInit::resolveReferences(Resolver &R) const {
426 bool Changed = false;
427 SmallVector<Init *, 16> NewBits(getNumBits());
428
429 Init *CachedBitVarRef = nullptr;
430 Init *CachedBitVarResolved = nullptr;
431
432 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
433 Init *CurBit = getBit(i);
434 Init *NewBit = CurBit;
Value stored to 'NewBit' during its initialization is never read
435
436 if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
437 if (CurBitVar->getBitVar() != CachedBitVarRef) {
438 CachedBitVarRef = CurBitVar->getBitVar();
439 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
440 }
441 assert(CachedBitVarResolved && "Unresolved bitvar reference")((CachedBitVarResolved && "Unresolved bitvar reference"
) ? static_cast<void> (0) : __assert_fail ("CachedBitVarResolved && \"Unresolved bitvar reference\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 441, __PRETTY_FUNCTION__))
;
442 NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
443 } else {
444 // getBit(0) implicitly converts int and bits<1> values to bit.
445 NewBit = CurBit->resolveReferences(R)->getBit(0);
446 }
447
448 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
449 NewBit = CurBit;
450 NewBits[i] = NewBit;
451 Changed |= CurBit != NewBit;
452 }
453
454 if (Changed)
455 return BitsInit::get(NewBits);
456
457 return const_cast<BitsInit *>(this);
458}
459
460IntInit *IntInit::get(int64_t V) {
461 static std::map<int64_t, IntInit*> ThePool;
462
463 IntInit *&I = ThePool[V];
464 if (!I) I = new(Allocator) IntInit(V);
465 return I;
466}
467
468std::string IntInit::getAsString() const {
469 return itostr(Value);
470}
471
472static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
473 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
474 return (NumBits >= sizeof(Value) * 8) ||
475 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
476}
477
478Init *IntInit::convertInitializerTo(RecTy *Ty) const {
479 if (isa<IntRecTy>(Ty))
480 return const_cast<IntInit *>(this);
481
482 if (isa<BitRecTy>(Ty)) {
483 int64_t Val = getValue();
484 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
485 return BitInit::get(Val != 0);
486 }
487
488 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
489 int64_t Value = getValue();
490 // Make sure this bitfield is large enough to hold the integer value.
491 if (!canFitInBitfield(Value, BRT->getNumBits()))
492 return nullptr;
493
494 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
495 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
496 NewBits[i] = BitInit::get(Value & ((i < 64) ? (1LL << i) : 0));
497
498 return BitsInit::get(NewBits);
499 }
500
501 return nullptr;
502}
503
504Init *
505IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
506 SmallVector<Init *, 16> NewBits(Bits.size());
507
508 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
509 if (Bits[i] >= 64)
510 return nullptr;
511
512 NewBits[i] = BitInit::get(Value & (INT64_C(1)1L << Bits[i]));
513 }
514 return BitsInit::get(NewBits);
515}
516
517CodeInit *CodeInit::get(StringRef V, const SMLoc &Loc) {
518 static StringSet<BumpPtrAllocator &> ThePool(Allocator);
519
520 CodeInitsConstructed++;
521
522 // Unlike StringMap, StringSet doesn't accept empty keys.
523 if (V.empty())
524 return new (Allocator) CodeInit("", Loc);
525
526 // Location tracking prevents us from de-duping CodeInits as we're never
527 // called with the same string and same location twice. However, we can at
528 // least de-dupe the strings for a modest saving.
529 auto &Entry = *ThePool.insert(V).first;
530 return new(Allocator) CodeInit(Entry.getKey(), Loc);
531}
532
533StringInit *StringInit::get(StringRef V) {
534 static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
535
536 auto &Entry = *ThePool.insert(std::make_pair(V, nullptr)).first;
537 if (!Entry.second)
538 Entry.second = new(Allocator) StringInit(Entry.getKey());
539 return Entry.second;
540}
541
542Init *StringInit::convertInitializerTo(RecTy *Ty) const {
543 if (isa<StringRecTy>(Ty))
544 return const_cast<StringInit *>(this);
545 if (isa<CodeRecTy>(Ty))
546 return CodeInit::get(getValue(), SMLoc());
547
548 return nullptr;
549}
550
551Init *CodeInit::convertInitializerTo(RecTy *Ty) const {
552 if (isa<CodeRecTy>(Ty))
553 return const_cast<CodeInit *>(this);
554 if (isa<StringRecTy>(Ty))
555 return StringInit::get(getValue());
556
557 return nullptr;
558}
559
560static void ProfileListInit(FoldingSetNodeID &ID,
561 ArrayRef<Init *> Range,
562 RecTy *EltTy) {
563 ID.AddInteger(Range.size());
564 ID.AddPointer(EltTy);
565
566 for (Init *I : Range)
567 ID.AddPointer(I);
568}
569
570ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
571 static FoldingSet<ListInit> ThePool;
572
573 FoldingSetNodeID ID;
574 ProfileListInit(ID, Range, EltTy);
575
576 void *IP = nullptr;
577 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
578 return I;
579
580 assert(Range.empty() || !isa<TypedInit>(Range[0]) ||((Range.empty() || !isa<TypedInit>(Range[0]) || cast<
TypedInit>(Range[0])->getType()->typeIsConvertibleTo
(EltTy)) ? static_cast<void> (0) : __assert_fail ("Range.empty() || !isa<TypedInit>(Range[0]) || cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 581, __PRETTY_FUNCTION__))
581 cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy))((Range.empty() || !isa<TypedInit>(Range[0]) || cast<
TypedInit>(Range[0])->getType()->typeIsConvertibleTo
(EltTy)) ? static_cast<void> (0) : __assert_fail ("Range.empty() || !isa<TypedInit>(Range[0]) || cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 581, __PRETTY_FUNCTION__))
;
582
583 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
584 alignof(ListInit));
585 ListInit *I = new(Mem) ListInit(Range.size(), EltTy);
586 std::uninitialized_copy(Range.begin(), Range.end(),
587 I->getTrailingObjects<Init *>());
588 ThePool.InsertNode(I, IP);
589 return I;
590}
591
592void ListInit::Profile(FoldingSetNodeID &ID) const {
593 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
594
595 ProfileListInit(ID, getValues(), EltTy);
596}
597
598Init *ListInit::convertInitializerTo(RecTy *Ty) const {
599 if (getType() == Ty)
600 return const_cast<ListInit*>(this);
601
602 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
603 SmallVector<Init*, 8> Elements;
604 Elements.reserve(getValues().size());
605
606 // Verify that all of the elements of the list are subclasses of the
607 // appropriate class!
608 bool Changed = false;
609 RecTy *ElementType = LRT->getElementType();
610 for (Init *I : getValues())
611 if (Init *CI = I->convertInitializerTo(ElementType)) {
612 Elements.push_back(CI);
613 if (CI != I)
614 Changed = true;
615 } else
616 return nullptr;
617
618 if (!Changed)
619 return const_cast<ListInit*>(this);
620 return ListInit::get(Elements, ElementType);
621 }
622
623 return nullptr;
624}
625
626Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
627 SmallVector<Init*, 8> Vals;
628 Vals.reserve(Elements.size());
629 for (unsigned Element : Elements) {
630 if (Element >= size())
631 return nullptr;
632 Vals.push_back(getElement(Element));
633 }
634 return ListInit::get(Vals, getElementType());
635}
636
637Record *ListInit::getElementAsRecord(unsigned i) const {
638 assert(i < NumValues && "List element index out of range!")((i < NumValues && "List element index out of range!"
) ? static_cast<void> (0) : __assert_fail ("i < NumValues && \"List element index out of range!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 638, __PRETTY_FUNCTION__))
;
639 DefInit *DI = dyn_cast<DefInit>(getElement(i));
640 if (!DI)
641 PrintFatalError("Expected record in list!");
642 return DI->getDef();
643}
644
645Init *ListInit::resolveReferences(Resolver &R) const {
646 SmallVector<Init*, 8> Resolved;
647 Resolved.reserve(size());
648 bool Changed = false;
649
650 for (Init *CurElt : getValues()) {
651 Init *E = CurElt->resolveReferences(R);
652 Changed |= E != CurElt;
653 Resolved.push_back(E);
654 }
655
656 if (Changed)
657 return ListInit::get(Resolved, getElementType());
658 return const_cast<ListInit *>(this);
659}
660
661bool ListInit::isConcrete() const {
662 for (Init *Element : *this) {
663 if (!Element->isConcrete())
664 return false;
665 }
666 return true;
667}
668
669std::string ListInit::getAsString() const {
670 std::string Result = "[";
671 const char *sep = "";
672 for (Init *Element : *this) {
673 Result += sep;
674 sep = ", ";
675 Result += Element->getAsString();
676 }
677 return Result + "]";
678}
679
680Init *OpInit::getBit(unsigned Bit) const {
681 if (getType() == BitRecTy::get())
682 return const_cast<OpInit*>(this);
683 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
684}
685
686static void
687ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
688 ID.AddInteger(Opcode);
689 ID.AddPointer(Op);
690 ID.AddPointer(Type);
691}
692
693UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
694 static FoldingSet<UnOpInit> ThePool;
695
696 FoldingSetNodeID ID;
697 ProfileUnOpInit(ID, Opc, LHS, Type);
698
699 void *IP = nullptr;
700 if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
701 return I;
702
703 UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
704 ThePool.InsertNode(I, IP);
705 return I;
706}
707
708void UnOpInit::Profile(FoldingSetNodeID &ID) const {
709 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
710}
711
712Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
713 switch (getOpcode()) {
714 case CAST:
715 if (isa<StringRecTy>(getType())) {
716 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
717 return LHSs;
718
719 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
720 return StringInit::get(LHSd->getAsString());
721
722 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
723 return StringInit::get(LHSi->getAsString());
724 } else if (isa<RecordRecTy>(getType())) {
725 if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
726 if (!CurRec && !IsFinal)
727 break;
728 assert(CurRec && "NULL pointer")((CurRec && "NULL pointer") ? static_cast<void>
(0) : __assert_fail ("CurRec && \"NULL pointer\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 728, __PRETTY_FUNCTION__))
;
729 Record *D;
730
731 // Self-references are allowed, but their resolution is delayed until
732 // the final resolve to ensure that we get the correct type for them.
733 if (Name == CurRec->getNameInit()) {
734 if (!IsFinal)
735 break;
736 D = CurRec;
737 } else {
738 D = CurRec->getRecords().getDef(Name->getValue());
739 if (!D) {
740 if (IsFinal)
741 PrintFatalError(CurRec->getLoc(),
742 Twine("Undefined reference to record: '") +
743 Name->getValue() + "'\n");
744 break;
745 }
746 }
747
748 DefInit *DI = DefInit::get(D);
749 if (!DI->getType()->typeIsA(getType())) {
750 PrintFatalError(CurRec->getLoc(),
751 Twine("Expected type '") +
752 getType()->getAsString() + "', got '" +
753 DI->getType()->getAsString() + "' in: " +
754 getAsString() + "\n");
755 }
756 return DI;
757 }
758 }
759
760 if (Init *NewInit = LHS->convertInitializerTo(getType()))
761 return NewInit;
762 break;
763
764 case HEAD:
765 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
766 assert(!LHSl->empty() && "Empty list in head")((!LHSl->empty() && "Empty list in head") ? static_cast
<void> (0) : __assert_fail ("!LHSl->empty() && \"Empty list in head\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 766, __PRETTY_FUNCTION__))
;
767 return LHSl->getElement(0);
768 }
769 break;
770
771 case TAIL:
772 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
773 assert(!LHSl->empty() && "Empty list in tail")((!LHSl->empty() && "Empty list in tail") ? static_cast
<void> (0) : __assert_fail ("!LHSl->empty() && \"Empty list in tail\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 773, __PRETTY_FUNCTION__))
;
774 // Note the +1. We can't just pass the result of getValues()
775 // directly.
776 return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
777 }
778 break;
779
780 case SIZE:
781 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
782 return IntInit::get(LHSl->size());
783 break;
784
785 case EMPTY:
786 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
787 return IntInit::get(LHSl->empty());
788 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
789 return IntInit::get(LHSs->getValue().empty());
790 break;
791
792 case GETOP:
793 if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
794 DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
795 if (!DI->getType()->typeIsA(getType())) {
796 PrintFatalError(CurRec->getLoc(),
797 Twine("Expected type '") +
798 getType()->getAsString() + "', got '" +
799 DI->getType()->getAsString() + "' in: " +
800 getAsString() + "\n");
801 } else {
802 return DI;
803 }
804 }
805 break;
806 }
807 return const_cast<UnOpInit *>(this);
808}
809
810Init *UnOpInit::resolveReferences(Resolver &R) const {
811 Init *lhs = LHS->resolveReferences(R);
812
813 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
814 return (UnOpInit::get(getOpcode(), lhs, getType()))
815 ->Fold(R.getCurrentRecord(), R.isFinal());
816 return const_cast<UnOpInit *>(this);
817}
818
819std::string UnOpInit::getAsString() const {
820 std::string Result;
821 switch (getOpcode()) {
822 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
823 case HEAD: Result = "!head"; break;
824 case TAIL: Result = "!tail"; break;
825 case SIZE: Result = "!size"; break;
826 case EMPTY: Result = "!empty"; break;
827 case GETOP: Result = "!getop"; break;
828 }
829 return Result + "(" + LHS->getAsString() + ")";
830}
831
832static void
833ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
834 RecTy *Type) {
835 ID.AddInteger(Opcode);
836 ID.AddPointer(LHS);
837 ID.AddPointer(RHS);
838 ID.AddPointer(Type);
839}
840
841BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
842 Init *RHS, RecTy *Type) {
843 static FoldingSet<BinOpInit> ThePool;
844
845 FoldingSetNodeID ID;
846 ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
847
848 void *IP = nullptr;
849 if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
850 return I;
851
852 BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
853 ThePool.InsertNode(I, IP);
854 return I;
855}
856
857void BinOpInit::Profile(FoldingSetNodeID &ID) const {
858 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
859}
860
861static StringInit *ConcatStringInits(const StringInit *I0,
862 const StringInit *I1) {
863 SmallString<80> Concat(I0->getValue());
864 Concat.append(I1->getValue());
865 return StringInit::get(Concat);
866}
867
868Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
869 // Shortcut for the common case of concatenating two strings.
870 if (const StringInit *I0s = dyn_cast<StringInit>(I0))
871 if (const StringInit *I1s = dyn_cast<StringInit>(I1))
872 return ConcatStringInits(I0s, I1s);
873 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
874}
875
876static ListInit *ConcatListInits(const ListInit *LHS,
877 const ListInit *RHS) {
878 SmallVector<Init *, 8> Args;
879 Args.insert(Args.end(), LHS->begin(), LHS->end());
880 Args.insert(Args.end(), RHS->begin(), RHS->end());
881 return ListInit::get(Args, LHS->getElementType());
882}
883
884Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
885 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list")((isa<ListRecTy>(LHS->getType()) && "First arg must be a list"
) ? static_cast<void> (0) : __assert_fail ("isa<ListRecTy>(LHS->getType()) && \"First arg must be a list\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 885, __PRETTY_FUNCTION__))
;
886
887 // Shortcut for the common case of concatenating two lists.
888 if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
889 if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
890 return ConcatListInits(LHSList, RHSList);
891 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
892}
893
894Init *BinOpInit::getListSplat(TypedInit *LHS, Init *RHS) {
895 return BinOpInit::get(BinOpInit::LISTSPLAT, LHS, RHS, LHS->getType());
896}
897
898Init *BinOpInit::Fold(Record *CurRec) const {
899 switch (getOpcode()) {
900 case CONCAT: {
901 DagInit *LHSs = dyn_cast<DagInit>(LHS);
902 DagInit *RHSs = dyn_cast<DagInit>(RHS);
903 if (LHSs && RHSs) {
904 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
905 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
906 if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
907 (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
908 break;
909 if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
910 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
911 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
912 "'");
913 }
914 Init *Op = LOp ? LOp : ROp;
915 if (!Op)
916 Op = UnsetInit::get();
917
918 SmallVector<Init*, 8> Args;
919 SmallVector<StringInit*, 8> ArgNames;
920 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
921 Args.push_back(LHSs->getArg(i));
922 ArgNames.push_back(LHSs->getArgName(i));
923 }
924 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
925 Args.push_back(RHSs->getArg(i));
926 ArgNames.push_back(RHSs->getArgName(i));
927 }
928 return DagInit::get(Op, nullptr, Args, ArgNames);
929 }
930 break;
931 }
932 case LISTCONCAT: {
933 ListInit *LHSs = dyn_cast<ListInit>(LHS);
934 ListInit *RHSs = dyn_cast<ListInit>(RHS);
935 if (LHSs && RHSs) {
936 SmallVector<Init *, 8> Args;
937 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
938 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
939 return ListInit::get(Args, LHSs->getElementType());
940 }
941 break;
942 }
943 case LISTSPLAT: {
944 TypedInit *Value = dyn_cast<TypedInit>(LHS);
945 IntInit *Size = dyn_cast<IntInit>(RHS);
946 if (Value && Size) {
947 SmallVector<Init *, 8> Args(Size->getValue(), Value);
948 return ListInit::get(Args, Value->getType());
949 }
950 break;
951 }
952 case STRCONCAT: {
953 StringInit *LHSs = dyn_cast<StringInit>(LHS);
954 StringInit *RHSs = dyn_cast<StringInit>(RHS);
955 if (LHSs && RHSs)
956 return ConcatStringInits(LHSs, RHSs);
957 break;
958 }
959 case EQ:
960 case NE:
961 case LE:
962 case LT:
963 case GE:
964 case GT: {
965 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
966 // to string objects.
967 IntInit *L =
968 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
969 IntInit *R =
970 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
971
972 if (L && R) {
973 bool Result;
974 switch (getOpcode()) {
975 case EQ: Result = L->getValue() == R->getValue(); break;
976 case NE: Result = L->getValue() != R->getValue(); break;
977 case LE: Result = L->getValue() <= R->getValue(); break;
978 case LT: Result = L->getValue() < R->getValue(); break;
979 case GE: Result = L->getValue() >= R->getValue(); break;
980 case GT: Result = L->getValue() > R->getValue(); break;
981 default: llvm_unreachable("unhandled comparison")::llvm::llvm_unreachable_internal("unhandled comparison", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 981)
;
982 }
983 return BitInit::get(Result);
984 }
985
986 if (getOpcode() == EQ || getOpcode() == NE) {
987 StringInit *LHSs = dyn_cast<StringInit>(LHS);
988 StringInit *RHSs = dyn_cast<StringInit>(RHS);
989
990 // Make sure we've resolved
991 if (LHSs && RHSs) {
992 bool Equal = LHSs->getValue() == RHSs->getValue();
993 return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
994 }
995 }
996
997 break;
998 }
999 case SETOP: {
1000 DagInit *Dag = dyn_cast<DagInit>(LHS);
1001 DefInit *Op = dyn_cast<DefInit>(RHS);
1002 if (Dag && Op) {
1003 SmallVector<Init*, 8> Args;
1004 SmallVector<StringInit*, 8> ArgNames;
1005 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1006 Args.push_back(Dag->getArg(i));
1007 ArgNames.push_back(Dag->getArgName(i));
1008 }
1009 return DagInit::get(Op, nullptr, Args, ArgNames);
1010 }
1011 break;
1012 }
1013 case ADD:
1014 case MUL:
1015 case AND:
1016 case OR:
1017 case SHL:
1018 case SRA:
1019 case SRL: {
1020 IntInit *LHSi =
1021 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
1022 IntInit *RHSi =
1023 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
1024 if (LHSi && RHSi) {
1025 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
1026 int64_t Result;
1027 switch (getOpcode()) {
1028 default: llvm_unreachable("Bad opcode!")::llvm::llvm_unreachable_internal("Bad opcode!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1028)
;
1029 case ADD: Result = LHSv + RHSv; break;
1030 case MUL: Result = LHSv * RHSv; break;
1031 case AND: Result = LHSv & RHSv; break;
1032 case OR: Result = LHSv | RHSv; break;
1033 case SHL: Result = LHSv << RHSv; break;
1034 case SRA: Result = LHSv >> RHSv; break;
1035 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1036 }
1037 return IntInit::get(Result);
1038 }
1039 break;
1040 }
1041 }
1042 return const_cast<BinOpInit *>(this);
1043}
1044
1045Init *BinOpInit::resolveReferences(Resolver &R) const {
1046 Init *lhs = LHS->resolveReferences(R);
1047 Init *rhs = RHS->resolveReferences(R);
1048
1049 if (LHS != lhs || RHS != rhs)
1050 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1051 ->Fold(R.getCurrentRecord());
1052 return const_cast<BinOpInit *>(this);
1053}
1054
1055std::string BinOpInit::getAsString() const {
1056 std::string Result;
1057 switch (getOpcode()) {
1058 case CONCAT: Result = "!con"; break;
1059 case ADD: Result = "!add"; break;
1060 case MUL: Result = "!mul"; break;
1061 case AND: Result = "!and"; break;
1062 case OR: Result = "!or"; break;
1063 case SHL: Result = "!shl"; break;
1064 case SRA: Result = "!sra"; break;
1065 case SRL: Result = "!srl"; break;
1066 case EQ: Result = "!eq"; break;
1067 case NE: Result = "!ne"; break;
1068 case LE: Result = "!le"; break;
1069 case LT: Result = "!lt"; break;
1070 case GE: Result = "!ge"; break;
1071 case GT: Result = "!gt"; break;
1072 case LISTCONCAT: Result = "!listconcat"; break;
1073 case LISTSPLAT: Result = "!listsplat"; break;
1074 case STRCONCAT: Result = "!strconcat"; break;
1075 case SETOP: Result = "!setop"; break;
1076 }
1077 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1078}
1079
1080static void
1081ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1082 Init *RHS, RecTy *Type) {
1083 ID.AddInteger(Opcode);
1084 ID.AddPointer(LHS);
1085 ID.AddPointer(MHS);
1086 ID.AddPointer(RHS);
1087 ID.AddPointer(Type);
1088}
1089
1090TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1091 RecTy *Type) {
1092 static FoldingSet<TernOpInit> ThePool;
1093
1094 FoldingSetNodeID ID;
1095 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1096
1097 void *IP = nullptr;
1098 if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1099 return I;
1100
1101 TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1102 ThePool.InsertNode(I, IP);
1103 return I;
1104}
1105
1106void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1107 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1108}
1109
1110static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1111 MapResolver R(CurRec);
1112 R.set(LHS, MHSe);
1113 return RHS->resolveReferences(R);
1114}
1115
1116static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1117 Record *CurRec) {
1118 bool Change = false;
1119 Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1120 if (Val != MHSd->getOperator())
1121 Change = true;
1122
1123 SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1124 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1125 Init *Arg = MHSd->getArg(i);
1126 Init *NewArg;
1127 StringInit *ArgName = MHSd->getArgName(i);
1128
1129 if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1130 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1131 else
1132 NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1133
1134 NewArgs.push_back(std::make_pair(NewArg, ArgName));
1135 if (Arg != NewArg)
1136 Change = true;
1137 }
1138
1139 if (Change)
1140 return DagInit::get(Val, nullptr, NewArgs);
1141 return MHSd;
1142}
1143
1144// Applies RHS to all elements of MHS, using LHS as a temp variable.
1145static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1146 Record *CurRec) {
1147 if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1148 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1149
1150 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1151 SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1152
1153 for (Init *&Item : NewList) {
1154 Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1155 if (NewItem != Item)
1156 Item = NewItem;
1157 }
1158 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1159 }
1160
1161 return nullptr;
1162}
1163
1164Init *TernOpInit::Fold(Record *CurRec) const {
1165 switch (getOpcode()) {
1166 case SUBST: {
1167 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1168 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1169 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1170
1171 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1172 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1173 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1174
1175 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1176 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1177 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1178
1179 if (LHSd && MHSd && RHSd) {
1180 Record *Val = RHSd->getDef();
1181 if (LHSd->getAsString() == RHSd->getAsString())
1182 Val = MHSd->getDef();
1183 return DefInit::get(Val);
1184 }
1185 if (LHSv && MHSv && RHSv) {
1186 std::string Val = std::string(RHSv->getName());
1187 if (LHSv->getAsString() == RHSv->getAsString())
1188 Val = std::string(MHSv->getName());
1189 return VarInit::get(Val, getType());
1190 }
1191 if (LHSs && MHSs && RHSs) {
1192 std::string Val = std::string(RHSs->getValue());
1193
1194 std::string::size_type found;
1195 std::string::size_type idx = 0;
1196 while (true) {
1197 found = Val.find(std::string(LHSs->getValue()), idx);
1198 if (found == std::string::npos)
1199 break;
1200 Val.replace(found, LHSs->getValue().size(),
1201 std::string(MHSs->getValue()));
1202 idx = found + MHSs->getValue().size();
1203 }
1204
1205 return StringInit::get(Val);
1206 }
1207 break;
1208 }
1209
1210 case FOREACH: {
1211 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1212 return Result;
1213 break;
1214 }
1215
1216 case IF: {
1217 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1218 LHS->convertInitializerTo(IntRecTy::get()))) {
1219 if (LHSi->getValue())
1220 return MHS;
1221 return RHS;
1222 }
1223 break;
1224 }
1225
1226 case DAG: {
1227 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1228 ListInit *RHSl = dyn_cast<ListInit>(RHS);
1229 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1230 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1231
1232 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1233 break; // Typically prevented by the parser, but might happen with template args
1234
1235 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1236 SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1237 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1238 for (unsigned i = 0; i != Size; ++i) {
1239 Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1240 Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1241 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1242 return const_cast<TernOpInit *>(this);
1243 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1244 }
1245 return DagInit::get(LHS, nullptr, Children);
1246 }
1247 break;
1248 }
1249 }
1250
1251 return const_cast<TernOpInit *>(this);
1252}
1253
1254Init *TernOpInit::resolveReferences(Resolver &R) const {
1255 Init *lhs = LHS->resolveReferences(R);
1256
1257 if (getOpcode() == IF && lhs != LHS) {
1258 if (IntInit *Value = dyn_cast_or_null<IntInit>(
1259 lhs->convertInitializerTo(IntRecTy::get()))) {
1260 // Short-circuit
1261 if (Value->getValue())
1262 return MHS->resolveReferences(R);
1263 return RHS->resolveReferences(R);
1264 }
1265 }
1266
1267 Init *mhs = MHS->resolveReferences(R);
1268 Init *rhs;
1269
1270 if (getOpcode() == FOREACH) {
1271 ShadowResolver SR(R);
1272 SR.addShadow(lhs);
1273 rhs = RHS->resolveReferences(SR);
1274 } else {
1275 rhs = RHS->resolveReferences(R);
1276 }
1277
1278 if (LHS != lhs || MHS != mhs || RHS != rhs)
1279 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1280 ->Fold(R.getCurrentRecord());
1281 return const_cast<TernOpInit *>(this);
1282}
1283
1284std::string TernOpInit::getAsString() const {
1285 std::string Result;
1286 bool UnquotedLHS = false;
1287 switch (getOpcode()) {
1288 case SUBST: Result = "!subst"; break;
1289 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1290 case IF: Result = "!if"; break;
1291 case DAG: Result = "!dag"; break;
1292 }
1293 return (Result + "(" +
1294 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1295 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1296}
1297
1298static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1299 Init *Start, Init *List, Init *Expr,
1300 RecTy *Type) {
1301 ID.AddPointer(Start);
1302 ID.AddPointer(List);
1303 ID.AddPointer(A);
1304 ID.AddPointer(B);
1305 ID.AddPointer(Expr);
1306 ID.AddPointer(Type);
1307}
1308
1309FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1310 Init *Expr, RecTy *Type) {
1311 static FoldingSet<FoldOpInit> ThePool;
1312
1313 FoldingSetNodeID ID;
1314 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1315
1316 void *IP = nullptr;
1317 if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1318 return I;
1319
1320 FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1321 ThePool.InsertNode(I, IP);
1322 return I;
1323}
1324
1325void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1326 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1327}
1328
1329Init *FoldOpInit::Fold(Record *CurRec) const {
1330 if (ListInit *LI = dyn_cast<ListInit>(List)) {
1331 Init *Accum = Start;
1332 for (Init *Elt : *LI) {
1333 MapResolver R(CurRec);
1334 R.set(A, Accum);
1335 R.set(B, Elt);
1336 Accum = Expr->resolveReferences(R);
1337 }
1338 return Accum;
1339 }
1340 return const_cast<FoldOpInit *>(this);
1341}
1342
1343Init *FoldOpInit::resolveReferences(Resolver &R) const {
1344 Init *NewStart = Start->resolveReferences(R);
1345 Init *NewList = List->resolveReferences(R);
1346 ShadowResolver SR(R);
1347 SR.addShadow(A);
1348 SR.addShadow(B);
1349 Init *NewExpr = Expr->resolveReferences(SR);
1350
1351 if (Start == NewStart && List == NewList && Expr == NewExpr)
1352 return const_cast<FoldOpInit *>(this);
1353
1354 return get(NewStart, NewList, A, B, NewExpr, getType())
1355 ->Fold(R.getCurrentRecord());
1356}
1357
1358Init *FoldOpInit::getBit(unsigned Bit) const {
1359 return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1360}
1361
1362std::string FoldOpInit::getAsString() const {
1363 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1364 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1365 ", " + Expr->getAsString() + ")")
1366 .str();
1367}
1368
1369static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1370 Init *Expr) {
1371 ID.AddPointer(CheckType);
1372 ID.AddPointer(Expr);
1373}
1374
1375IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1376 static FoldingSet<IsAOpInit> ThePool;
1377
1378 FoldingSetNodeID ID;
1379 ProfileIsAOpInit(ID, CheckType, Expr);
1380
1381 void *IP = nullptr;
1382 if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1383 return I;
1384
1385 IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1386 ThePool.InsertNode(I, IP);
1387 return I;
1388}
1389
1390void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1391 ProfileIsAOpInit(ID, CheckType, Expr);
1392}
1393
1394Init *IsAOpInit::Fold() const {
1395 if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1396 // Is the expression type known to be (a subclass of) the desired type?
1397 if (TI->getType()->typeIsConvertibleTo(CheckType))
1398 return IntInit::get(1);
1399
1400 if (isa<RecordRecTy>(CheckType)) {
1401 // If the target type is not a subclass of the expression type, or if
1402 // the expression has fully resolved to a record, we know that it can't
1403 // be of the required type.
1404 if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1405 return IntInit::get(0);
1406 } else {
1407 // We treat non-record types as not castable.
1408 return IntInit::get(0);
1409 }
1410 }
1411 return const_cast<IsAOpInit *>(this);
1412}
1413
1414Init *IsAOpInit::resolveReferences(Resolver &R) const {
1415 Init *NewExpr = Expr->resolveReferences(R);
1416 if (Expr != NewExpr)
1417 return get(CheckType, NewExpr)->Fold();
1418 return const_cast<IsAOpInit *>(this);
1419}
1420
1421Init *IsAOpInit::getBit(unsigned Bit) const {
1422 return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1423}
1424
1425std::string IsAOpInit::getAsString() const {
1426 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1427 Expr->getAsString() + ")")
1428 .str();
1429}
1430
1431RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1432 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1433 for (Record *Rec : RecordType->getClasses()) {
1434 if (RecordVal *Field = Rec->getValue(FieldName))
1435 return Field->getType();
1436 }
1437 }
1438 return nullptr;
1439}
1440
1441Init *
1442TypedInit::convertInitializerTo(RecTy *Ty) const {
1443 if (getType() == Ty || getType()->typeIsA(Ty))
1444 return const_cast<TypedInit *>(this);
1445
1446 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1447 cast<BitsRecTy>(Ty)->getNumBits() == 1)
1448 return BitsInit::get({const_cast<TypedInit *>(this)});
1449
1450 return nullptr;
1451}
1452
1453Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1454 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1455 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1456 unsigned NumBits = T->getNumBits();
1457
1458 SmallVector<Init *, 16> NewBits;
1459 NewBits.reserve(Bits.size());
1460 for (unsigned Bit : Bits) {
1461 if (Bit >= NumBits)
1462 return nullptr;
1463
1464 NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1465 }
1466 return BitsInit::get(NewBits);
1467}
1468
1469Init *TypedInit::getCastTo(RecTy *Ty) const {
1470 // Handle the common case quickly
1471 if (getType() == Ty || getType()->typeIsA(Ty))
1472 return const_cast<TypedInit *>(this);
1473
1474 if (Init *Converted = convertInitializerTo(Ty)) {
1475 assert(!isa<TypedInit>(Converted) ||((!isa<TypedInit>(Converted) || cast<TypedInit>(Converted
)->getType()->typeIsA(Ty)) ? static_cast<void> (0
) : __assert_fail ("!isa<TypedInit>(Converted) || cast<TypedInit>(Converted)->getType()->typeIsA(Ty)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1476, __PRETTY_FUNCTION__))
1476 cast<TypedInit>(Converted)->getType()->typeIsA(Ty))((!isa<TypedInit>(Converted) || cast<TypedInit>(Converted
)->getType()->typeIsA(Ty)) ? static_cast<void> (0
) : __assert_fail ("!isa<TypedInit>(Converted) || cast<TypedInit>(Converted)->getType()->typeIsA(Ty)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1476, __PRETTY_FUNCTION__))
;
1477 return Converted;
1478 }
1479
1480 if (!getType()->typeIsConvertibleTo(Ty))
1481 return nullptr;
1482
1483 return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1484 ->Fold(nullptr);
1485}
1486
1487Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1488 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1489 if (!T) return nullptr; // Cannot subscript a non-list variable.
1490
1491 if (Elements.size() == 1)
1492 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1493
1494 SmallVector<Init*, 8> ListInits;
1495 ListInits.reserve(Elements.size());
1496 for (unsigned Element : Elements)
1497 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1498 Element));
1499 return ListInit::get(ListInits, T->getElementType());
1500}
1501
1502
1503VarInit *VarInit::get(StringRef VN, RecTy *T) {
1504 Init *Value = StringInit::get(VN);
1505 return VarInit::get(Value, T);
1506}
1507
1508VarInit *VarInit::get(Init *VN, RecTy *T) {
1509 using Key = std::pair<RecTy *, Init *>;
1510 static DenseMap<Key, VarInit*> ThePool;
1511
1512 Key TheKey(std::make_pair(T, VN));
1513
1514 VarInit *&I = ThePool[TheKey];
1515 if (!I)
1516 I = new(Allocator) VarInit(VN, T);
1517 return I;
1518}
1519
1520StringRef VarInit::getName() const {
1521 StringInit *NameString = cast<StringInit>(getNameInit());
1522 return NameString->getValue();
1523}
1524
1525Init *VarInit::getBit(unsigned Bit) const {
1526 if (getType() == BitRecTy::get())
1527 return const_cast<VarInit*>(this);
1528 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1529}
1530
1531Init *VarInit::resolveReferences(Resolver &R) const {
1532 if (Init *Val = R.resolve(VarName))
1533 return Val;
1534 return const_cast<VarInit *>(this);
1535}
1536
1537VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1538 using Key = std::pair<TypedInit *, unsigned>;
1539 static DenseMap<Key, VarBitInit*> ThePool;
1540
1541 Key TheKey(std::make_pair(T, B));
1542
1543 VarBitInit *&I = ThePool[TheKey];
1544 if (!I)
1545 I = new(Allocator) VarBitInit(T, B);
1546 return I;
1547}
1548
1549std::string VarBitInit::getAsString() const {
1550 return TI->getAsString() + "{" + utostr(Bit) + "}";
1551}
1552
1553Init *VarBitInit::resolveReferences(Resolver &R) const {
1554 Init *I = TI->resolveReferences(R);
1555 if (TI != I)
1556 return I->getBit(getBitNum());
1557
1558 return const_cast<VarBitInit*>(this);
1559}
1560
1561VarListElementInit *VarListElementInit::get(TypedInit *T,
1562 unsigned E) {
1563 using Key = std::pair<TypedInit *, unsigned>;
1564 static DenseMap<Key, VarListElementInit*> ThePool;
1565
1566 Key TheKey(std::make_pair(T, E));
1567
1568 VarListElementInit *&I = ThePool[TheKey];
1569 if (!I) I = new(Allocator) VarListElementInit(T, E);
1570 return I;
1571}
1572
1573std::string VarListElementInit::getAsString() const {
1574 return TI->getAsString() + "[" + utostr(Element) + "]";
1575}
1576
1577Init *VarListElementInit::resolveReferences(Resolver &R) const {
1578 Init *NewTI = TI->resolveReferences(R);
1579 if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1580 // Leave out-of-bounds array references as-is. This can happen without
1581 // being an error, e.g. in the untaken "branch" of an !if expression.
1582 if (getElementNum() < List->size())
1583 return List->getElement(getElementNum());
1584 }
1585 if (NewTI != TI && isa<TypedInit>(NewTI))
1586 return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1587 return const_cast<VarListElementInit *>(this);
1588}
1589
1590Init *VarListElementInit::getBit(unsigned Bit) const {
1591 if (getType() == BitRecTy::get())
1592 return const_cast<VarListElementInit*>(this);
1593 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1594}
1595
1596DefInit::DefInit(Record *D)
1597 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1598
1599DefInit *DefInit::get(Record *R) {
1600 return R->getDefInit();
1601}
1602
1603Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1604 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1605 if (getType()->typeIsConvertibleTo(RRT))
1606 return const_cast<DefInit *>(this);
1607 return nullptr;
1608}
1609
1610RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1611 if (const RecordVal *RV = Def->getValue(FieldName))
1612 return RV->getType();
1613 return nullptr;
1614}
1615
1616std::string DefInit::getAsString() const { return std::string(Def->getName()); }
1617
1618static void ProfileVarDefInit(FoldingSetNodeID &ID,
1619 Record *Class,
1620 ArrayRef<Init *> Args) {
1621 ID.AddInteger(Args.size());
1622 ID.AddPointer(Class);
1623
1624 for (Init *I : Args)
1625 ID.AddPointer(I);
1626}
1627
1628VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1629 static FoldingSet<VarDefInit> ThePool;
1630
1631 FoldingSetNodeID ID;
1632 ProfileVarDefInit(ID, Class, Args);
1633
1634 void *IP = nullptr;
1635 if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1636 return I;
1637
1638 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1639 alignof(VarDefInit));
1640 VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1641 std::uninitialized_copy(Args.begin(), Args.end(),
1642 I->getTrailingObjects<Init *>());
1643 ThePool.InsertNode(I, IP);
1644 return I;
1645}
1646
1647void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1648 ProfileVarDefInit(ID, Class, args());
1649}
1650
1651DefInit *VarDefInit::instantiate() {
1652 if (!Def) {
1653 RecordKeeper &Records = Class->getRecords();
1654 auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1655 Class->getLoc(), Records,
1656 /*IsAnonymous=*/true);
1657 Record *NewRec = NewRecOwner.get();
1658
1659 // Copy values from class to instance
1660 for (const RecordVal &Val : Class->getValues())
1661 NewRec->addValue(Val);
1662
1663 // Substitute and resolve template arguments
1664 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1665 MapResolver R(NewRec);
1666
1667 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1668 if (i < args_size())
1669 R.set(TArgs[i], getArg(i));
1670 else
1671 R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1672
1673 NewRec->removeValue(TArgs[i]);
1674 }
1675
1676 NewRec->resolveReferences(R);
1677
1678 // Add superclasses.
1679 ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1680 for (const auto &SCPair : SCs)
1681 NewRec->addSuperClass(SCPair.first, SCPair.second);
1682
1683 NewRec->addSuperClass(Class,
1684 SMRange(Class->getLoc().back(),
1685 Class->getLoc().back()));
1686
1687 // Resolve internal references and store in record keeper
1688 NewRec->resolveReferences();
1689 Records.addDef(std::move(NewRecOwner));
1690
1691 Def = DefInit::get(NewRec);
1692 }
1693
1694 return Def;
1695}
1696
1697Init *VarDefInit::resolveReferences(Resolver &R) const {
1698 TrackUnresolvedResolver UR(&R);
1699 bool Changed = false;
1700 SmallVector<Init *, 8> NewArgs;
1701 NewArgs.reserve(args_size());
1702
1703 for (Init *Arg : args()) {
1704 Init *NewArg = Arg->resolveReferences(UR);
1705 NewArgs.push_back(NewArg);
1706 Changed |= NewArg != Arg;
1707 }
1708
1709 if (Changed) {
1710 auto New = VarDefInit::get(Class, NewArgs);
1711 if (!UR.foundUnresolved())
1712 return New->instantiate();
1713 return New;
1714 }
1715 return const_cast<VarDefInit *>(this);
1716}
1717
1718Init *VarDefInit::Fold() const {
1719 if (Def)
1720 return Def;
1721
1722 TrackUnresolvedResolver R;
1723 for (Init *Arg : args())
1724 Arg->resolveReferences(R);
1725
1726 if (!R.foundUnresolved())
1727 return const_cast<VarDefInit *>(this)->instantiate();
1728 return const_cast<VarDefInit *>(this);
1729}
1730
1731std::string VarDefInit::getAsString() const {
1732 std::string Result = Class->getNameInitAsString() + "<";
1733 const char *sep = "";
1734 for (Init *Arg : args()) {
1735 Result += sep;
1736 sep = ", ";
1737 Result += Arg->getAsString();
1738 }
1739 return Result + ">";
1740}
1741
1742FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1743 using Key = std::pair<Init *, StringInit *>;
1744 static DenseMap<Key, FieldInit*> ThePool;
1745
1746 Key TheKey(std::make_pair(R, FN));
1747
1748 FieldInit *&I = ThePool[TheKey];
1749 if (!I) I = new(Allocator) FieldInit(R, FN);
1750 return I;
1751}
1752
1753Init *FieldInit::getBit(unsigned Bit) const {
1754 if (getType() == BitRecTy::get())
1755 return const_cast<FieldInit*>(this);
1756 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1757}
1758
1759Init *FieldInit::resolveReferences(Resolver &R) const {
1760 Init *NewRec = Rec->resolveReferences(R);
1761 if (NewRec != Rec)
1762 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1763 return const_cast<FieldInit *>(this);
1764}
1765
1766Init *FieldInit::Fold(Record *CurRec) const {
1767 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1768 Record *Def = DI->getDef();
1769 if (Def == CurRec)
1770 PrintFatalError(CurRec->getLoc(),
1771 Twine("Attempting to access field '") +
1772 FieldName->getAsUnquotedString() + "' of '" +
1773 Rec->getAsString() + "' is a forbidden self-reference");
1774 Init *FieldVal = Def->getValue(FieldName)->getValue();
1775 if (FieldVal->isComplete())
1776 return FieldVal;
1777 }
1778 return const_cast<FieldInit *>(this);
1779}
1780
1781bool FieldInit::isConcrete() const {
1782 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1783 Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
1784 return FieldVal->isConcrete();
1785 }
1786 return false;
1787}
1788
1789static void ProfileCondOpInit(FoldingSetNodeID &ID,
1790 ArrayRef<Init *> CondRange,
1791 ArrayRef<Init *> ValRange,
1792 const RecTy *ValType) {
1793 assert(CondRange.size() == ValRange.size() &&((CondRange.size() == ValRange.size() && "Number of conditions and values must match!"
) ? static_cast<void> (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1794, __PRETTY_FUNCTION__))
1794 "Number of conditions and values must match!")((CondRange.size() == ValRange.size() && "Number of conditions and values must match!"
) ? static_cast<void> (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1794, __PRETTY_FUNCTION__))
;
1795 ID.AddPointer(ValType);
1796 ArrayRef<Init *>::iterator Case = CondRange.begin();
1797 ArrayRef<Init *>::iterator Val = ValRange.begin();
1798
1799 while (Case != CondRange.end()) {
1800 ID.AddPointer(*Case++);
1801 ID.AddPointer(*Val++);
1802 }
1803}
1804
1805void CondOpInit::Profile(FoldingSetNodeID &ID) const {
1806 ProfileCondOpInit(ID,
1807 makeArrayRef(getTrailingObjects<Init *>(), NumConds),
1808 makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
1809 ValType);
1810}
1811
1812CondOpInit *
1813CondOpInit::get(ArrayRef<Init *> CondRange,
1814 ArrayRef<Init *> ValRange, RecTy *Ty) {
1815 assert(CondRange.size() == ValRange.size() &&((CondRange.size() == ValRange.size() && "Number of conditions and values must match!"
) ? static_cast<void> (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1816, __PRETTY_FUNCTION__))
1816 "Number of conditions and values must match!")((CondRange.size() == ValRange.size() && "Number of conditions and values must match!"
) ? static_cast<void> (0) : __assert_fail ("CondRange.size() == ValRange.size() && \"Number of conditions and values must match!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1816, __PRETTY_FUNCTION__))
;
1817
1818 static FoldingSet<CondOpInit> ThePool;
1819 FoldingSetNodeID ID;
1820 ProfileCondOpInit(ID, CondRange, ValRange, Ty);
1821
1822 void *IP = nullptr;
1823 if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1824 return I;
1825
1826 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()),
1827 alignof(BitsInit));
1828 CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
1829
1830 std::uninitialized_copy(CondRange.begin(), CondRange.end(),
1831 I->getTrailingObjects<Init *>());
1832 std::uninitialized_copy(ValRange.begin(), ValRange.end(),
1833 I->getTrailingObjects<Init *>()+CondRange.size());
1834 ThePool.InsertNode(I, IP);
1835 return I;
1836}
1837
1838Init *CondOpInit::resolveReferences(Resolver &R) const {
1839 SmallVector<Init*, 4> NewConds;
1840 bool Changed = false;
1841 for (const Init *Case : getConds()) {
1842 Init *NewCase = Case->resolveReferences(R);
1843 NewConds.push_back(NewCase);
1844 Changed |= NewCase != Case;
1845 }
1846
1847 SmallVector<Init*, 4> NewVals;
1848 for (const Init *Val : getVals()) {
1849 Init *NewVal = Val->resolveReferences(R);
1850 NewVals.push_back(NewVal);
1851 Changed |= NewVal != Val;
1852 }
1853
1854 if (Changed)
1855 return (CondOpInit::get(NewConds, NewVals,
1856 getValType()))->Fold(R.getCurrentRecord());
1857
1858 return const_cast<CondOpInit *>(this);
1859}
1860
1861Init *CondOpInit::Fold(Record *CurRec) const {
1862 for ( unsigned i = 0; i < NumConds; ++i) {
1863 Init *Cond = getCond(i);
1864 Init *Val = getVal(i);
1865
1866 if (IntInit *CondI = dyn_cast_or_null<IntInit>(
1867 Cond->convertInitializerTo(IntRecTy::get()))) {
1868 if (CondI->getValue())
1869 return Val->convertInitializerTo(getValType());
1870 } else
1871 return const_cast<CondOpInit *>(this);
1872 }
1873
1874 PrintFatalError(CurRec->getLoc(),
1875 CurRec->getName() +
1876 " does not have any true condition in:" +
1877 this->getAsString());
1878 return nullptr;
1879}
1880
1881bool CondOpInit::isConcrete() const {
1882 for (const Init *Case : getConds())
1883 if (!Case->isConcrete())
1884 return false;
1885
1886 for (const Init *Val : getVals())
1887 if (!Val->isConcrete())
1888 return false;
1889
1890 return true;
1891}
1892
1893bool CondOpInit::isComplete() const {
1894 for (const Init *Case : getConds())
1895 if (!Case->isComplete())
1896 return false;
1897
1898 for (const Init *Val : getVals())
1899 if (!Val->isConcrete())
1900 return false;
1901
1902 return true;
1903}
1904
1905std::string CondOpInit::getAsString() const {
1906 std::string Result = "!cond(";
1907 for (unsigned i = 0; i < getNumConds(); i++) {
1908 Result += getCond(i)->getAsString() + ": ";
1909 Result += getVal(i)->getAsString();
1910 if (i != getNumConds()-1)
1911 Result += ", ";
1912 }
1913 return Result + ")";
1914}
1915
1916Init *CondOpInit::getBit(unsigned Bit) const {
1917 return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
1918}
1919
1920static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1921 ArrayRef<Init *> ArgRange,
1922 ArrayRef<StringInit *> NameRange) {
1923 ID.AddPointer(V);
1924 ID.AddPointer(VN);
1925
1926 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1927 ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1928 while (Arg != ArgRange.end()) {
1929 assert(Name != NameRange.end() && "Arg name underflow!")((Name != NameRange.end() && "Arg name underflow!") ?
static_cast<void> (0) : __assert_fail ("Name != NameRange.end() && \"Arg name underflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1929, __PRETTY_FUNCTION__))
;
1930 ID.AddPointer(*Arg++);
1931 ID.AddPointer(*Name++);
1932 }
1933 assert(Name == NameRange.end() && "Arg name overflow!")((Name == NameRange.end() && "Arg name overflow!") ? static_cast
<void> (0) : __assert_fail ("Name == NameRange.end() && \"Arg name overflow!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 1933, __PRETTY_FUNCTION__))
;
1934}
1935
1936DagInit *
1937DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1938 ArrayRef<StringInit *> NameRange) {
1939 static FoldingSet<DagInit> ThePool;
1940
1941 FoldingSetNodeID ID;
1942 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1943
1944 void *IP = nullptr;
1945 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1946 return I;
1947
1948 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1949 DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1950 std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1951 I->getTrailingObjects<Init *>());
1952 std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1953 I->getTrailingObjects<StringInit *>());
1954 ThePool.InsertNode(I, IP);
1955 return I;
1956}
1957
1958DagInit *
1959DagInit::get(Init *V, StringInit *VN,
1960 ArrayRef<std::pair<Init*, StringInit*>> args) {
1961 SmallVector<Init *, 8> Args;
1962 SmallVector<StringInit *, 8> Names;
1963
1964 for (const auto &Arg : args) {
1965 Args.push_back(Arg.first);
1966 Names.push_back(Arg.second);
1967 }
1968
1969 return DagInit::get(V, VN, Args, Names);
1970}
1971
1972void DagInit::Profile(FoldingSetNodeID &ID) const {
1973 ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1974}
1975
1976Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
1977 if (DefInit *DefI = dyn_cast<DefInit>(Val))
1978 return DefI->getDef();
1979 PrintFatalError(Loc, "Expected record as operator");
1980 return nullptr;
1981}
1982
1983Init *DagInit::resolveReferences(Resolver &R) const {
1984 SmallVector<Init*, 8> NewArgs;
1985 NewArgs.reserve(arg_size());
1986 bool ArgsChanged = false;
1987 for (const Init *Arg : getArgs()) {
1988 Init *NewArg = Arg->resolveReferences(R);
1989 NewArgs.push_back(NewArg);
1990 ArgsChanged |= NewArg != Arg;
1991 }
1992
1993 Init *Op = Val->resolveReferences(R);
1994 if (Op != Val || ArgsChanged)
1995 return DagInit::get(Op, ValName, NewArgs, getArgNames());
1996
1997 return const_cast<DagInit *>(this);
1998}
1999
2000bool DagInit::isConcrete() const {
2001 if (!Val->isConcrete())
2002 return false;
2003 for (const Init *Elt : getArgs()) {
2004 if (!Elt->isConcrete())
2005 return false;
2006 }
2007 return true;
2008}
2009
2010std::string DagInit::getAsString() const {
2011 std::string Result = "(" + Val->getAsString();
2012 if (ValName)
2013 Result += ":" + ValName->getAsUnquotedString();
2014 if (!arg_empty()) {
2015 Result += " " + getArg(0)->getAsString();
2016 if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
2017 for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
2018 Result += ", " + getArg(i)->getAsString();
2019 if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
2020 }
2021 }
2022 return Result + ")";
2023}
2024
2025//===----------------------------------------------------------------------===//
2026// Other implementations
2027//===----------------------------------------------------------------------===//
2028
2029RecordVal::RecordVal(Init *N, RecTy *T, bool P)
2030 : Name(N), TyAndPrefix(T, P) {
2031 setValue(UnsetInit::get());
2032 assert(Value && "Cannot create unset value for current type!")((Value && "Cannot create unset value for current type!"
) ? static_cast<void> (0) : __assert_fail ("Value && \"Cannot create unset value for current type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 2032, __PRETTY_FUNCTION__))
;
2033}
2034
2035StringRef RecordVal::getName() const {
2036 return cast<StringInit>(getNameInit())->getValue();
2037}
2038
2039bool RecordVal::setValue(Init *V) {
2040 if (V) {
2041 Value = V->getCastTo(getType());
2042 if (Value) {
2043 assert(!isa<TypedInit>(Value) ||((!isa<TypedInit>(Value) || cast<TypedInit>(Value
)->getType()->typeIsA(getType())) ? static_cast<void
> (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 2044, __PRETTY_FUNCTION__))
2044 cast<TypedInit>(Value)->getType()->typeIsA(getType()))((!isa<TypedInit>(Value) || cast<TypedInit>(Value
)->getType()->typeIsA(getType())) ? static_cast<void
> (0) : __assert_fail ("!isa<TypedInit>(Value) || cast<TypedInit>(Value)->getType()->typeIsA(getType())"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 2044, __PRETTY_FUNCTION__))
;
2045 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2046 if (!isa<BitsInit>(Value)) {
2047 SmallVector<Init *, 64> Bits;
2048 Bits.reserve(BTy->getNumBits());
2049 for (unsigned i = 0, e = BTy->getNumBits(); i < e; ++i)
2050 Bits.push_back(Value->getBit(i));
2051 Value = BitsInit::get(Bits);
2052 }
2053 }
2054 }
2055 return Value == nullptr;
2056 }
2057 Value = nullptr;
2058 return false;
2059}
2060
2061#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2062LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordVal::dump() const { errs() << *this; }
2063#endif
2064
2065void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2066 if (getPrefix()) OS << "field ";
2067 OS << *getType() << " " << getNameInitAsString();
2068
2069 if (getValue())
2070 OS << " = " << *getValue();
2071
2072 if (PrintSem) OS << ";\n";
2073}
2074
2075unsigned Record::LastID = 0;
2076
2077void Record::checkName() {
2078 // Ensure the record name has string type.
2079 const TypedInit *TypedName = cast<const TypedInit>(Name);
2080 if (!isa<StringRecTy>(TypedName->getType()))
2081 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2082 "' is not a string!");
2083}
2084
2085RecordRecTy *Record::getType() {
2086 SmallVector<Record *, 4> DirectSCs;
2087 getDirectSuperClasses(DirectSCs);
2088 return RecordRecTy::get(DirectSCs);
2089}
2090
2091DefInit *Record::getDefInit() {
2092 if (!TheInit)
2093 TheInit = new(Allocator) DefInit(this);
2094 return TheInit;
2095}
2096
2097void Record::setName(Init *NewName) {
2098 Name = NewName;
2099 checkName();
2100 // DO NOT resolve record values to the name at this point because
2101 // there might be default values for arguments of this def. Those
2102 // arguments might not have been resolved yet so we don't want to
2103 // prematurely assume values for those arguments were not passed to
2104 // this def.
2105 //
2106 // Nonetheless, it may be that some of this Record's values
2107 // reference the record name. Indeed, the reason for having the
2108 // record name be an Init is to provide this flexibility. The extra
2109 // resolve steps after completely instantiating defs takes care of
2110 // this. See TGParser::ParseDef and TGParser::ParseDefm.
2111}
2112
2113void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2114 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2115 while (!SCs.empty()) {
2116 // Superclasses are in reverse preorder, so 'back' is a direct superclass,
2117 // and its transitive superclasses are directly preceding it.
2118 Record *SC = SCs.back().first;
2119 SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2120 Classes.push_back(SC);
2121 }
2122}
2123
2124void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2125 for (RecordVal &Value : Values) {
2126 if (SkipVal == &Value) // Skip resolve the same field as the given one
2127 continue;
2128 if (Init *V = Value.getValue()) {
2129 Init *VR = V->resolveReferences(R);
2130 if (Value.setValue(VR)) {
2131 std::string Type;
2132 if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2133 Type =
2134 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2135 PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
2136 "is found when setting '" +
2137 Value.getNameInitAsString() +
2138 "' of type '" +
2139 Value.getType()->getAsString() +
2140 "' after resolving references: " +
2141 VR->getAsUnquotedString() + "\n");
2142 }
2143 }
2144 }
2145 Init *OldName = getNameInit();
2146 Init *NewName = Name->resolveReferences(R);
2147 if (NewName != OldName) {
2148 // Re-register with RecordKeeper.
2149 setName(NewName);
2150 }
2151}
2152
2153void Record::resolveReferences() {
2154 RecordResolver R(*this);
2155 R.setFinal(true);
2156 resolveReferences(R);
2157}
2158
2159void Record::resolveReferencesTo(const RecordVal *RV) {
2160 RecordValResolver R(*this, RV);
2161 resolveReferences(R, RV);
2162}
2163
2164#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2165LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Record::dump() const { errs() << *this; }
2166#endif
2167
2168raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2169 OS << R.getNameInitAsString();
2170
2171 ArrayRef<Init *> TArgs = R.getTemplateArgs();
2172 if (!TArgs.empty()) {
2173 OS << "<";
2174 bool NeedComma = false;
2175 for (const Init *TA : TArgs) {
2176 if (NeedComma) OS << ", ";
2177 NeedComma = true;
2178 const RecordVal *RV = R.getValue(TA);
2179 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-11~++20200309111110+2c36c23f347/llvm/lib/TableGen/Record.cpp"
, 2179, __PRETTY_FUNCTION__))
;
2180 RV->print(OS, false);
2181 }
2182 OS << ">";
2183 }
2184
2185 OS << " {";
2186 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2187 if (!SC.empty()) {
2188 OS << "\t//";
2189 for (const auto &SuperPair : SC)
2190 OS << " " << SuperPair.first->getNameInitAsString();
2191 }
2192 OS << "\n";
2193
2194 for (const RecordVal &Val : R.getValues())
2195 if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2196 OS << Val;
2197 for (const RecordVal &Val : R.getValues())
2198 if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2199 OS << Val;
2200
2201 return OS << "}\n";
2202}
2203
2204Init *Record::getValueInit(StringRef FieldName) const {
2205 const RecordVal *R = getValue(FieldName);
2206 if (!R || !R->getValue())
2207 PrintFatalError(getLoc(), "Record `" + getName() +
2208 "' does not have a field named `" + FieldName + "'!\n");
2209 return R->getValue();
2210}
2211
2212StringRef Record::getValueAsString(StringRef FieldName) const {
2213 const RecordVal *R = getValue(FieldName);
2214 if (!R || !R->getValue())
2215 PrintFatalError(getLoc(), "Record `" + getName() +
2216 "' does not have a field named `" + FieldName + "'!\n");
2217
2218 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2219 return SI->getValue();
2220 if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2221 return CI->getValue();
2222
2223 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2224 FieldName + "' does not have a string initializer!");
2225}
2226
2227BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2228 const RecordVal *R = getValue(FieldName);
2229 if (!R || !R->getValue())
2230 PrintFatalError(getLoc(), "Record `" + getName() +
2231 "' does not have a field named `" + FieldName + "'!\n");
2232
2233 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2234 return BI;
2235 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2236 FieldName + "' does not have a BitsInit initializer!");
2237}
2238
2239ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2240 const RecordVal *R = getValue(FieldName);
2241 if (!R || !R->getValue())
2242 PrintFatalError(getLoc(), "Record `" + getName() +
2243 "' does not have a field named `" + FieldName + "'!\n");
2244
2245 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2246 return LI;
2247 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2248 FieldName + "' does not have a list initializer!");
2249}
2250
2251std::vector<Record*>
2252Record::getValueAsListOfDefs(StringRef FieldName) const {
2253 ListInit *List = getValueAsListInit(FieldName);
2254 std::vector<Record*> Defs;
2255 for (Init *I : List->getValues()) {
2256 if (DefInit *DI = dyn_cast<DefInit>(I))
2257 Defs.push_back(DI->getDef());
2258 else
2259 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2260 FieldName + "' list is not entirely DefInit!");
2261 }
2262 return Defs;
2263}
2264
2265int64_t Record::getValueAsInt(StringRef FieldName) const {
2266 const RecordVal *R = getValue(FieldName);
2267 if (!R || !R->getValue())
2268 PrintFatalError(getLoc(), "Record `" + getName() +
2269 "' does not have a field named `" + FieldName + "'!\n");
2270
2271 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2272 return II->getValue();
2273 PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2274 FieldName +
2275 "' does not have an int initializer: " +
2276 R->getValue()->getAsString());
2277}
2278
2279std::vector<int64_t>
2280Record::getValueAsListOfInts(StringRef FieldName) const {
2281 ListInit *List = getValueAsListInit(FieldName);
2282 std::vector<int64_t> Ints;
2283 for (Init *I : List->getValues()) {
2284 if (IntInit *II = dyn_cast<IntInit>(I))
2285 Ints.push_back(II->getValue());
2286 else
2287 PrintFatalError(getLoc(),
2288 Twine("Record `") + getName() + "', field `" + FieldName +
2289 "' does not have a list of ints initializer: " +
2290 I->getAsString());
2291 }
2292 return Ints;
2293}
2294
2295std::vector<StringRef>
2296Record::getValueAsListOfStrings(StringRef FieldName) const {
2297 ListInit *List = getValueAsListInit(FieldName);
2298 std::vector<StringRef> Strings;
2299 for (Init *I : List->getValues()) {
2300 if (StringInit *SI = dyn_cast<StringInit>(I))
2301 Strings.push_back(SI->getValue());
2302 else
2303 PrintFatalError(getLoc(),
2304 Twine("Record `") + getName() + "', field `" + FieldName +
2305 "' does not have a list of strings initializer: " +
2306 I->getAsString());
2307 }
2308 return Strings;
2309}
2310
2311Record *Record::getValueAsDef(StringRef FieldName) const {
2312 const RecordVal *R = getValue(FieldName);
2313 if (!R || !R->getValue())
2314 PrintFatalError(getLoc(), "Record `" + getName() +
2315 "' does not have a field named `" + FieldName + "'!\n");
2316
2317 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2318 return DI->getDef();
2319 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2320 FieldName + "' does not have a def initializer!");
2321}
2322
2323Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
2324 const RecordVal *R = getValue(FieldName);
2325 if (!R || !R->getValue())
2326 PrintFatalError(getLoc(), "Record `" + getName() +
2327 "' does not have a field named `" + FieldName + "'!\n");
2328
2329 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2330 return DI->getDef();
2331 if (isa<UnsetInit>(R->getValue()))
2332 return nullptr;
2333 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2334 FieldName + "' does not have either a def initializer or '?'!");
2335}
2336
2337
2338bool Record::getValueAsBit(StringRef FieldName) const {
2339 const RecordVal *R = getValue(FieldName);
2340 if (!R || !R->getValue())
2341 PrintFatalError(getLoc(), "Record `" + getName() +
2342 "' does not have a field named `" + FieldName + "'!\n");
2343
2344 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2345 return BI->getValue();
2346 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2347 FieldName + "' does not have a bit initializer!");
2348}
2349
2350bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2351 const RecordVal *R = getValue(FieldName);
2352 if (!R || !R->getValue())
2353 PrintFatalError(getLoc(), "Record `" + getName() +
2354 "' does not have a field named `" + FieldName.str() + "'!\n");
2355
2356 if (isa<UnsetInit>(R->getValue())) {
2357 Unset = true;
2358 return false;
2359 }
2360 Unset = false;
2361 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2362 return BI->getValue();
2363 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2364 FieldName + "' does not have a bit initializer!");
2365}
2366
2367DagInit *Record::getValueAsDag(StringRef FieldName) const {
2368 const RecordVal *R = getValue(FieldName);
2369 if (!R || !R->getValue())
2370 PrintFatalError(getLoc(), "Record `" + getName() +
2371 "' does not have a field named `" + FieldName + "'!\n");
2372
2373 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2374 return DI;
2375 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2376 FieldName + "' does not have a dag initializer!");
2377}
2378
2379#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2380LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RecordKeeper::dump() const { errs() << *this; }
2381#endif
2382
2383raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2384 OS << "------------- Classes -----------------\n";
2385 for (const auto &C : RK.getClasses())
2386 OS << "class " << *C.second;
2387
2388 OS << "------------- Defs -----------------\n";
2389 for (const auto &D : RK.getDefs())
2390 OS << "def " << *D.second;
2391 return OS;
2392}
2393
2394/// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2395/// an identifier.
2396Init *RecordKeeper::getNewAnonymousName() {
2397 return StringInit::get("anonymous_" + utostr(AnonCounter++));
2398}
2399
2400std::vector<Record *>
2401RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2402 Record *Class = getClass(ClassName);
2403 if (!Class)
2404 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2405
2406 std::vector<Record*> Defs;
2407 for (const auto &D : getDefs())
2408 if (D.second->isSubClassOf(Class))
2409 Defs.push_back(D.second.get());
2410
2411 return Defs;
2412}
2413
2414Init *MapResolver::resolve(Init *VarName) {
2415 auto It = Map.find(VarName);
2416 if (It == Map.end())
2417 return nullptr;
2418
2419 Init *I = It->second.V;
2420
2421 if (!It->second.Resolved && Map.size() > 1) {
2422 // Resolve mutual references among the mapped variables, but prevent
2423 // infinite recursion.
2424 Map.erase(It);
2425 I = I->resolveReferences(*this);
2426 Map[VarName] = {I, true};
2427 }
2428
2429 return I;
2430}
2431
2432Init *RecordResolver::resolve(Init *VarName) {
2433 Init *Val = Cache.lookup(VarName);
2434 if (Val)
2435 return Val;
2436
2437 for (Init *S : Stack) {
2438 if (S == VarName)
2439 return nullptr; // prevent infinite recursion
2440 }
2441
2442 if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2443 if (!isa<UnsetInit>(RV->getValue())) {
2444 Val = RV->getValue();
2445 Stack.push_back(VarName);
2446 Val = Val->resolveReferences(*this);
2447 Stack.pop_back();
2448 }
2449 }
2450
2451 Cache[VarName] = Val;
2452 return Val;
2453}
2454
2455Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2456 Init *I = nullptr;
2457
2458 if (R) {
2459 I = R->resolve(VarName);
2460 if (I && !FoundUnresolved) {
2461 // Do not recurse into the resolved initializer, as that would change
2462 // the behavior of the resolver we're delegating, but do check to see
2463 // if there are unresolved variables remaining.
2464 TrackUnresolvedResolver Sub;
2465 I->resolveReferences(Sub);
2466 FoundUnresolved |= Sub.FoundUnresolved;
2467 }
2468 }
2469
2470 if (!I)
2471 FoundUnresolved = true;
2472 return I;
2473}
2474
2475Init *HasReferenceResolver::resolve(Init *VarName)
2476{
2477 if (VarName == VarNameToTrack)
2478 Found = true;
2479 return nullptr;
2480}