[MIPS GlobalISel] Select MSA vector generic and builtin add
[llvm-complete.git] / lib / TableGen / Record.cpp
blob835ef8c7141b9b2da3d2d32d8d805bd6b5dd895f
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.
11 //===----------------------------------------------------------------------===//
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>
40 using namespace llvm;
42 #define DEBUG_TYPE "tblgen-records"
44 static BumpPtrAllocator Allocator;
46 STATISTIC(CodeInitsConstructed,
47 "The total number of unique CodeInits constructed");
49 //===----------------------------------------------------------------------===//
50 // Type implementations
51 //===----------------------------------------------------------------------===//
53 BitRecTy BitRecTy::Shared;
54 CodeRecTy CodeRecTy::Shared;
55 IntRecTy IntRecTy::Shared;
56 StringRecTy StringRecTy::Shared;
57 DagRecTy DagRecTy::Shared;
59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
61 #endif
63 ListRecTy *RecTy::getListTy() {
64 if (!ListTy)
65 ListTy = new(Allocator) ListRecTy(this);
66 return ListTy;
69 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
70 assert(RHS && "NULL pointer");
71 return Kind == RHS->getRecTyKind();
74 bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
76 bool 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;
84 BitsRecTy *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;
94 std::string BitsRecTy::getAsString() const {
95 return "bits<" + utostr(Size) + ">";
98 bool 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);
105 bool BitsRecTy::typeIsA(const RecTy *RHS) const {
106 if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
107 return RHSb->Size == Size;
108 return false;
111 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
112 RecTyKind kind = RHS->getRecTyKind();
113 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
116 bool CodeRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
117 RecTyKind Kind = RHS->getRecTyKind();
118 return Kind == CodeRecTyKind || Kind == StringRecTyKind;
121 std::string StringRecTy::getAsString() const {
122 return "string";
125 bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
126 RecTyKind Kind = RHS->getRecTyKind();
127 return Kind == StringRecTyKind || Kind == CodeRecTyKind;
130 std::string ListRecTy::getAsString() const {
131 return "list<" + Ty->getAsString() + ">";
134 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
135 if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
136 return Ty->typeIsConvertibleTo(ListTy->getElementType());
137 return false;
140 bool ListRecTy::typeIsA(const RecTy *RHS) const {
141 if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
142 return getElementType()->typeIsA(RHSl->getElementType());
143 return false;
146 std::string DagRecTy::getAsString() const {
147 return "dag";
150 static void ProfileRecordRecTy(FoldingSetNodeID &ID,
151 ArrayRef<Record *> Classes) {
152 ID.AddInteger(Classes.size());
153 for (Record *R : Classes)
154 ID.AddPointer(R);
157 RecordRecTy *RecordRecTy::get(ArrayRef<Record *> UnsortedClasses) {
158 if (UnsortedClasses.empty()) {
159 static RecordRecTy AnyRecord(0);
160 return &AnyRecord;
163 FoldingSet<RecordRecTy> &ThePool =
164 UnsortedClasses[0]->getRecords().RecordTypePool;
166 SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
167 UnsortedClasses.end());
168 llvm::sort(Classes, [](Record *LHS, Record *RHS) {
169 return LHS->getNameInitAsString() < RHS->getNameInitAsString();
172 FoldingSetNodeID ID;
173 ProfileRecordRecTy(ID, Classes);
175 void *IP = nullptr;
176 if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
177 return Ty;
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]));
185 assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
187 #endif
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;
198 void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
199 ProfileRecordRecTy(ID, getClasses());
202 std::string RecordRecTy::getAsString() const {
203 if (NumClasses == 1)
204 return getClasses()[0]->getNameInitAsString();
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();
214 Str += "}";
215 return Str;
218 bool RecordRecTy::isSubClassOf(Record *Class) const {
219 return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
220 return MySuperClass == Class ||
221 MySuperClass->isSubClassOf(Class);
225 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
226 if (this == RHS)
227 return true;
229 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
230 if (!RTy)
231 return false;
233 return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
234 return isSubClassOf(TargetClass);
238 bool RecordRecTy::typeIsA(const RecTy *RHS) const {
239 return typeIsConvertibleTo(RHS);
242 static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
243 SmallVector<Record *, 4> CommonSuperClasses;
244 SmallVector<Record *, 4> Stack;
246 Stack.insert(Stack.end(), T1->classes_begin(), T1->classes_end());
248 while (!Stack.empty()) {
249 Record *R = Stack.back();
250 Stack.pop_back();
252 if (T2->isSubClassOf(R)) {
253 CommonSuperClasses.push_back(R);
254 } else {
255 R->getDirectSuperClasses(Stack);
259 return RecordRecTy::get(CommonSuperClasses);
262 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
263 if (T1 == T2)
264 return T1;
266 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
267 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
268 return resolveRecordTypes(RecTy1, RecTy2);
271 if (T1->typeIsConvertibleTo(T2))
272 return T2;
273 if (T2->typeIsConvertibleTo(T1))
274 return T1;
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();
285 return nullptr;
288 //===----------------------------------------------------------------------===//
289 // Initializer implementations
290 //===----------------------------------------------------------------------===//
292 void Init::anchor() {}
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295 LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
296 #endif
298 UnsetInit *UnsetInit::get() {
299 static UnsetInit TheInit;
300 return &TheInit;
303 Init *UnsetInit::getCastTo(RecTy *Ty) const {
304 return const_cast<UnsetInit *>(this);
307 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
308 return const_cast<UnsetInit *>(this);
311 BitInit *BitInit::get(bool V) {
312 static BitInit True(true);
313 static BitInit False(false);
315 return V ? &True : &False;
318 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
319 if (isa<BitRecTy>(Ty))
320 return const_cast<BitInit *>(this);
322 if (isa<IntRecTy>(Ty))
323 return IntInit::get(getValue());
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));
331 return nullptr;
334 static void
335 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
336 ID.AddInteger(Range.size());
338 for (Init *I : Range)
339 ID.AddPointer(I);
342 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
343 static FoldingSet<BitsInit> ThePool;
345 FoldingSetNodeID ID;
346 ProfileBitsInit(ID, Range);
348 void *IP = nullptr;
349 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
350 return I;
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;
361 void BitsInit::Profile(FoldingSetNodeID &ID) const {
362 ProfileBitsInit(ID, makeArrayRef(getTrailingObjects<Init *>(), NumBits));
365 Init *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);
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);
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);
388 return nullptr;
391 Init *
392 BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
393 SmallVector<Init *, 16> NewBits(Bits.size());
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]);
400 return BitsInit::get(NewBits);
403 bool BitsInit::isConcrete() const {
404 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
405 if (!getBit(i)->isConcrete())
406 return false;
408 return true;
411 std::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 += "*";
420 return Result + " }";
423 // resolveReferences - If there are any field references that refer to fields
424 // that have been filled in, we can propagate the values now.
425 Init *BitsInit::resolveReferences(Resolver &R) const {
426 bool Changed = false;
427 SmallVector<Init *, 16> NewBits(getNumBits());
429 Init *CachedBitVarRef = nullptr;
430 Init *CachedBitVarResolved = nullptr;
432 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
433 Init *CurBit = getBit(i);
434 Init *NewBit = CurBit;
436 if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
437 if (CurBitVar->getBitVar() != CachedBitVarRef) {
438 CachedBitVarRef = CurBitVar->getBitVar();
439 CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
441 assert(CachedBitVarResolved && "Unresolved bitvar reference");
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);
448 if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
449 NewBit = CurBit;
450 NewBits[i] = NewBit;
451 Changed |= CurBit != NewBit;
454 if (Changed)
455 return BitsInit::get(NewBits);
457 return const_cast<BitsInit *>(this);
460 IntInit *IntInit::get(int64_t V) {
461 static std::map<int64_t, IntInit*> ThePool;
463 IntInit *&I = ThePool[V];
464 if (!I) I = new(Allocator) IntInit(V);
465 return I;
468 std::string IntInit::getAsString() const {
469 return itostr(Value);
472 static 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);
478 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
479 if (isa<IntRecTy>(Ty))
480 return const_cast<IntInit *>(this);
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);
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;
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));
498 return BitsInit::get(NewBits);
501 return nullptr;
504 Init *
505 IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
506 SmallVector<Init *, 16> NewBits(Bits.size());
508 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
509 if (Bits[i] >= 64)
510 return nullptr;
512 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
514 return BitsInit::get(NewBits);
517 CodeInit *CodeInit::get(StringRef V, const SMLoc &Loc) {
518 static StringSet<BumpPtrAllocator &> ThePool(Allocator);
520 CodeInitsConstructed++;
522 // Unlike StringMap, StringSet doesn't accept empty keys.
523 if (V.empty())
524 return new (Allocator) CodeInit("", Loc);
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);
533 StringInit *StringInit::get(StringRef V) {
534 static StringMap<StringInit*, BumpPtrAllocator &> ThePool(Allocator);
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;
542 Init *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());
548 return nullptr;
551 Init *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());
557 return nullptr;
560 static void ProfileListInit(FoldingSetNodeID &ID,
561 ArrayRef<Init *> Range,
562 RecTy *EltTy) {
563 ID.AddInteger(Range.size());
564 ID.AddPointer(EltTy);
566 for (Init *I : Range)
567 ID.AddPointer(I);
570 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
571 static FoldingSet<ListInit> ThePool;
573 FoldingSetNodeID ID;
574 ProfileListInit(ID, Range, EltTy);
576 void *IP = nullptr;
577 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
578 return I;
580 assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
581 cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
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;
592 void ListInit::Profile(FoldingSetNodeID &ID) const {
593 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
595 ProfileListInit(ID, getValues(), EltTy);
598 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
599 if (getType() == Ty)
600 return const_cast<ListInit*>(this);
602 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
603 SmallVector<Init*, 8> Elements;
604 Elements.reserve(getValues().size());
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;
618 if (!Changed)
619 return const_cast<ListInit*>(this);
620 return ListInit::get(Elements, ElementType);
623 return nullptr;
626 Init *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));
634 return ListInit::get(Vals, getElementType());
637 Record *ListInit::getElementAsRecord(unsigned i) const {
638 assert(i < NumValues && "List element index out of range!");
639 DefInit *DI = dyn_cast<DefInit>(getElement(i));
640 if (!DI)
641 PrintFatalError("Expected record in list!");
642 return DI->getDef();
645 Init *ListInit::resolveReferences(Resolver &R) const {
646 SmallVector<Init*, 8> Resolved;
647 Resolved.reserve(size());
648 bool Changed = false;
650 for (Init *CurElt : getValues()) {
651 Init *E = CurElt->resolveReferences(R);
652 Changed |= E != CurElt;
653 Resolved.push_back(E);
656 if (Changed)
657 return ListInit::get(Resolved, getElementType());
658 return const_cast<ListInit *>(this);
661 bool ListInit::isConcrete() const {
662 for (Init *Element : *this) {
663 if (!Element->isConcrete())
664 return false;
666 return true;
669 std::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();
677 return Result + "]";
680 Init *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);
686 static void
687 ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
688 ID.AddInteger(Opcode);
689 ID.AddPointer(Op);
690 ID.AddPointer(Type);
693 UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
694 static FoldingSet<UnOpInit> ThePool;
696 FoldingSetNodeID ID;
697 ProfileUnOpInit(ID, Opc, LHS, Type);
699 void *IP = nullptr;
700 if (UnOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
701 return I;
703 UnOpInit *I = new(Allocator) UnOpInit(Opc, LHS, Type);
704 ThePool.InsertNode(I, IP);
705 return I;
708 void UnOpInit::Profile(FoldingSetNodeID &ID) const {
709 ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
712 Init *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;
719 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
720 return StringInit::get(LHSd->getAsString());
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");
729 Record *D;
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;
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");
756 return DI;
760 if (Init *NewInit = LHS->convertInitializerTo(getType()))
761 return NewInit;
762 break;
764 case HEAD:
765 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
766 assert(!LHSl->empty() && "Empty list in head");
767 return LHSl->getElement(0);
769 break;
771 case TAIL:
772 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
773 assert(!LHSl->empty() && "Empty list in tail");
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());
778 break;
780 case SIZE:
781 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
782 return IntInit::get(LHSl->size());
783 break;
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;
792 return const_cast<UnOpInit *>(this);
795 Init *UnOpInit::resolveReferences(Resolver &R) const {
796 Init *lhs = LHS->resolveReferences(R);
798 if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
799 return (UnOpInit::get(getOpcode(), lhs, getType()))
800 ->Fold(R.getCurrentRecord(), R.isFinal());
801 return const_cast<UnOpInit *>(this);
804 std::string UnOpInit::getAsString() const {
805 std::string Result;
806 switch (getOpcode()) {
807 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
808 case HEAD: Result = "!head"; break;
809 case TAIL: Result = "!tail"; break;
810 case SIZE: Result = "!size"; break;
811 case EMPTY: Result = "!empty"; break;
813 return Result + "(" + LHS->getAsString() + ")";
816 static void
817 ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
818 RecTy *Type) {
819 ID.AddInteger(Opcode);
820 ID.AddPointer(LHS);
821 ID.AddPointer(RHS);
822 ID.AddPointer(Type);
825 BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS,
826 Init *RHS, RecTy *Type) {
827 static FoldingSet<BinOpInit> ThePool;
829 FoldingSetNodeID ID;
830 ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
832 void *IP = nullptr;
833 if (BinOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
834 return I;
836 BinOpInit *I = new(Allocator) BinOpInit(Opc, LHS, RHS, Type);
837 ThePool.InsertNode(I, IP);
838 return I;
841 void BinOpInit::Profile(FoldingSetNodeID &ID) const {
842 ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
845 static StringInit *ConcatStringInits(const StringInit *I0,
846 const StringInit *I1) {
847 SmallString<80> Concat(I0->getValue());
848 Concat.append(I1->getValue());
849 return StringInit::get(Concat);
852 Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
853 // Shortcut for the common case of concatenating two strings.
854 if (const StringInit *I0s = dyn_cast<StringInit>(I0))
855 if (const StringInit *I1s = dyn_cast<StringInit>(I1))
856 return ConcatStringInits(I0s, I1s);
857 return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1, StringRecTy::get());
860 static ListInit *ConcatListInits(const ListInit *LHS,
861 const ListInit *RHS) {
862 SmallVector<Init *, 8> Args;
863 Args.insert(Args.end(), LHS->begin(), LHS->end());
864 Args.insert(Args.end(), RHS->begin(), RHS->end());
865 return ListInit::get(Args, LHS->getElementType());
868 Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
869 assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
871 // Shortcut for the common case of concatenating two lists.
872 if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
873 if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
874 return ConcatListInits(LHSList, RHSList);
875 return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
878 Init *BinOpInit::getListSplat(TypedInit *LHS, Init *RHS) {
879 return BinOpInit::get(BinOpInit::LISTSPLAT, LHS, RHS, LHS->getType());
882 Init *BinOpInit::Fold(Record *CurRec) const {
883 switch (getOpcode()) {
884 case CONCAT: {
885 DagInit *LHSs = dyn_cast<DagInit>(LHS);
886 DagInit *RHSs = dyn_cast<DagInit>(RHS);
887 if (LHSs && RHSs) {
888 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
889 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
890 if (!LOp || !ROp)
891 break;
892 if (LOp->getDef() != ROp->getDef()) {
893 PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
894 LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
895 "'");
897 SmallVector<Init*, 8> Args;
898 SmallVector<StringInit*, 8> ArgNames;
899 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
900 Args.push_back(LHSs->getArg(i));
901 ArgNames.push_back(LHSs->getArgName(i));
903 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
904 Args.push_back(RHSs->getArg(i));
905 ArgNames.push_back(RHSs->getArgName(i));
907 return DagInit::get(LHSs->getOperator(), nullptr, Args, ArgNames);
909 break;
911 case LISTCONCAT: {
912 ListInit *LHSs = dyn_cast<ListInit>(LHS);
913 ListInit *RHSs = dyn_cast<ListInit>(RHS);
914 if (LHSs && RHSs) {
915 SmallVector<Init *, 8> Args;
916 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
917 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
918 return ListInit::get(Args, LHSs->getElementType());
920 break;
922 case LISTSPLAT: {
923 TypedInit *Value = dyn_cast<TypedInit>(LHS);
924 IntInit *Size = dyn_cast<IntInit>(RHS);
925 if (Value && Size) {
926 SmallVector<Init *, 8> Args(Size->getValue(), Value);
927 return ListInit::get(Args, Value->getType());
929 break;
931 case STRCONCAT: {
932 StringInit *LHSs = dyn_cast<StringInit>(LHS);
933 StringInit *RHSs = dyn_cast<StringInit>(RHS);
934 if (LHSs && RHSs)
935 return ConcatStringInits(LHSs, RHSs);
936 break;
938 case EQ:
939 case NE:
940 case LE:
941 case LT:
942 case GE:
943 case GT: {
944 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
945 // to string objects.
946 IntInit *L =
947 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
948 IntInit *R =
949 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
951 if (L && R) {
952 bool Result;
953 switch (getOpcode()) {
954 case EQ: Result = L->getValue() == R->getValue(); break;
955 case NE: Result = L->getValue() != R->getValue(); break;
956 case LE: Result = L->getValue() <= R->getValue(); break;
957 case LT: Result = L->getValue() < R->getValue(); break;
958 case GE: Result = L->getValue() >= R->getValue(); break;
959 case GT: Result = L->getValue() > R->getValue(); break;
960 default: llvm_unreachable("unhandled comparison");
962 return BitInit::get(Result);
965 if (getOpcode() == EQ || getOpcode() == NE) {
966 StringInit *LHSs = dyn_cast<StringInit>(LHS);
967 StringInit *RHSs = dyn_cast<StringInit>(RHS);
969 // Make sure we've resolved
970 if (LHSs && RHSs) {
971 bool Equal = LHSs->getValue() == RHSs->getValue();
972 return BitInit::get(getOpcode() == EQ ? Equal : !Equal);
976 break;
978 case ADD:
979 case MUL:
980 case AND:
981 case OR:
982 case SHL:
983 case SRA:
984 case SRL: {
985 IntInit *LHSi =
986 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
987 IntInit *RHSi =
988 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
989 if (LHSi && RHSi) {
990 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
991 int64_t Result;
992 switch (getOpcode()) {
993 default: llvm_unreachable("Bad opcode!");
994 case ADD: Result = LHSv + RHSv; break;
995 case MUL: Result = LHSv * RHSv; break;
996 case AND: Result = LHSv & RHSv; break;
997 case OR: Result = LHSv | RHSv; break;
998 case SHL: Result = LHSv << RHSv; break;
999 case SRA: Result = LHSv >> RHSv; break;
1000 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1002 return IntInit::get(Result);
1004 break;
1007 return const_cast<BinOpInit *>(this);
1010 Init *BinOpInit::resolveReferences(Resolver &R) const {
1011 Init *lhs = LHS->resolveReferences(R);
1012 Init *rhs = RHS->resolveReferences(R);
1014 if (LHS != lhs || RHS != rhs)
1015 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
1016 ->Fold(R.getCurrentRecord());
1017 return const_cast<BinOpInit *>(this);
1020 std::string BinOpInit::getAsString() const {
1021 std::string Result;
1022 switch (getOpcode()) {
1023 case CONCAT: Result = "!con"; break;
1024 case ADD: Result = "!add"; break;
1025 case MUL: Result = "!mul"; break;
1026 case AND: Result = "!and"; break;
1027 case OR: Result = "!or"; break;
1028 case SHL: Result = "!shl"; break;
1029 case SRA: Result = "!sra"; break;
1030 case SRL: Result = "!srl"; break;
1031 case EQ: Result = "!eq"; break;
1032 case NE: Result = "!ne"; break;
1033 case LE: Result = "!le"; break;
1034 case LT: Result = "!lt"; break;
1035 case GE: Result = "!ge"; break;
1036 case GT: Result = "!gt"; break;
1037 case LISTCONCAT: Result = "!listconcat"; break;
1038 case LISTSPLAT: Result = "!listsplat"; break;
1039 case STRCONCAT: Result = "!strconcat"; break;
1041 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
1044 static void
1045 ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
1046 Init *RHS, RecTy *Type) {
1047 ID.AddInteger(Opcode);
1048 ID.AddPointer(LHS);
1049 ID.AddPointer(MHS);
1050 ID.AddPointer(RHS);
1051 ID.AddPointer(Type);
1054 TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
1055 RecTy *Type) {
1056 static FoldingSet<TernOpInit> ThePool;
1058 FoldingSetNodeID ID;
1059 ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
1061 void *IP = nullptr;
1062 if (TernOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1063 return I;
1065 TernOpInit *I = new(Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
1066 ThePool.InsertNode(I, IP);
1067 return I;
1070 void TernOpInit::Profile(FoldingSetNodeID &ID) const {
1071 ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
1074 static Init *ForeachApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
1075 MapResolver R(CurRec);
1076 R.set(LHS, MHSe);
1077 return RHS->resolveReferences(R);
1080 static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
1081 Record *CurRec) {
1082 bool Change = false;
1083 Init *Val = ForeachApply(LHS, MHSd->getOperator(), RHS, CurRec);
1084 if (Val != MHSd->getOperator())
1085 Change = true;
1087 SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
1088 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1089 Init *Arg = MHSd->getArg(i);
1090 Init *NewArg;
1091 StringInit *ArgName = MHSd->getArgName(i);
1093 if (DagInit *Argd = dyn_cast<DagInit>(Arg))
1094 NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
1095 else
1096 NewArg = ForeachApply(LHS, Arg, RHS, CurRec);
1098 NewArgs.push_back(std::make_pair(NewArg, ArgName));
1099 if (Arg != NewArg)
1100 Change = true;
1103 if (Change)
1104 return DagInit::get(Val, nullptr, NewArgs);
1105 return MHSd;
1108 // Applies RHS to all elements of MHS, using LHS as a temp variable.
1109 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1110 Record *CurRec) {
1111 if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
1112 return ForeachDagApply(LHS, MHSd, RHS, CurRec);
1114 if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
1115 SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
1117 for (Init *&Item : NewList) {
1118 Init *NewItem = ForeachApply(LHS, Item, RHS, CurRec);
1119 if (NewItem != Item)
1120 Item = NewItem;
1122 return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
1125 return nullptr;
1128 Init *TernOpInit::Fold(Record *CurRec) const {
1129 switch (getOpcode()) {
1130 case SUBST: {
1131 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1132 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1133 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1135 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1136 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1137 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1139 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1140 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1141 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1143 if (LHSd && MHSd && RHSd) {
1144 Record *Val = RHSd->getDef();
1145 if (LHSd->getAsString() == RHSd->getAsString())
1146 Val = MHSd->getDef();
1147 return DefInit::get(Val);
1149 if (LHSv && MHSv && RHSv) {
1150 std::string Val = RHSv->getName();
1151 if (LHSv->getAsString() == RHSv->getAsString())
1152 Val = MHSv->getName();
1153 return VarInit::get(Val, getType());
1155 if (LHSs && MHSs && RHSs) {
1156 std::string Val = RHSs->getValue();
1158 std::string::size_type found;
1159 std::string::size_type idx = 0;
1160 while (true) {
1161 found = Val.find(LHSs->getValue(), idx);
1162 if (found == std::string::npos)
1163 break;
1164 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1165 idx = found + MHSs->getValue().size();
1168 return StringInit::get(Val);
1170 break;
1173 case FOREACH: {
1174 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
1175 return Result;
1176 break;
1179 case IF: {
1180 if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
1181 LHS->convertInitializerTo(IntRecTy::get()))) {
1182 if (LHSi->getValue())
1183 return MHS;
1184 return RHS;
1186 break;
1189 case DAG: {
1190 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1191 ListInit *RHSl = dyn_cast<ListInit>(RHS);
1192 bool MHSok = MHSl || isa<UnsetInit>(MHS);
1193 bool RHSok = RHSl || isa<UnsetInit>(RHS);
1195 if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
1196 break; // Typically prevented by the parser, but might happen with template args
1198 if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
1199 SmallVector<std::pair<Init *, StringInit *>, 8> Children;
1200 unsigned Size = MHSl ? MHSl->size() : RHSl->size();
1201 for (unsigned i = 0; i != Size; ++i) {
1202 Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get();
1203 Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get();
1204 if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
1205 return const_cast<TernOpInit *>(this);
1206 Children.emplace_back(Node, dyn_cast<StringInit>(Name));
1208 return DagInit::get(LHS, nullptr, Children);
1210 break;
1214 return const_cast<TernOpInit *>(this);
1217 Init *TernOpInit::resolveReferences(Resolver &R) const {
1218 Init *lhs = LHS->resolveReferences(R);
1220 if (getOpcode() == IF && lhs != LHS) {
1221 if (IntInit *Value = dyn_cast_or_null<IntInit>(
1222 lhs->convertInitializerTo(IntRecTy::get()))) {
1223 // Short-circuit
1224 if (Value->getValue())
1225 return MHS->resolveReferences(R);
1226 return RHS->resolveReferences(R);
1230 Init *mhs = MHS->resolveReferences(R);
1231 Init *rhs;
1233 if (getOpcode() == FOREACH) {
1234 ShadowResolver SR(R);
1235 SR.addShadow(lhs);
1236 rhs = RHS->resolveReferences(SR);
1237 } else {
1238 rhs = RHS->resolveReferences(R);
1241 if (LHS != lhs || MHS != mhs || RHS != rhs)
1242 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
1243 ->Fold(R.getCurrentRecord());
1244 return const_cast<TernOpInit *>(this);
1247 std::string TernOpInit::getAsString() const {
1248 std::string Result;
1249 bool UnquotedLHS = false;
1250 switch (getOpcode()) {
1251 case SUBST: Result = "!subst"; break;
1252 case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
1253 case IF: Result = "!if"; break;
1254 case DAG: Result = "!dag"; break;
1256 return (Result + "(" +
1257 (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
1258 ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
1261 static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *A, Init *B,
1262 Init *Start, Init *List, Init *Expr,
1263 RecTy *Type) {
1264 ID.AddPointer(Start);
1265 ID.AddPointer(List);
1266 ID.AddPointer(A);
1267 ID.AddPointer(B);
1268 ID.AddPointer(Expr);
1269 ID.AddPointer(Type);
1272 FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
1273 Init *Expr, RecTy *Type) {
1274 static FoldingSet<FoldOpInit> ThePool;
1276 FoldingSetNodeID ID;
1277 ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
1279 void *IP = nullptr;
1280 if (FoldOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1281 return I;
1283 FoldOpInit *I = new (Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
1284 ThePool.InsertNode(I, IP);
1285 return I;
1288 void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
1289 ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
1292 Init *FoldOpInit::Fold(Record *CurRec) const {
1293 if (ListInit *LI = dyn_cast<ListInit>(List)) {
1294 Init *Accum = Start;
1295 for (Init *Elt : *LI) {
1296 MapResolver R(CurRec);
1297 R.set(A, Accum);
1298 R.set(B, Elt);
1299 Accum = Expr->resolveReferences(R);
1301 return Accum;
1303 return const_cast<FoldOpInit *>(this);
1306 Init *FoldOpInit::resolveReferences(Resolver &R) const {
1307 Init *NewStart = Start->resolveReferences(R);
1308 Init *NewList = List->resolveReferences(R);
1309 ShadowResolver SR(R);
1310 SR.addShadow(A);
1311 SR.addShadow(B);
1312 Init *NewExpr = Expr->resolveReferences(SR);
1314 if (Start == NewStart && List == NewList && Expr == NewExpr)
1315 return const_cast<FoldOpInit *>(this);
1317 return get(NewStart, NewList, A, B, NewExpr, getType())
1318 ->Fold(R.getCurrentRecord());
1321 Init *FoldOpInit::getBit(unsigned Bit) const {
1322 return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
1325 std::string FoldOpInit::getAsString() const {
1326 return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
1327 ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
1328 ", " + Expr->getAsString() + ")")
1329 .str();
1332 static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
1333 Init *Expr) {
1334 ID.AddPointer(CheckType);
1335 ID.AddPointer(Expr);
1338 IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
1339 static FoldingSet<IsAOpInit> ThePool;
1341 FoldingSetNodeID ID;
1342 ProfileIsAOpInit(ID, CheckType, Expr);
1344 void *IP = nullptr;
1345 if (IsAOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1346 return I;
1348 IsAOpInit *I = new (Allocator) IsAOpInit(CheckType, Expr);
1349 ThePool.InsertNode(I, IP);
1350 return I;
1353 void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
1354 ProfileIsAOpInit(ID, CheckType, Expr);
1357 Init *IsAOpInit::Fold() const {
1358 if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
1359 // Is the expression type known to be (a subclass of) the desired type?
1360 if (TI->getType()->typeIsConvertibleTo(CheckType))
1361 return IntInit::get(1);
1363 if (isa<RecordRecTy>(CheckType)) {
1364 // If the target type is not a subclass of the expression type, or if
1365 // the expression has fully resolved to a record, we know that it can't
1366 // be of the required type.
1367 if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
1368 return IntInit::get(0);
1369 } else {
1370 // We treat non-record types as not castable.
1371 return IntInit::get(0);
1374 return const_cast<IsAOpInit *>(this);
1377 Init *IsAOpInit::resolveReferences(Resolver &R) const {
1378 Init *NewExpr = Expr->resolveReferences(R);
1379 if (Expr != NewExpr)
1380 return get(CheckType, NewExpr)->Fold();
1381 return const_cast<IsAOpInit *>(this);
1384 Init *IsAOpInit::getBit(unsigned Bit) const {
1385 return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
1388 std::string IsAOpInit::getAsString() const {
1389 return (Twine("!isa<") + CheckType->getAsString() + ">(" +
1390 Expr->getAsString() + ")")
1391 .str();
1394 RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
1395 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
1396 for (Record *Rec : RecordType->getClasses()) {
1397 if (RecordVal *Field = Rec->getValue(FieldName))
1398 return Field->getType();
1401 return nullptr;
1404 Init *
1405 TypedInit::convertInitializerTo(RecTy *Ty) const {
1406 if (getType() == Ty || getType()->typeIsA(Ty))
1407 return const_cast<TypedInit *>(this);
1409 if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
1410 cast<BitsRecTy>(Ty)->getNumBits() == 1)
1411 return BitsInit::get({const_cast<TypedInit *>(this)});
1413 return nullptr;
1416 Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
1417 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1418 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1419 unsigned NumBits = T->getNumBits();
1421 SmallVector<Init *, 16> NewBits;
1422 NewBits.reserve(Bits.size());
1423 for (unsigned Bit : Bits) {
1424 if (Bit >= NumBits)
1425 return nullptr;
1427 NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
1429 return BitsInit::get(NewBits);
1432 Init *TypedInit::getCastTo(RecTy *Ty) const {
1433 // Handle the common case quickly
1434 if (getType() == Ty || getType()->typeIsA(Ty))
1435 return const_cast<TypedInit *>(this);
1437 if (Init *Converted = convertInitializerTo(Ty)) {
1438 assert(!isa<TypedInit>(Converted) ||
1439 cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
1440 return Converted;
1443 if (!getType()->typeIsConvertibleTo(Ty))
1444 return nullptr;
1446 return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
1447 ->Fold(nullptr);
1450 Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
1451 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1452 if (!T) return nullptr; // Cannot subscript a non-list variable.
1454 if (Elements.size() == 1)
1455 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1457 SmallVector<Init*, 8> ListInits;
1458 ListInits.reserve(Elements.size());
1459 for (unsigned Element : Elements)
1460 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1461 Element));
1462 return ListInit::get(ListInits, T->getElementType());
1466 VarInit *VarInit::get(StringRef VN, RecTy *T) {
1467 Init *Value = StringInit::get(VN);
1468 return VarInit::get(Value, T);
1471 VarInit *VarInit::get(Init *VN, RecTy *T) {
1472 using Key = std::pair<RecTy *, Init *>;
1473 static DenseMap<Key, VarInit*> ThePool;
1475 Key TheKey(std::make_pair(T, VN));
1477 VarInit *&I = ThePool[TheKey];
1478 if (!I)
1479 I = new(Allocator) VarInit(VN, T);
1480 return I;
1483 StringRef VarInit::getName() const {
1484 StringInit *NameString = cast<StringInit>(getNameInit());
1485 return NameString->getValue();
1488 Init *VarInit::getBit(unsigned Bit) const {
1489 if (getType() == BitRecTy::get())
1490 return const_cast<VarInit*>(this);
1491 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1494 Init *VarInit::resolveReferences(Resolver &R) const {
1495 if (Init *Val = R.resolve(VarName))
1496 return Val;
1497 return const_cast<VarInit *>(this);
1500 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1501 using Key = std::pair<TypedInit *, unsigned>;
1502 static DenseMap<Key, VarBitInit*> ThePool;
1504 Key TheKey(std::make_pair(T, B));
1506 VarBitInit *&I = ThePool[TheKey];
1507 if (!I)
1508 I = new(Allocator) VarBitInit(T, B);
1509 return I;
1512 std::string VarBitInit::getAsString() const {
1513 return TI->getAsString() + "{" + utostr(Bit) + "}";
1516 Init *VarBitInit::resolveReferences(Resolver &R) const {
1517 Init *I = TI->resolveReferences(R);
1518 if (TI != I)
1519 return I->getBit(getBitNum());
1521 return const_cast<VarBitInit*>(this);
1524 VarListElementInit *VarListElementInit::get(TypedInit *T,
1525 unsigned E) {
1526 using Key = std::pair<TypedInit *, unsigned>;
1527 static DenseMap<Key, VarListElementInit*> ThePool;
1529 Key TheKey(std::make_pair(T, E));
1531 VarListElementInit *&I = ThePool[TheKey];
1532 if (!I) I = new(Allocator) VarListElementInit(T, E);
1533 return I;
1536 std::string VarListElementInit::getAsString() const {
1537 return TI->getAsString() + "[" + utostr(Element) + "]";
1540 Init *VarListElementInit::resolveReferences(Resolver &R) const {
1541 Init *NewTI = TI->resolveReferences(R);
1542 if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
1543 // Leave out-of-bounds array references as-is. This can happen without
1544 // being an error, e.g. in the untaken "branch" of an !if expression.
1545 if (getElementNum() < List->size())
1546 return List->getElement(getElementNum());
1548 if (NewTI != TI && isa<TypedInit>(NewTI))
1549 return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
1550 return const_cast<VarListElementInit *>(this);
1553 Init *VarListElementInit::getBit(unsigned Bit) const {
1554 if (getType() == BitRecTy::get())
1555 return const_cast<VarListElementInit*>(this);
1556 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1559 DefInit::DefInit(Record *D)
1560 : TypedInit(IK_DefInit, D->getType()), Def(D) {}
1562 DefInit *DefInit::get(Record *R) {
1563 return R->getDefInit();
1566 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1567 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1568 if (getType()->typeIsConvertibleTo(RRT))
1569 return const_cast<DefInit *>(this);
1570 return nullptr;
1573 RecTy *DefInit::getFieldType(StringInit *FieldName) const {
1574 if (const RecordVal *RV = Def->getValue(FieldName))
1575 return RV->getType();
1576 return nullptr;
1579 std::string DefInit::getAsString() const {
1580 return Def->getName();
1583 static void ProfileVarDefInit(FoldingSetNodeID &ID,
1584 Record *Class,
1585 ArrayRef<Init *> Args) {
1586 ID.AddInteger(Args.size());
1587 ID.AddPointer(Class);
1589 for (Init *I : Args)
1590 ID.AddPointer(I);
1593 VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
1594 static FoldingSet<VarDefInit> ThePool;
1596 FoldingSetNodeID ID;
1597 ProfileVarDefInit(ID, Class, Args);
1599 void *IP = nullptr;
1600 if (VarDefInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1601 return I;
1603 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
1604 alignof(VarDefInit));
1605 VarDefInit *I = new(Mem) VarDefInit(Class, Args.size());
1606 std::uninitialized_copy(Args.begin(), Args.end(),
1607 I->getTrailingObjects<Init *>());
1608 ThePool.InsertNode(I, IP);
1609 return I;
1612 void VarDefInit::Profile(FoldingSetNodeID &ID) const {
1613 ProfileVarDefInit(ID, Class, args());
1616 DefInit *VarDefInit::instantiate() {
1617 if (!Def) {
1618 RecordKeeper &Records = Class->getRecords();
1619 auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
1620 Class->getLoc(), Records,
1621 /*IsAnonymous=*/true);
1622 Record *NewRec = NewRecOwner.get();
1624 // Copy values from class to instance
1625 for (const RecordVal &Val : Class->getValues())
1626 NewRec->addValue(Val);
1628 // Substitute and resolve template arguments
1629 ArrayRef<Init *> TArgs = Class->getTemplateArgs();
1630 MapResolver R(NewRec);
1632 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1633 if (i < args_size())
1634 R.set(TArgs[i], getArg(i));
1635 else
1636 R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
1638 NewRec->removeValue(TArgs[i]);
1641 NewRec->resolveReferences(R);
1643 // Add superclasses.
1644 ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
1645 for (const auto &SCPair : SCs)
1646 NewRec->addSuperClass(SCPair.first, SCPair.second);
1648 NewRec->addSuperClass(Class,
1649 SMRange(Class->getLoc().back(),
1650 Class->getLoc().back()));
1652 // Resolve internal references and store in record keeper
1653 NewRec->resolveReferences();
1654 Records.addDef(std::move(NewRecOwner));
1656 Def = DefInit::get(NewRec);
1659 return Def;
1662 Init *VarDefInit::resolveReferences(Resolver &R) const {
1663 TrackUnresolvedResolver UR(&R);
1664 bool Changed = false;
1665 SmallVector<Init *, 8> NewArgs;
1666 NewArgs.reserve(args_size());
1668 for (Init *Arg : args()) {
1669 Init *NewArg = Arg->resolveReferences(UR);
1670 NewArgs.push_back(NewArg);
1671 Changed |= NewArg != Arg;
1674 if (Changed) {
1675 auto New = VarDefInit::get(Class, NewArgs);
1676 if (!UR.foundUnresolved())
1677 return New->instantiate();
1678 return New;
1680 return const_cast<VarDefInit *>(this);
1683 Init *VarDefInit::Fold() const {
1684 if (Def)
1685 return Def;
1687 TrackUnresolvedResolver R;
1688 for (Init *Arg : args())
1689 Arg->resolveReferences(R);
1691 if (!R.foundUnresolved())
1692 return const_cast<VarDefInit *>(this)->instantiate();
1693 return const_cast<VarDefInit *>(this);
1696 std::string VarDefInit::getAsString() const {
1697 std::string Result = Class->getNameInitAsString() + "<";
1698 const char *sep = "";
1699 for (Init *Arg : args()) {
1700 Result += sep;
1701 sep = ", ";
1702 Result += Arg->getAsString();
1704 return Result + ">";
1707 FieldInit *FieldInit::get(Init *R, StringInit *FN) {
1708 using Key = std::pair<Init *, StringInit *>;
1709 static DenseMap<Key, FieldInit*> ThePool;
1711 Key TheKey(std::make_pair(R, FN));
1713 FieldInit *&I = ThePool[TheKey];
1714 if (!I) I = new(Allocator) FieldInit(R, FN);
1715 return I;
1718 Init *FieldInit::getBit(unsigned Bit) const {
1719 if (getType() == BitRecTy::get())
1720 return const_cast<FieldInit*>(this);
1721 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1724 Init *FieldInit::resolveReferences(Resolver &R) const {
1725 Init *NewRec = Rec->resolveReferences(R);
1726 if (NewRec != Rec)
1727 return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
1728 return const_cast<FieldInit *>(this);
1731 Init *FieldInit::Fold(Record *CurRec) const {
1732 if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
1733 Record *Def = DI->getDef();
1734 if (Def == CurRec)
1735 PrintFatalError(CurRec->getLoc(),
1736 Twine("Attempting to access field '") +
1737 FieldName->getAsUnquotedString() + "' of '" +
1738 Rec->getAsString() + "' is a forbidden self-reference");
1739 Init *FieldVal = Def->getValue(FieldName)->getValue();
1740 if (FieldVal->isComplete())
1741 return FieldVal;
1743 return const_cast<FieldInit *>(this);
1746 static void ProfileCondOpInit(FoldingSetNodeID &ID,
1747 ArrayRef<Init *> CondRange,
1748 ArrayRef<Init *> ValRange,
1749 const RecTy *ValType) {
1750 assert(CondRange.size() == ValRange.size() &&
1751 "Number of conditions and values must match!");
1752 ID.AddPointer(ValType);
1753 ArrayRef<Init *>::iterator Case = CondRange.begin();
1754 ArrayRef<Init *>::iterator Val = ValRange.begin();
1756 while (Case != CondRange.end()) {
1757 ID.AddPointer(*Case++);
1758 ID.AddPointer(*Val++);
1762 void CondOpInit::Profile(FoldingSetNodeID &ID) const {
1763 ProfileCondOpInit(ID,
1764 makeArrayRef(getTrailingObjects<Init *>(), NumConds),
1765 makeArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
1766 ValType);
1769 CondOpInit *
1770 CondOpInit::get(ArrayRef<Init *> CondRange,
1771 ArrayRef<Init *> ValRange, RecTy *Ty) {
1772 assert(CondRange.size() == ValRange.size() &&
1773 "Number of conditions and values must match!");
1775 static FoldingSet<CondOpInit> ThePool;
1776 FoldingSetNodeID ID;
1777 ProfileCondOpInit(ID, CondRange, ValRange, Ty);
1779 void *IP = nullptr;
1780 if (CondOpInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1781 return I;
1783 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *>(2*CondRange.size()),
1784 alignof(BitsInit));
1785 CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
1787 std::uninitialized_copy(CondRange.begin(), CondRange.end(),
1788 I->getTrailingObjects<Init *>());
1789 std::uninitialized_copy(ValRange.begin(), ValRange.end(),
1790 I->getTrailingObjects<Init *>()+CondRange.size());
1791 ThePool.InsertNode(I, IP);
1792 return I;
1795 Init *CondOpInit::resolveReferences(Resolver &R) const {
1796 SmallVector<Init*, 4> NewConds;
1797 bool Changed = false;
1798 for (const Init *Case : getConds()) {
1799 Init *NewCase = Case->resolveReferences(R);
1800 NewConds.push_back(NewCase);
1801 Changed |= NewCase != Case;
1804 SmallVector<Init*, 4> NewVals;
1805 for (const Init *Val : getVals()) {
1806 Init *NewVal = Val->resolveReferences(R);
1807 NewVals.push_back(NewVal);
1808 Changed |= NewVal != Val;
1811 if (Changed)
1812 return (CondOpInit::get(NewConds, NewVals,
1813 getValType()))->Fold(R.getCurrentRecord());
1815 return const_cast<CondOpInit *>(this);
1818 Init *CondOpInit::Fold(Record *CurRec) const {
1819 for ( unsigned i = 0; i < NumConds; ++i) {
1820 Init *Cond = getCond(i);
1821 Init *Val = getVal(i);
1823 if (IntInit *CondI = dyn_cast_or_null<IntInit>(
1824 Cond->convertInitializerTo(IntRecTy::get()))) {
1825 if (CondI->getValue())
1826 return Val->convertInitializerTo(getValType());
1827 } else
1828 return const_cast<CondOpInit *>(this);
1831 PrintFatalError(CurRec->getLoc(),
1832 CurRec->getName() +
1833 " does not have any true condition in:" +
1834 this->getAsString());
1835 return nullptr;
1838 bool CondOpInit::isConcrete() const {
1839 for (const Init *Case : getConds())
1840 if (!Case->isConcrete())
1841 return false;
1843 for (const Init *Val : getVals())
1844 if (!Val->isConcrete())
1845 return false;
1847 return true;
1850 bool CondOpInit::isComplete() const {
1851 for (const Init *Case : getConds())
1852 if (!Case->isComplete())
1853 return false;
1855 for (const Init *Val : getVals())
1856 if (!Val->isConcrete())
1857 return false;
1859 return true;
1862 std::string CondOpInit::getAsString() const {
1863 std::string Result = "!cond(";
1864 for (unsigned i = 0; i < getNumConds(); i++) {
1865 Result += getCond(i)->getAsString() + ": ";
1866 Result += getVal(i)->getAsString();
1867 if (i != getNumConds()-1)
1868 Result += ", ";
1870 return Result + ")";
1873 Init *CondOpInit::getBit(unsigned Bit) const {
1874 return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
1877 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
1878 ArrayRef<Init *> ArgRange,
1879 ArrayRef<StringInit *> NameRange) {
1880 ID.AddPointer(V);
1881 ID.AddPointer(VN);
1883 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1884 ArrayRef<StringInit *>::iterator Name = NameRange.begin();
1885 while (Arg != ArgRange.end()) {
1886 assert(Name != NameRange.end() && "Arg name underflow!");
1887 ID.AddPointer(*Arg++);
1888 ID.AddPointer(*Name++);
1890 assert(Name == NameRange.end() && "Arg name overflow!");
1893 DagInit *
1894 DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
1895 ArrayRef<StringInit *> NameRange) {
1896 static FoldingSet<DagInit> ThePool;
1898 FoldingSetNodeID ID;
1899 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1901 void *IP = nullptr;
1902 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1903 return I;
1905 void *Mem = Allocator.Allocate(totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()), alignof(BitsInit));
1906 DagInit *I = new(Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
1907 std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
1908 I->getTrailingObjects<Init *>());
1909 std::uninitialized_copy(NameRange.begin(), NameRange.end(),
1910 I->getTrailingObjects<StringInit *>());
1911 ThePool.InsertNode(I, IP);
1912 return I;
1915 DagInit *
1916 DagInit::get(Init *V, StringInit *VN,
1917 ArrayRef<std::pair<Init*, StringInit*>> args) {
1918 SmallVector<Init *, 8> Args;
1919 SmallVector<StringInit *, 8> Names;
1921 for (const auto &Arg : args) {
1922 Args.push_back(Arg.first);
1923 Names.push_back(Arg.second);
1926 return DagInit::get(V, VN, Args, Names);
1929 void DagInit::Profile(FoldingSetNodeID &ID) const {
1930 ProfileDagInit(ID, Val, ValName, makeArrayRef(getTrailingObjects<Init *>(), NumArgs), makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
1933 Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
1934 if (DefInit *DefI = dyn_cast<DefInit>(Val))
1935 return DefI->getDef();
1936 PrintFatalError(Loc, "Expected record as operator");
1937 return nullptr;
1940 Init *DagInit::resolveReferences(Resolver &R) const {
1941 SmallVector<Init*, 8> NewArgs;
1942 NewArgs.reserve(arg_size());
1943 bool ArgsChanged = false;
1944 for (const Init *Arg : getArgs()) {
1945 Init *NewArg = Arg->resolveReferences(R);
1946 NewArgs.push_back(NewArg);
1947 ArgsChanged |= NewArg != Arg;
1950 Init *Op = Val->resolveReferences(R);
1951 if (Op != Val || ArgsChanged)
1952 return DagInit::get(Op, ValName, NewArgs, getArgNames());
1954 return const_cast<DagInit *>(this);
1957 bool DagInit::isConcrete() const {
1958 if (!Val->isConcrete())
1959 return false;
1960 for (const Init *Elt : getArgs()) {
1961 if (!Elt->isConcrete())
1962 return false;
1964 return true;
1967 std::string DagInit::getAsString() const {
1968 std::string Result = "(" + Val->getAsString();
1969 if (ValName)
1970 Result += ":" + ValName->getAsUnquotedString();
1971 if (!arg_empty()) {
1972 Result += " " + getArg(0)->getAsString();
1973 if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
1974 for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
1975 Result += ", " + getArg(i)->getAsString();
1976 if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
1979 return Result + ")";
1982 //===----------------------------------------------------------------------===//
1983 // Other implementations
1984 //===----------------------------------------------------------------------===//
1986 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
1987 : Name(N), TyAndPrefix(T, P) {
1988 setValue(UnsetInit::get());
1989 assert(Value && "Cannot create unset value for current type!");
1992 StringRef RecordVal::getName() const {
1993 return cast<StringInit>(getNameInit())->getValue();
1996 bool RecordVal::setValue(Init *V) {
1997 if (V) {
1998 Value = V->getCastTo(getType());
1999 if (Value) {
2000 assert(!isa<TypedInit>(Value) ||
2001 cast<TypedInit>(Value)->getType()->typeIsA(getType()));
2002 if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
2003 if (!isa<BitsInit>(Value)) {
2004 SmallVector<Init *, 64> Bits;
2005 Bits.reserve(BTy->getNumBits());
2006 for (unsigned i = 0, e = BTy->getNumBits(); i < e; ++i)
2007 Bits.push_back(Value->getBit(i));
2008 Value = BitsInit::get(Bits);
2012 return Value == nullptr;
2014 Value = nullptr;
2015 return false;
2018 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2019 LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
2020 #endif
2022 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
2023 if (getPrefix()) OS << "field ";
2024 OS << *getType() << " " << getNameInitAsString();
2026 if (getValue())
2027 OS << " = " << *getValue();
2029 if (PrintSem) OS << ";\n";
2032 unsigned Record::LastID = 0;
2034 void Record::checkName() {
2035 // Ensure the record name has string type.
2036 const TypedInit *TypedName = cast<const TypedInit>(Name);
2037 if (!isa<StringRecTy>(TypedName->getType()))
2038 PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
2039 "' is not a string!");
2042 RecordRecTy *Record::getType() {
2043 SmallVector<Record *, 4> DirectSCs;
2044 getDirectSuperClasses(DirectSCs);
2045 return RecordRecTy::get(DirectSCs);
2048 DefInit *Record::getDefInit() {
2049 if (!TheInit)
2050 TheInit = new(Allocator) DefInit(this);
2051 return TheInit;
2054 void Record::setName(Init *NewName) {
2055 Name = NewName;
2056 checkName();
2057 // DO NOT resolve record values to the name at this point because
2058 // there might be default values for arguments of this def. Those
2059 // arguments might not have been resolved yet so we don't want to
2060 // prematurely assume values for those arguments were not passed to
2061 // this def.
2063 // Nonetheless, it may be that some of this Record's values
2064 // reference the record name. Indeed, the reason for having the
2065 // record name be an Init is to provide this flexibility. The extra
2066 // resolve steps after completely instantiating defs takes care of
2067 // this. See TGParser::ParseDef and TGParser::ParseDefm.
2070 void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
2071 ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
2072 while (!SCs.empty()) {
2073 // Superclasses are in reverse preorder, so 'back' is a direct superclass,
2074 // and its transitive superclasses are directly preceding it.
2075 Record *SC = SCs.back().first;
2076 SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
2077 Classes.push_back(SC);
2081 void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
2082 for (RecordVal &Value : Values) {
2083 if (SkipVal == &Value) // Skip resolve the same field as the given one
2084 continue;
2085 if (Init *V = Value.getValue()) {
2086 Init *VR = V->resolveReferences(R);
2087 if (Value.setValue(VR)) {
2088 std::string Type;
2089 if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
2090 Type =
2091 (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
2092 PrintFatalError(getLoc(), Twine("Invalid value ") + Type +
2093 "is found when setting '" +
2094 Value.getNameInitAsString() +
2095 "' of type '" +
2096 Value.getType()->getAsString() +
2097 "' after resolving references: " +
2098 VR->getAsUnquotedString() + "\n");
2102 Init *OldName = getNameInit();
2103 Init *NewName = Name->resolveReferences(R);
2104 if (NewName != OldName) {
2105 // Re-register with RecordKeeper.
2106 setName(NewName);
2110 void Record::resolveReferences() {
2111 RecordResolver R(*this);
2112 R.setFinal(true);
2113 resolveReferences(R);
2116 void Record::resolveReferencesTo(const RecordVal *RV) {
2117 RecordValResolver R(*this, RV);
2118 resolveReferences(R, RV);
2121 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2122 LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
2123 #endif
2125 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
2126 OS << R.getNameInitAsString();
2128 ArrayRef<Init *> TArgs = R.getTemplateArgs();
2129 if (!TArgs.empty()) {
2130 OS << "<";
2131 bool NeedComma = false;
2132 for (const Init *TA : TArgs) {
2133 if (NeedComma) OS << ", ";
2134 NeedComma = true;
2135 const RecordVal *RV = R.getValue(TA);
2136 assert(RV && "Template argument record not found??");
2137 RV->print(OS, false);
2139 OS << ">";
2142 OS << " {";
2143 ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
2144 if (!SC.empty()) {
2145 OS << "\t//";
2146 for (const auto &SuperPair : SC)
2147 OS << " " << SuperPair.first->getNameInitAsString();
2149 OS << "\n";
2151 for (const RecordVal &Val : R.getValues())
2152 if (Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2153 OS << Val;
2154 for (const RecordVal &Val : R.getValues())
2155 if (!Val.getPrefix() && !R.isTemplateArg(Val.getNameInit()))
2156 OS << Val;
2158 return OS << "}\n";
2161 Init *Record::getValueInit(StringRef FieldName) const {
2162 const RecordVal *R = getValue(FieldName);
2163 if (!R || !R->getValue())
2164 PrintFatalError(getLoc(), "Record `" + getName() +
2165 "' does not have a field named `" + FieldName + "'!\n");
2166 return R->getValue();
2169 StringRef Record::getValueAsString(StringRef FieldName) const {
2170 const RecordVal *R = getValue(FieldName);
2171 if (!R || !R->getValue())
2172 PrintFatalError(getLoc(), "Record `" + getName() +
2173 "' does not have a field named `" + FieldName + "'!\n");
2175 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
2176 return SI->getValue();
2177 if (CodeInit *CI = dyn_cast<CodeInit>(R->getValue()))
2178 return CI->getValue();
2180 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2181 FieldName + "' does not have a string initializer!");
2184 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
2185 const RecordVal *R = getValue(FieldName);
2186 if (!R || !R->getValue())
2187 PrintFatalError(getLoc(), "Record `" + getName() +
2188 "' does not have a field named `" + FieldName + "'!\n");
2190 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
2191 return BI;
2192 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2193 FieldName + "' does not have a BitsInit initializer!");
2196 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
2197 const RecordVal *R = getValue(FieldName);
2198 if (!R || !R->getValue())
2199 PrintFatalError(getLoc(), "Record `" + getName() +
2200 "' does not have a field named `" + FieldName + "'!\n");
2202 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
2203 return LI;
2204 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2205 FieldName + "' does not have a list initializer!");
2208 std::vector<Record*>
2209 Record::getValueAsListOfDefs(StringRef FieldName) const {
2210 ListInit *List = getValueAsListInit(FieldName);
2211 std::vector<Record*> Defs;
2212 for (Init *I : List->getValues()) {
2213 if (DefInit *DI = dyn_cast<DefInit>(I))
2214 Defs.push_back(DI->getDef());
2215 else
2216 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2217 FieldName + "' list is not entirely DefInit!");
2219 return Defs;
2222 int64_t Record::getValueAsInt(StringRef FieldName) const {
2223 const RecordVal *R = getValue(FieldName);
2224 if (!R || !R->getValue())
2225 PrintFatalError(getLoc(), "Record `" + getName() +
2226 "' does not have a field named `" + FieldName + "'!\n");
2228 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
2229 return II->getValue();
2230 PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
2231 FieldName +
2232 "' does not have an int initializer: " +
2233 R->getValue()->getAsString());
2236 std::vector<int64_t>
2237 Record::getValueAsListOfInts(StringRef FieldName) const {
2238 ListInit *List = getValueAsListInit(FieldName);
2239 std::vector<int64_t> Ints;
2240 for (Init *I : List->getValues()) {
2241 if (IntInit *II = dyn_cast<IntInit>(I))
2242 Ints.push_back(II->getValue());
2243 else
2244 PrintFatalError(getLoc(),
2245 Twine("Record `") + getName() + "', field `" + FieldName +
2246 "' does not have a list of ints initializer: " +
2247 I->getAsString());
2249 return Ints;
2252 std::vector<StringRef>
2253 Record::getValueAsListOfStrings(StringRef FieldName) const {
2254 ListInit *List = getValueAsListInit(FieldName);
2255 std::vector<StringRef> Strings;
2256 for (Init *I : List->getValues()) {
2257 if (StringInit *SI = dyn_cast<StringInit>(I))
2258 Strings.push_back(SI->getValue());
2259 else
2260 PrintFatalError(getLoc(),
2261 Twine("Record `") + getName() + "', field `" + FieldName +
2262 "' does not have a list of strings initializer: " +
2263 I->getAsString());
2265 return Strings;
2268 Record *Record::getValueAsDef(StringRef FieldName) const {
2269 const RecordVal *R = getValue(FieldName);
2270 if (!R || !R->getValue())
2271 PrintFatalError(getLoc(), "Record `" + getName() +
2272 "' does not have a field named `" + FieldName + "'!\n");
2274 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
2275 return DI->getDef();
2276 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2277 FieldName + "' does not have a def initializer!");
2280 bool Record::getValueAsBit(StringRef FieldName) const {
2281 const RecordVal *R = getValue(FieldName);
2282 if (!R || !R->getValue())
2283 PrintFatalError(getLoc(), "Record `" + getName() +
2284 "' does not have a field named `" + FieldName + "'!\n");
2286 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2287 return BI->getValue();
2288 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2289 FieldName + "' does not have a bit initializer!");
2292 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
2293 const RecordVal *R = getValue(FieldName);
2294 if (!R || !R->getValue())
2295 PrintFatalError(getLoc(), "Record `" + getName() +
2296 "' does not have a field named `" + FieldName.str() + "'!\n");
2298 if (isa<UnsetInit>(R->getValue())) {
2299 Unset = true;
2300 return false;
2302 Unset = false;
2303 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
2304 return BI->getValue();
2305 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2306 FieldName + "' does not have a bit initializer!");
2309 DagInit *Record::getValueAsDag(StringRef FieldName) const {
2310 const RecordVal *R = getValue(FieldName);
2311 if (!R || !R->getValue())
2312 PrintFatalError(getLoc(), "Record `" + getName() +
2313 "' does not have a field named `" + FieldName + "'!\n");
2315 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
2316 return DI;
2317 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
2318 FieldName + "' does not have a dag initializer!");
2321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2322 LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
2323 #endif
2325 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
2326 OS << "------------- Classes -----------------\n";
2327 for (const auto &C : RK.getClasses())
2328 OS << "class " << *C.second;
2330 OS << "------------- Defs -----------------\n";
2331 for (const auto &D : RK.getDefs())
2332 OS << "def " << *D.second;
2333 return OS;
2336 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
2337 /// an identifier.
2338 Init *RecordKeeper::getNewAnonymousName() {
2339 return StringInit::get("anonymous_" + utostr(AnonCounter++));
2342 std::vector<Record *>
2343 RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
2344 Record *Class = getClass(ClassName);
2345 if (!Class)
2346 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2348 std::vector<Record*> Defs;
2349 for (const auto &D : getDefs())
2350 if (D.second->isSubClassOf(Class))
2351 Defs.push_back(D.second.get());
2353 return Defs;
2356 Init *MapResolver::resolve(Init *VarName) {
2357 auto It = Map.find(VarName);
2358 if (It == Map.end())
2359 return nullptr;
2361 Init *I = It->second.V;
2363 if (!It->second.Resolved && Map.size() > 1) {
2364 // Resolve mutual references among the mapped variables, but prevent
2365 // infinite recursion.
2366 Map.erase(It);
2367 I = I->resolveReferences(*this);
2368 Map[VarName] = {I, true};
2371 return I;
2374 Init *RecordResolver::resolve(Init *VarName) {
2375 Init *Val = Cache.lookup(VarName);
2376 if (Val)
2377 return Val;
2379 for (Init *S : Stack) {
2380 if (S == VarName)
2381 return nullptr; // prevent infinite recursion
2384 if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
2385 if (!isa<UnsetInit>(RV->getValue())) {
2386 Val = RV->getValue();
2387 Stack.push_back(VarName);
2388 Val = Val->resolveReferences(*this);
2389 Stack.pop_back();
2393 Cache[VarName] = Val;
2394 return Val;
2397 Init *TrackUnresolvedResolver::resolve(Init *VarName) {
2398 Init *I = nullptr;
2400 if (R) {
2401 I = R->resolve(VarName);
2402 if (I && !FoundUnresolved) {
2403 // Do not recurse into the resolved initializer, as that would change
2404 // the behavior of the resolver we're delegating, but do check to see
2405 // if there are unresolved variables remaining.
2406 TrackUnresolvedResolver Sub;
2407 I->resolveReferences(Sub);
2408 FoundUnresolved |= Sub.FoundUnresolved;
2412 if (!I)
2413 FoundUnresolved = true;
2414 return I;
2417 Init *HasReferenceResolver::resolve(Init *VarName)
2419 if (VarName == VarNameToTrack)
2420 Found = true;
2421 return nullptr;