1 //===- Record.cpp - Record implementation ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the tablegen record classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/TableGen/Error.h"
29 //===----------------------------------------------------------------------===//
30 // std::string wrapper for DenseMap purposes
31 //===----------------------------------------------------------------------===//
35 /// TableGenStringKey - This is a wrapper for std::string suitable for
36 /// using as a key to a DenseMap. Because there isn't a particularly
37 /// good way to indicate tombstone or empty keys for strings, we want
38 /// to wrap std::string to indicate that this is a "special" string
39 /// not expected to take on certain values (those of the tombstone and
40 /// empty keys). This makes things a little safer as it clarifies
41 /// that DenseMap is really not appropriate for general strings.
43 class TableGenStringKey {
45 TableGenStringKey(const std::string &str) : data(str) {}
46 TableGenStringKey(const char *str) : data(str) {}
48 const std::string &str() const { return data; }
50 friend hash_code hash_value(const TableGenStringKey &Value) {
51 using llvm::hash_value;
52 return hash_value(Value.str());
58 /// Specialize DenseMapInfo for TableGenStringKey.
59 template<> struct DenseMapInfo<TableGenStringKey> {
60 static inline TableGenStringKey getEmptyKey() {
61 TableGenStringKey Empty("<<<EMPTY KEY>>>");
64 static inline TableGenStringKey getTombstoneKey() {
65 TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
68 static unsigned getHashValue(const TableGenStringKey& Val) {
69 using llvm::hash_value;
70 return hash_value(Val);
72 static bool isEqual(const TableGenStringKey& LHS,
73 const TableGenStringKey& RHS) {
74 return LHS.str() == RHS.str();
80 //===----------------------------------------------------------------------===//
81 // Type implementations
82 //===----------------------------------------------------------------------===//
84 BitRecTy BitRecTy::Shared;
85 IntRecTy IntRecTy::Shared;
86 StringRecTy StringRecTy::Shared;
87 DagRecTy DagRecTy::Shared;
89 void RecTy::anchor() { }
90 void RecTy::dump() const { print(errs()); }
92 ListRecTy *RecTy::getListTy() {
94 ListTy = new ListRecTy(this);
98 bool RecTy::baseClassOf(const RecTy *RHS) const{
99 assert (RHS && "NULL pointer");
100 return Kind == RHS->getRecTyKind();
103 Init *BitRecTy::convertValue(BitsInit *BI) {
104 if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
105 return BI->getBit(0);
108 Init *BitRecTy::convertValue(IntInit *II) {
109 int64_t Val = II->getValue();
110 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
112 return BitInit::get(Val != 0);
115 Init *BitRecTy::convertValue(TypedInit *VI) {
116 RecTy *Ty = VI->getType();
117 if (isa<BitRecTy>(Ty))
118 return VI; // Accept variable if it is already of bit type!
119 if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
120 // Accept only bits<1> expression.
121 return BitsTy->getNumBits() == 1 ? VI : nullptr;
122 // Ternary !if can be converted to bit, but only if both sides are
123 // convertible to a bit.
124 if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
125 if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
127 if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
128 !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
136 if(RecTy::baseClassOf(RHS) || RHS->getRecTyKind() == IntRecTyKind)
138 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
139 return BitsTy->getNumBits() == 1;
143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
144 static std::vector<BitsRecTy*> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 BitsRecTy *&Ty = Shared[Sz];
149 Ty = new BitsRecTy(Sz);
153 std::string BitsRecTy::getAsString() const {
154 return "bits<" + utostr(Size) + ">";
157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
158 SmallVector<Init *, 16> NewBits(Size);
160 for (unsigned i = 0; i != Size; ++i)
161 NewBits[i] = UnsetInit::get();
163 return BitsInit::get(NewBits);
166 Init *BitsRecTy::convertValue(BitInit *UI) {
167 if (Size != 1) return nullptr; // Can only convert single bit.
168 return BitsInit::get(UI);
171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
172 /// the integer value.
173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
174 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
175 return (NumBits >= sizeof(Value) * 8) ||
176 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
179 /// convertValue from Int initializer to bits type: Split the integer up into the
180 /// appropriate bits.
182 Init *BitsRecTy::convertValue(IntInit *II) {
183 int64_t Value = II->getValue();
184 // Make sure this bitfield is large enough to hold the integer value.
185 if (!canFitInBitfield(Value, Size))
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = BitInit::get(Value & (1LL << i));
193 return BitsInit::get(NewBits);
196 Init *BitsRecTy::convertValue(BitsInit *BI) {
197 // If the number of bits is right, return it. Otherwise we need to expand or
199 if (BI->getNumBits() == Size) return BI;
203 Init *BitsRecTy::convertValue(TypedInit *VI) {
204 if (Size == 1 && isa<BitRecTy>(VI->getType()))
205 return BitsInit::get(VI);
207 if (VI->getType()->typeIsConvertibleTo(this)) {
208 SmallVector<Init *, 16> NewBits(Size);
210 for (unsigned i = 0; i != Size; ++i)
211 NewBits[i] = VarBitInit::get(VI, i);
212 return BitsInit::get(NewBits);
218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
219 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
220 return cast<BitsRecTy>(RHS)->Size == Size;
221 RecTyKind kind = RHS->getRecTyKind();
222 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
225 Init *IntRecTy::convertValue(BitInit *BI) {
226 return IntInit::get(BI->getValue());
229 Init *IntRecTy::convertValue(BitsInit *BI) {
231 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
232 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
233 Result |= Bit->getValue() << i;
237 return IntInit::get(Result);
240 Init *IntRecTy::convertValue(TypedInit *TI) {
241 if (TI->getType()->typeIsConvertibleTo(this))
242 return TI; // Accept variable if already of the right type!
246 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
247 RecTyKind kind = RHS->getRecTyKind();
248 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
251 Init *StringRecTy::convertValue(UnOpInit *BO) {
252 if (BO->getOpcode() == UnOpInit::CAST) {
253 Init *L = BO->getOperand()->convertInitializerTo(this);
254 if (!L) return nullptr;
255 if (L != BO->getOperand())
256 return UnOpInit::get(UnOpInit::CAST, L, StringRecTy::get());
260 return convertValue((TypedInit*)BO);
263 Init *StringRecTy::convertValue(BinOpInit *BO) {
264 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
265 Init *L = BO->getLHS()->convertInitializerTo(this);
266 Init *R = BO->getRHS()->convertInitializerTo(this);
267 if (!L || !R) return nullptr;
268 if (L != BO->getLHS() || R != BO->getRHS())
269 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, StringRecTy::get());
273 return convertValue((TypedInit*)BO);
277 Init *StringRecTy::convertValue(TypedInit *TI) {
278 if (isa<StringRecTy>(TI->getType()))
279 return TI; // Accept variable if already of the right type!
283 std::string ListRecTy::getAsString() const {
284 return "list<" + Ty->getAsString() + ">";
287 Init *ListRecTy::convertValue(ListInit *LI) {
288 std::vector<Init*> Elements;
290 // Verify that all of the elements of the list are subclasses of the
291 // appropriate class!
292 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
293 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
294 Elements.push_back(CI);
298 if (!isa<ListRecTy>(LI->getType()))
301 return ListInit::get(Elements, this);
304 Init *ListRecTy::convertValue(TypedInit *TI) {
305 // Ensure that TI is compatible with our class.
306 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
307 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
312 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
313 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
314 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
318 Init *DagRecTy::convertValue(TypedInit *TI) {
319 if (TI->getType()->typeIsConvertibleTo(this))
324 Init *DagRecTy::convertValue(UnOpInit *BO) {
325 if (BO->getOpcode() == UnOpInit::CAST) {
326 Init *L = BO->getOperand()->convertInitializerTo(this);
327 if (!L) return nullptr;
328 if (L != BO->getOperand())
329 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
335 Init *DagRecTy::convertValue(BinOpInit *BO) {
336 if (BO->getOpcode() == BinOpInit::CONCAT) {
337 Init *L = BO->getLHS()->convertInitializerTo(this);
338 Init *R = BO->getRHS()->convertInitializerTo(this);
339 if (!L || !R) return nullptr;
340 if (L != BO->getLHS() || R != BO->getRHS())
341 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
347 RecordRecTy *RecordRecTy::get(Record *R) {
348 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
351 std::string RecordRecTy::getAsString() const {
352 return Rec->getName();
355 Init *RecordRecTy::convertValue(DefInit *DI) {
356 // Ensure that DI is a subclass of Rec.
357 if (!DI->getDef()->isSubClassOf(Rec))
362 Init *RecordRecTy::convertValue(TypedInit *TI) {
363 // Ensure that TI is compatible with Rec.
364 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
365 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
366 RRT->getRecord() == getRecord())
371 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
372 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
376 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
379 const std::vector<Record*> &SC = Rec->getSuperClasses();
380 for (unsigned i = 0, e = SC.size(); i != e; ++i)
381 if (RTy->getRecord()->isSubClassOf(SC[i]))
387 /// resolveTypes - Find a common type that T1 and T2 convert to.
388 /// Return null if no such type exists.
390 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
391 if (T1->typeIsConvertibleTo(T2))
393 if (T2->typeIsConvertibleTo(T1))
396 // If one is a Record type, check superclasses
397 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
398 // See if T2 inherits from a type T1 also inherits from
399 const std::vector<Record *> &T1SuperClasses =
400 RecTy1->getRecord()->getSuperClasses();
401 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
402 iend = T1SuperClasses.end();
405 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
406 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
411 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
412 // See if T1 inherits from a type T2 also inherits from
413 const std::vector<Record *> &T2SuperClasses =
414 RecTy2->getRecord()->getSuperClasses();
415 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
416 iend = T2SuperClasses.end();
419 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
420 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
429 //===----------------------------------------------------------------------===//
430 // Initializer implementations
431 //===----------------------------------------------------------------------===//
433 void Init::anchor() { }
434 void Init::dump() const { return print(errs()); }
436 void UnsetInit::anchor() { }
438 UnsetInit *UnsetInit::get() {
439 static UnsetInit TheInit;
443 void BitInit::anchor() { }
445 BitInit *BitInit::get(bool V) {
446 static BitInit True(true);
447 static BitInit False(false);
449 return V ? &True : &False;
453 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
454 ID.AddInteger(Range.size());
456 for (ArrayRef<Init *>::iterator i = Range.begin(),
463 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
464 typedef FoldingSet<BitsInit> Pool;
468 ProfileBitsInit(ID, Range);
471 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
474 BitsInit *I = new BitsInit(Range);
475 ThePool.InsertNode(I, IP);
480 void BitsInit::Profile(FoldingSetNodeID &ID) const {
481 ProfileBitsInit(ID, Bits);
485 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
486 SmallVector<Init *, 16> NewBits(Bits.size());
488 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
489 if (Bits[i] >= getNumBits())
491 NewBits[i] = getBit(Bits[i]);
493 return BitsInit::get(NewBits);
496 std::string BitsInit::getAsString() const {
497 std::string Result = "{ ";
498 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
499 if (i) Result += ", ";
500 if (Init *Bit = getBit(e-i-1))
501 Result += Bit->getAsString();
505 return Result + " }";
508 // Fix bit initializer to preserve the behavior that bit reference from a unset
509 // bits initializer will resolve into VarBitInit to keep the field name and bit
510 // number used in targets with fixed insn length.
511 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
512 if (RV || !isa<UnsetInit>(After))
517 // resolveReferences - If there are any field references that refer to fields
518 // that have been filled in, we can propagate the values now.
520 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
521 bool Changed = false;
522 SmallVector<Init *, 16> NewBits(getNumBits());
524 Init *CachedInit = nullptr;
525 Init *CachedBitVar = nullptr;
526 bool CachedBitVarChanged = false;
528 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
529 Init *CurBit = Bits[i];
530 Init *CurBitVar = CurBit->getBitVar();
534 if (CurBitVar == CachedBitVar) {
535 if (CachedBitVarChanged) {
536 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
537 NewBits[i] = fixBitInit(RV, CurBit, Bit);
541 CachedBitVar = CurBitVar;
542 CachedBitVarChanged = false;
547 CurBitVar = CurBitVar->resolveReferences(R, RV);
548 CachedBitVarChanged |= B != CurBitVar;
549 Changed |= B != CurBitVar;
550 } while (B != CurBitVar);
551 CachedInit = CurBitVar;
553 if (CachedBitVarChanged) {
554 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
555 NewBits[i] = fixBitInit(RV, CurBit, Bit);
560 return BitsInit::get(NewBits);
562 return const_cast<BitsInit *>(this);
565 IntInit *IntInit::get(int64_t V) {
566 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
568 std::unique_ptr<IntInit> &I = ThePool[V];
569 if (!I) I.reset(new IntInit(V));
573 std::string IntInit::getAsString() const {
574 return itostr(Value);
578 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
579 SmallVector<Init *, 16> NewBits(Bits.size());
581 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
585 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
587 return BitsInit::get(NewBits);
590 void StringInit::anchor() { }
592 StringInit *StringInit::get(StringRef V) {
593 static StringMap<std::unique_ptr<StringInit>> ThePool;
595 std::unique_ptr<StringInit> &I = ThePool[V];
596 if (!I) I.reset(new StringInit(V));
600 static void ProfileListInit(FoldingSetNodeID &ID,
601 ArrayRef<Init *> Range,
603 ID.AddInteger(Range.size());
604 ID.AddPointer(EltTy);
606 for (ArrayRef<Init *>::iterator i = Range.begin(),
613 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
614 typedef FoldingSet<ListInit> Pool;
616 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
619 ProfileListInit(ID, Range, EltTy);
622 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
625 ListInit *I = new ListInit(Range, EltTy);
626 ThePool.InsertNode(I, IP);
627 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
631 void ListInit::Profile(FoldingSetNodeID &ID) const {
632 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
633 assert(ListType && "Bad type for ListInit!");
634 RecTy *EltTy = ListType->getElementType();
636 ProfileListInit(ID, Values, EltTy);
640 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
641 std::vector<Init*> Vals;
642 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
643 if (Elements[i] >= getSize())
645 Vals.push_back(getElement(Elements[i]));
647 return ListInit::get(Vals, getType());
650 Record *ListInit::getElementAsRecord(unsigned i) const {
651 assert(i < Values.size() && "List element index out of range!");
652 DefInit *DI = dyn_cast<DefInit>(Values[i]);
654 PrintFatalError("Expected record in list!");
658 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
659 std::vector<Init*> Resolved;
660 Resolved.reserve(getSize());
661 bool Changed = false;
663 for (unsigned i = 0, e = getSize(); i != e; ++i) {
665 Init *CurElt = getElement(i);
669 CurElt = CurElt->resolveReferences(R, RV);
670 Changed |= E != CurElt;
671 } while (E != CurElt);
672 Resolved.push_back(E);
676 return ListInit::get(Resolved, getType());
677 return const_cast<ListInit *>(this);
680 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
681 unsigned Elt) const {
682 if (Elt >= getSize())
683 return nullptr; // Out of range reference.
684 Init *E = getElement(Elt);
685 // If the element is set to some value, or if we are resolving a reference
686 // to a specific variable and that variable is explicitly unset, then
687 // replace the VarListElementInit with it.
688 if (IRV || !isa<UnsetInit>(E))
693 std::string ListInit::getAsString() const {
694 std::string Result = "[";
695 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
696 if (i) Result += ", ";
697 Result += Values[i]->getAsString();
702 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
703 unsigned Elt) const {
704 Init *Resolved = resolveReferences(R, IRV);
705 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
707 Resolved = OResolved->Fold(&R, nullptr);
710 if (Resolved != this) {
711 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
712 assert(Typed && "Expected typed init for list reference");
714 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
717 return VarListElementInit::get(Typed, Elt);
724 Init *OpInit::getBit(unsigned Bit) const {
725 if (getType() == BitRecTy::get())
726 return const_cast<OpInit*>(this);
727 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
730 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
731 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
732 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
734 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
736 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
737 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
741 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
742 switch (getOpcode()) {
744 if (getType()->getAsString() == "string") {
745 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
748 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
749 return StringInit::get(LHSd->getDef()->getName());
751 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
752 return StringInit::get(LHSi->getAsString());
754 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
755 std::string Name = LHSs->getValue();
757 // From TGParser::ParseIDValue
759 if (const RecordVal *RV = CurRec->getValue(Name)) {
760 if (RV->getType() != getType())
761 PrintFatalError("type mismatch in cast");
762 return VarInit::get(Name, RV->getType());
765 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
768 if (CurRec->isTemplateArg(TemplateArgName)) {
769 const RecordVal *RV = CurRec->getValue(TemplateArgName);
770 assert(RV && "Template arg doesn't exist??");
772 if (RV->getType() != getType())
773 PrintFatalError("type mismatch in cast");
775 return VarInit::get(TemplateArgName, RV->getType());
780 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
782 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
783 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
784 assert(RV && "Template arg doesn't exist??");
786 if (RV->getType() != getType())
787 PrintFatalError("type mismatch in cast");
789 return VarInit::get(MCName, RV->getType());
792 assert(CurRec && "NULL pointer");
793 if (Record *D = (CurRec->getRecords()).getDef(Name))
794 return DefInit::get(D);
796 PrintFatalError(CurRec->getLoc(),
797 "Undefined reference:'" + Name + "'\n");
803 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
804 assert(LHSl->getSize() != 0 && "Empty list in car");
805 return LHSl->getElement(0);
810 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
811 assert(LHSl->getSize() != 0 && "Empty list in cdr");
812 // Note the +1. We can't just pass the result of getValues()
814 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
815 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
817 ListInit::get(ArrayRef<Init *>(begin, end - begin),
824 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
825 if (LHSl->getSize() == 0) {
826 return IntInit::get(1);
828 return IntInit::get(0);
831 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
832 if (LHSs->getValue().empty()) {
833 return IntInit::get(1);
835 return IntInit::get(0);
842 return const_cast<UnOpInit *>(this);
845 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
846 Init *lhs = LHS->resolveReferences(R, RV);
849 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
850 return Fold(&R, nullptr);
853 std::string UnOpInit::getAsString() const {
856 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
857 case HEAD: Result = "!head"; break;
858 case TAIL: Result = "!tail"; break;
859 case EMPTY: Result = "!empty"; break;
861 return Result + "(" + LHS->getAsString() + ")";
864 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
865 Init *rhs, RecTy *Type) {
867 std::pair<std::pair<unsigned, Init *>, Init *>,
871 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
873 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
876 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
877 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
881 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
882 switch (getOpcode()) {
884 DagInit *LHSs = dyn_cast<DagInit>(LHS);
885 DagInit *RHSs = dyn_cast<DagInit>(RHS);
887 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
888 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
889 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
890 PrintFatalError("Concated Dag operators do not match!");
891 std::vector<Init*> Args;
892 std::vector<std::string> ArgNames;
893 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
894 Args.push_back(LHSs->getArg(i));
895 ArgNames.push_back(LHSs->getArgName(i));
897 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
898 Args.push_back(RHSs->getArg(i));
899 ArgNames.push_back(RHSs->getArgName(i));
901 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
906 ListInit *LHSs = dyn_cast<ListInit>(LHS);
907 ListInit *RHSs = dyn_cast<ListInit>(RHS);
909 std::vector<Init *> Args;
910 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
911 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
912 return ListInit::get(
913 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
918 StringInit *LHSs = dyn_cast<StringInit>(LHS);
919 StringInit *RHSs = dyn_cast<StringInit>(RHS);
921 return StringInit::get(LHSs->getValue() + RHSs->getValue());
925 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
926 // to string objects.
928 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
930 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
933 return IntInit::get(L->getValue() == R->getValue());
935 StringInit *LHSs = dyn_cast<StringInit>(LHS);
936 StringInit *RHSs = dyn_cast<StringInit>(RHS);
938 // Make sure we've resolved
940 return IntInit::get(LHSs->getValue() == RHSs->getValue());
950 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
952 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
954 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
956 switch (getOpcode()) {
957 default: llvm_unreachable("Bad opcode!");
958 case ADD: Result = LHSv + RHSv; break;
959 case AND: Result = LHSv & RHSv; break;
960 case SHL: Result = LHSv << RHSv; break;
961 case SRA: Result = LHSv >> RHSv; break;
962 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
964 return IntInit::get(Result);
969 return const_cast<BinOpInit *>(this);
972 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
973 Init *lhs = LHS->resolveReferences(R, RV);
974 Init *rhs = RHS->resolveReferences(R, RV);
976 if (LHS != lhs || RHS != rhs)
977 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
978 return Fold(&R, nullptr);
981 std::string BinOpInit::getAsString() const {
984 case CONCAT: Result = "!con"; break;
985 case ADD: Result = "!add"; break;
986 case AND: Result = "!and"; break;
987 case SHL: Result = "!shl"; break;
988 case SRA: Result = "!sra"; break;
989 case SRL: Result = "!srl"; break;
990 case EQ: Result = "!eq"; break;
991 case LISTCONCAT: Result = "!listconcat"; break;
992 case STRCONCAT: Result = "!strconcat"; break;
994 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
997 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
998 Init *mhs, Init *rhs,
1002 std::pair<std::pair<unsigned, RecTy *>, Init *>,
1008 typedef DenseMap<Key, TernOpInit *> Pool;
1009 static Pool ThePool;
1011 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
1017 TernOpInit *&I = ThePool[TheKey];
1018 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
1022 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1023 Record *CurRec, MultiClass *CurMultiClass);
1025 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1026 RecTy *Type, Record *CurRec,
1027 MultiClass *CurMultiClass) {
1028 std::vector<Init *> NewOperands;
1030 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
1032 // If this is a dag, recurse
1033 if (TArg && TArg->getType()->getAsString() == "dag") {
1034 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1035 CurRec, CurMultiClass);
1039 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1040 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1043 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1044 Type, CurRec, CurMultiClass);
1046 NewOperands.push_back(Result);
1048 NewOperands.push_back(Arg);
1050 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1051 NewOperands.push_back(Arg);
1053 NewOperands.push_back(RHSo->getOperand(i));
1057 // Now run the operator and use its result as the new leaf
1058 const OpInit *NewOp = RHSo->clone(NewOperands);
1059 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1060 return (NewVal != NewOp) ? NewVal : nullptr;
1063 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1064 Record *CurRec, MultiClass *CurMultiClass) {
1065 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1066 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1068 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1071 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1074 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1077 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1079 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1081 Init *Val = MHSd->getOperator();
1082 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1083 Type, CurRec, CurMultiClass);
1088 std::vector<std::pair<Init *, std::string> > args;
1089 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1091 std::string ArgName;
1092 Arg = MHSd->getArg(i);
1093 ArgName = MHSd->getArgName(i);
1096 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1097 CurRec, CurMultiClass);
1102 // TODO: Process arg names
1103 args.push_back(std::make_pair(Arg, ArgName));
1106 return DagInit::get(Val, "", args);
1109 std::vector<Init *> NewOperands;
1110 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1112 for (std::vector<Init *>::iterator li = NewList.begin(),
1113 liend = NewList.end();
1117 NewOperands.clear();
1118 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1119 // First, replace the foreach variable with the list item
1120 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1121 NewOperands.push_back(Item);
1123 NewOperands.push_back(RHSo->getOperand(i));
1127 // Now run the operator and use its result as the new list item
1128 const OpInit *NewOp = RHSo->clone(NewOperands);
1129 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1130 if (NewItem != NewOp)
1133 return ListInit::get(NewList, MHSl->getType());
1139 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1140 switch (getOpcode()) {
1142 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1143 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1144 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1146 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1147 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1148 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1150 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1151 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1152 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1154 if ((LHSd && MHSd && RHSd)
1155 || (LHSv && MHSv && RHSv)
1156 || (LHSs && MHSs && RHSs)) {
1158 Record *Val = RHSd->getDef();
1159 if (LHSd->getAsString() == RHSd->getAsString()) {
1160 Val = MHSd->getDef();
1162 return DefInit::get(Val);
1165 std::string Val = RHSv->getName();
1166 if (LHSv->getAsString() == RHSv->getAsString()) {
1167 Val = MHSv->getName();
1169 return VarInit::get(Val, getType());
1172 std::string Val = RHSs->getValue();
1174 std::string::size_type found;
1175 std::string::size_type idx = 0;
1177 found = Val.find(LHSs->getValue(), idx);
1178 if (found != std::string::npos) {
1179 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1181 idx = found + MHSs->getValue().size();
1182 } while (found != std::string::npos);
1184 return StringInit::get(Val);
1191 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1192 CurRec, CurMultiClass);
1200 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1201 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1202 LHSi = dyn_cast<IntInit>(I);
1204 if (LHSi->getValue()) {
1214 return const_cast<TernOpInit *>(this);
1217 Init *TernOpInit::resolveReferences(Record &R,
1218 const RecordVal *RV) const {
1219 Init *lhs = LHS->resolveReferences(R, RV);
1221 if (Opc == IF && lhs != LHS) {
1222 IntInit *Value = dyn_cast<IntInit>(lhs);
1223 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1224 Value = dyn_cast<IntInit>(I);
1227 if (Value->getValue()) {
1228 Init *mhs = MHS->resolveReferences(R, RV);
1229 return (TernOpInit::get(getOpcode(), lhs, mhs,
1230 RHS, getType()))->Fold(&R, nullptr);
1232 Init *rhs = RHS->resolveReferences(R, RV);
1233 return (TernOpInit::get(getOpcode(), lhs, MHS,
1234 rhs, getType()))->Fold(&R, nullptr);
1239 Init *mhs = MHS->resolveReferences(R, RV);
1240 Init *rhs = RHS->resolveReferences(R, RV);
1242 if (LHS != lhs || MHS != mhs || RHS != rhs)
1243 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1244 getType()))->Fold(&R, nullptr);
1245 return Fold(&R, nullptr);
1248 std::string TernOpInit::getAsString() const {
1251 case SUBST: Result = "!subst"; break;
1252 case FOREACH: Result = "!foreach"; break;
1253 case IF: Result = "!if"; break;
1255 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1256 + RHS->getAsString() + ")";
1259 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1260 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1261 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1262 return Field->getType();
1267 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1268 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1269 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1270 unsigned NumBits = T->getNumBits();
1272 SmallVector<Init *, 16> NewBits(Bits.size());
1273 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1274 if (Bits[i] >= NumBits)
1277 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1279 return BitsInit::get(NewBits);
1283 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1284 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1285 if (!T) return nullptr; // Cannot subscript a non-list variable.
1287 if (Elements.size() == 1)
1288 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1290 std::vector<Init*> ListInits;
1291 ListInits.reserve(Elements.size());
1292 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1293 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1295 return ListInit::get(ListInits, T);
1299 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1300 Init *Value = StringInit::get(VN);
1301 return VarInit::get(Value, T);
1304 VarInit *VarInit::get(Init *VN, RecTy *T) {
1305 typedef std::pair<RecTy *, Init *> Key;
1306 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1308 Key TheKey(std::make_pair(T, VN));
1310 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1311 if (!I) I.reset(new VarInit(VN, T));
1315 const std::string &VarInit::getName() const {
1316 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1317 assert(NameString && "VarInit name is not a string!");
1318 return NameString->getValue();
1321 Init *VarInit::getBit(unsigned Bit) const {
1322 if (getType() == BitRecTy::get())
1323 return const_cast<VarInit*>(this);
1324 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1327 Init *VarInit::resolveListElementReference(Record &R,
1328 const RecordVal *IRV,
1329 unsigned Elt) const {
1330 if (R.isTemplateArg(getNameInit())) return nullptr;
1331 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1333 RecordVal *RV = R.getValue(getNameInit());
1334 assert(RV && "Reference to a non-existent variable?");
1335 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1337 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1338 assert(VI && "Invalid list element!");
1339 return VarListElementInit::get(VI, Elt);
1342 if (Elt >= LI->getSize())
1343 return nullptr; // Out of range reference.
1344 Init *E = LI->getElement(Elt);
1345 // If the element is set to some value, or if we are resolving a reference
1346 // to a specific variable and that variable is explicitly unset, then
1347 // replace the VarListElementInit with it.
1348 if (IRV || !isa<UnsetInit>(E))
1354 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1355 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1356 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1357 return RV->getType();
1361 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1362 const std::string &FieldName) const {
1363 if (isa<RecordRecTy>(getType()))
1364 if (const RecordVal *Val = R.getValue(VarName)) {
1365 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1367 Init *TheInit = Val->getValue();
1368 assert(TheInit != this && "Infinite loop detected!");
1369 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1377 /// resolveReferences - This method is used by classes that refer to other
1378 /// variables which may not be defined at the time the expression is formed.
1379 /// If a value is set for the variable later, this method will be called on
1380 /// users of the value to allow the value to propagate out.
1382 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1383 if (RecordVal *Val = R.getValue(VarName))
1384 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1385 return Val->getValue();
1386 return const_cast<VarInit *>(this);
1389 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1390 typedef std::pair<TypedInit *, unsigned> Key;
1391 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1393 Key TheKey(std::make_pair(T, B));
1395 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1396 if (!I) I.reset(new VarBitInit(T, B));
1400 std::string VarBitInit::getAsString() const {
1401 return TI->getAsString() + "{" + utostr(Bit) + "}";
1404 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1405 Init *I = TI->resolveReferences(R, RV);
1407 return I->getBit(getBitNum());
1409 return const_cast<VarBitInit*>(this);
1412 VarListElementInit *VarListElementInit::get(TypedInit *T,
1414 typedef std::pair<TypedInit *, unsigned> Key;
1415 typedef DenseMap<Key, VarListElementInit *> Pool;
1417 static Pool ThePool;
1419 Key TheKey(std::make_pair(T, E));
1421 VarListElementInit *&I = ThePool[TheKey];
1422 if (!I) I = new VarListElementInit(T, E);
1426 std::string VarListElementInit::getAsString() const {
1427 return TI->getAsString() + "[" + utostr(Element) + "]";
1431 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1432 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1435 return const_cast<VarListElementInit *>(this);
1438 Init *VarListElementInit::getBit(unsigned Bit) const {
1439 if (getType() == BitRecTy::get())
1440 return const_cast<VarListElementInit*>(this);
1441 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1444 Init *VarListElementInit:: resolveListElementReference(Record &R,
1445 const RecordVal *RV,
1446 unsigned Elt) const {
1447 Init *Result = TI->resolveListElementReference(R, RV, Element);
1450 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1451 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1452 if (Result2) return Result2;
1453 return new VarListElementInit(TInit, Elt);
1461 DefInit *DefInit::get(Record *R) {
1462 return R->getDefInit();
1465 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1466 if (const RecordVal *RV = Def->getValue(FieldName))
1467 return RV->getType();
1471 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1472 const std::string &FieldName) const {
1473 return Def->getValue(FieldName)->getValue();
1477 std::string DefInit::getAsString() const {
1478 return Def->getName();
1481 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1482 typedef std::pair<Init *, TableGenStringKey> Key;
1483 typedef DenseMap<Key, FieldInit *> Pool;
1484 static Pool ThePool;
1486 Key TheKey(std::make_pair(R, FN));
1488 FieldInit *&I = ThePool[TheKey];
1489 if (!I) I = new FieldInit(R, FN);
1493 Init *FieldInit::getBit(unsigned Bit) const {
1494 if (getType() == BitRecTy::get())
1495 return const_cast<FieldInit*>(this);
1496 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1499 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1500 unsigned Elt) const {
1501 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1502 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1503 if (Elt >= LI->getSize()) return nullptr;
1504 Init *E = LI->getElement(Elt);
1506 // If the element is set to some value, or if we are resolving a
1507 // reference to a specific variable and that variable is explicitly
1508 // unset, then replace the VarListElementInit with it.
1509 if (RV || !isa<UnsetInit>(E))
1515 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1516 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1518 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1520 Init *BVR = BitsVal->resolveReferences(R, RV);
1521 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1524 if (NewRec != Rec) {
1525 return FieldInit::get(NewRec, FieldName);
1527 return const_cast<FieldInit *>(this);
1530 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1531 ArrayRef<Init *> ArgRange,
1532 ArrayRef<std::string> NameRange) {
1536 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1537 ArrayRef<std::string>::iterator Name = NameRange.begin();
1538 while (Arg != ArgRange.end()) {
1539 assert(Name != NameRange.end() && "Arg name underflow!");
1540 ID.AddPointer(*Arg++);
1541 ID.AddString(*Name++);
1543 assert(Name == NameRange.end() && "Arg name overflow!");
1547 DagInit::get(Init *V, const std::string &VN,
1548 ArrayRef<Init *> ArgRange,
1549 ArrayRef<std::string> NameRange) {
1550 typedef FoldingSet<DagInit> Pool;
1551 static Pool ThePool;
1553 FoldingSetNodeID ID;
1554 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1557 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1560 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1561 ThePool.InsertNode(I, IP);
1567 DagInit::get(Init *V, const std::string &VN,
1568 const std::vector<std::pair<Init*, std::string> > &args) {
1569 typedef std::pair<Init*, std::string> PairType;
1571 std::vector<Init *> Args;
1572 std::vector<std::string> Names;
1574 for (std::vector<PairType>::const_iterator i = args.begin(),
1578 Args.push_back(i->first);
1579 Names.push_back(i->second);
1582 return DagInit::get(V, VN, Args, Names);
1585 void DagInit::Profile(FoldingSetNodeID &ID) const {
1586 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1589 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1590 std::vector<Init*> NewArgs;
1591 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1592 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1594 Init *Op = Val->resolveReferences(R, RV);
1596 if (Args != NewArgs || Op != Val)
1597 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1599 return const_cast<DagInit *>(this);
1603 std::string DagInit::getAsString() const {
1604 std::string Result = "(" + Val->getAsString();
1605 if (!ValName.empty())
1606 Result += ":" + ValName;
1607 if (!Args.empty()) {
1608 Result += " " + Args[0]->getAsString();
1609 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1610 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1611 Result += ", " + Args[i]->getAsString();
1612 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1615 return Result + ")";
1619 //===----------------------------------------------------------------------===//
1620 // Other implementations
1621 //===----------------------------------------------------------------------===//
1623 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1624 : Name(N), Ty(T), Prefix(P) {
1625 Value = Ty->convertValue(UnsetInit::get());
1626 assert(Value && "Cannot create unset value for current type!");
1629 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1630 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1631 Value = Ty->convertValue(UnsetInit::get());
1632 assert(Value && "Cannot create unset value for current type!");
1635 const std::string &RecordVal::getName() const {
1636 StringInit *NameString = dyn_cast<StringInit>(Name);
1637 assert(NameString && "RecordVal name is not a string!");
1638 return NameString->getValue();
1641 void RecordVal::dump() const { errs() << *this; }
1643 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1644 if (getPrefix()) OS << "field ";
1645 OS << *getType() << " " << getNameInitAsString();
1648 OS << " = " << *getValue();
1650 if (PrintSem) OS << ";\n";
1653 unsigned Record::LastID = 0;
1655 void Record::init() {
1658 // Every record potentially has a def at the top. This value is
1659 // replaced with the top-level def name at instantiation time.
1660 RecordVal DN("NAME", StringRecTy::get(), 0);
1664 void Record::checkName() {
1665 // Ensure the record name has string type.
1666 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1667 assert(TypedName && "Record name is not typed!");
1668 RecTy *Type = TypedName->getType();
1669 if (!isa<StringRecTy>(Type))
1670 PrintFatalError(getLoc(), "Record name is not a string!");
1673 DefInit *Record::getDefInit() {
1675 TheInit = new DefInit(this, new RecordRecTy(this));
1679 const std::string &Record::getName() const {
1680 const StringInit *NameString = dyn_cast<StringInit>(Name);
1681 assert(NameString && "Record name is not a string!");
1682 return NameString->getValue();
1685 void Record::setName(Init *NewName) {
1688 // DO NOT resolve record values to the name at this point because
1689 // there might be default values for arguments of this def. Those
1690 // arguments might not have been resolved yet so we don't want to
1691 // prematurely assume values for those arguments were not passed to
1694 // Nonetheless, it may be that some of this Record's values
1695 // reference the record name. Indeed, the reason for having the
1696 // record name be an Init is to provide this flexibility. The extra
1697 // resolve steps after completely instantiating defs takes care of
1698 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1701 void Record::setName(const std::string &Name) {
1702 setName(StringInit::get(Name));
1705 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1706 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1708 void Record::resolveReferencesTo(const RecordVal *RV) {
1709 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1710 if (RV == &Values[i]) // Skip resolve the same field as the given one
1712 if (Init *V = Values[i].getValue())
1713 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1714 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1715 + Values[i].getNameInitAsString()
1716 + "' after resolving references"
1717 + (RV ? " against '" + RV->getNameInitAsString()
1719 + RV->getValue()->getAsUnquotedString() + ")"
1723 Init *OldName = getNameInit();
1724 Init *NewName = Name->resolveReferences(*this, RV);
1725 if (NewName != OldName) {
1726 // Re-register with RecordKeeper.
1731 void Record::dump() const { errs() << *this; }
1733 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1734 OS << R.getNameInitAsString();
1736 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1737 if (!TArgs.empty()) {
1739 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1741 const RecordVal *RV = R.getValue(TArgs[i]);
1742 assert(RV && "Template argument record not found??");
1743 RV->print(OS, false);
1749 const std::vector<Record*> &SC = R.getSuperClasses();
1752 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1753 OS << " " << SC[i]->getNameInitAsString();
1757 const std::vector<RecordVal> &Vals = R.getValues();
1758 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1759 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1761 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1762 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1768 /// getValueInit - Return the initializer for a value with the specified name,
1769 /// or abort if the field does not exist.
1771 Init *Record::getValueInit(StringRef FieldName) const {
1772 const RecordVal *R = getValue(FieldName);
1773 if (!R || !R->getValue())
1774 PrintFatalError(getLoc(), "Record `" + getName() +
1775 "' does not have a field named `" + FieldName + "'!\n");
1776 return R->getValue();
1780 /// getValueAsString - This method looks up the specified field and returns its
1781 /// value as a string, aborts if the field does not exist or if
1782 /// the value is not a string.
1784 std::string Record::getValueAsString(StringRef FieldName) const {
1785 const RecordVal *R = getValue(FieldName);
1786 if (!R || !R->getValue())
1787 PrintFatalError(getLoc(), "Record `" + getName() +
1788 "' does not have a field named `" + FieldName + "'!\n");
1790 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1791 return SI->getValue();
1792 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1793 FieldName + "' does not have a string initializer!");
1796 /// getValueAsBitsInit - This method looks up the specified field and returns
1797 /// its value as a BitsInit, aborts if the field does not exist or if
1798 /// the value is not the right type.
1800 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1801 const RecordVal *R = getValue(FieldName);
1802 if (!R || !R->getValue())
1803 PrintFatalError(getLoc(), "Record `" + getName() +
1804 "' does not have a field named `" + FieldName + "'!\n");
1806 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1808 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1809 FieldName + "' does not have a BitsInit initializer!");
1812 /// getValueAsListInit - This method looks up the specified field and returns
1813 /// its value as a ListInit, aborting if the field does not exist or if
1814 /// the value is not the right type.
1816 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1817 const RecordVal *R = getValue(FieldName);
1818 if (!R || !R->getValue())
1819 PrintFatalError(getLoc(), "Record `" + getName() +
1820 "' does not have a field named `" + FieldName + "'!\n");
1822 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1824 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1825 FieldName + "' does not have a list initializer!");
1828 /// getValueAsListOfDefs - This method looks up the specified field and returns
1829 /// its value as a vector of records, aborting if the field does not exist
1830 /// or if the value is not the right type.
1832 std::vector<Record*>
1833 Record::getValueAsListOfDefs(StringRef FieldName) const {
1834 ListInit *List = getValueAsListInit(FieldName);
1835 std::vector<Record*> Defs;
1836 for (unsigned i = 0; i < List->getSize(); i++) {
1837 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1838 Defs.push_back(DI->getDef());
1840 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1841 FieldName + "' list is not entirely DefInit!");
1847 /// getValueAsInt - This method looks up the specified field and returns its
1848 /// value as an int64_t, aborting if the field does not exist or if the value
1849 /// is not the right type.
1851 int64_t Record::getValueAsInt(StringRef FieldName) const {
1852 const RecordVal *R = getValue(FieldName);
1853 if (!R || !R->getValue())
1854 PrintFatalError(getLoc(), "Record `" + getName() +
1855 "' does not have a field named `" + FieldName + "'!\n");
1857 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1858 return II->getValue();
1859 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1860 FieldName + "' does not have an int initializer!");
1863 /// getValueAsListOfInts - This method looks up the specified field and returns
1864 /// its value as a vector of integers, aborting if the field does not exist or
1865 /// if the value is not the right type.
1867 std::vector<int64_t>
1868 Record::getValueAsListOfInts(StringRef FieldName) const {
1869 ListInit *List = getValueAsListInit(FieldName);
1870 std::vector<int64_t> Ints;
1871 for (unsigned i = 0; i < List->getSize(); i++) {
1872 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1873 Ints.push_back(II->getValue());
1875 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1876 FieldName + "' does not have a list of ints initializer!");
1882 /// getValueAsListOfStrings - This method looks up the specified field and
1883 /// returns its value as a vector of strings, aborting if the field does not
1884 /// exist or if the value is not the right type.
1886 std::vector<std::string>
1887 Record::getValueAsListOfStrings(StringRef FieldName) const {
1888 ListInit *List = getValueAsListInit(FieldName);
1889 std::vector<std::string> Strings;
1890 for (unsigned i = 0; i < List->getSize(); i++) {
1891 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1892 Strings.push_back(II->getValue());
1894 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1895 FieldName + "' does not have a list of strings initializer!");
1901 /// getValueAsDef - This method looks up the specified field and returns its
1902 /// value as a Record, aborting if the field does not exist or if the value
1903 /// is not the right type.
1905 Record *Record::getValueAsDef(StringRef FieldName) const {
1906 const RecordVal *R = getValue(FieldName);
1907 if (!R || !R->getValue())
1908 PrintFatalError(getLoc(), "Record `" + getName() +
1909 "' does not have a field named `" + FieldName + "'!\n");
1911 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1912 return DI->getDef();
1913 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1914 FieldName + "' does not have a def initializer!");
1917 /// getValueAsBit - This method looks up the specified field and returns its
1918 /// value as a bit, aborting if the field does not exist or if the value is
1919 /// not the right type.
1921 bool Record::getValueAsBit(StringRef FieldName) const {
1922 const RecordVal *R = getValue(FieldName);
1923 if (!R || !R->getValue())
1924 PrintFatalError(getLoc(), "Record `" + getName() +
1925 "' does not have a field named `" + FieldName + "'!\n");
1927 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1928 return BI->getValue();
1929 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1930 FieldName + "' does not have a bit initializer!");
1933 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1934 const RecordVal *R = getValue(FieldName);
1935 if (!R || !R->getValue())
1936 PrintFatalError(getLoc(), "Record `" + getName() +
1937 "' does not have a field named `" + FieldName.str() + "'!\n");
1939 if (isa<UnsetInit>(R->getValue())) {
1944 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1945 return BI->getValue();
1946 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1947 FieldName + "' does not have a bit initializer!");
1950 /// getValueAsDag - This method looks up the specified field and returns its
1951 /// value as an Dag, aborting if the field does not exist or if the value is
1952 /// not the right type.
1954 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1955 const RecordVal *R = getValue(FieldName);
1956 if (!R || !R->getValue())
1957 PrintFatalError(getLoc(), "Record `" + getName() +
1958 "' does not have a field named `" + FieldName + "'!\n");
1960 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1962 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1963 FieldName + "' does not have a dag initializer!");
1967 void MultiClass::dump() const {
1968 errs() << "Record:\n";
1971 errs() << "Defs:\n";
1972 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1973 rend = DefPrototypes.end();
1981 void RecordKeeper::dump() const { errs() << *this; }
1983 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1984 OS << "------------- Classes -----------------\n";
1985 const auto &Classes = RK.getClasses();
1986 for (const auto &C : Classes)
1987 OS << "class " << *C.second;
1989 OS << "------------- Defs -----------------\n";
1990 const auto &Defs = RK.getDefs();
1991 for (const auto &D : Defs)
1992 OS << "def " << *D.second;
1997 /// getAllDerivedDefinitions - This method returns all concrete definitions
1998 /// that derive from the specified class name. If a class with the specified
1999 /// name does not exist, an error is printed and true is returned.
2000 std::vector<Record*>
2001 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2002 Record *Class = getClass(ClassName);
2004 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
2006 std::vector<Record*> Defs;
2007 for (const auto &D : getDefs())
2008 if (D.second->isSubClassOf(Class))
2009 Defs.push_back(D.second.get());
2014 /// QualifyName - Return an Init with a qualifier prefix referring
2015 /// to CurRec's name.
2016 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2017 Init *Name, const std::string &Scoper) {
2018 RecTy *Type = cast<TypedInit>(Name)->getType();
2020 BinOpInit *NewName =
2021 BinOpInit::get(BinOpInit::STRCONCAT,
2022 BinOpInit::get(BinOpInit::STRCONCAT,
2023 CurRec.getNameInit(),
2024 StringInit::get(Scoper),
2025 Type)->Fold(&CurRec, CurMultiClass),
2029 if (CurMultiClass && Scoper != "::") {
2031 BinOpInit::get(BinOpInit::STRCONCAT,
2032 BinOpInit::get(BinOpInit::STRCONCAT,
2033 CurMultiClass->Rec.getNameInit(),
2034 StringInit::get("::"),
2035 Type)->Fold(&CurRec, CurMultiClass),
2036 NewName->Fold(&CurRec, CurMultiClass),
2040 return NewName->Fold(&CurRec, CurMultiClass);
2043 /// QualifyName - Return an Init with a qualifier prefix referring
2044 /// to CurRec's name.
2045 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2046 const std::string &Name,
2047 const std::string &Scoper) {
2048 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);