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.reset(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<std::unique_ptr<BitsRecTy>> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
149 Ty.reset(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 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
400 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
401 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
406 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
407 // See if T1 inherits from a type T2 also inherits from
408 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
409 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
410 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
419 //===----------------------------------------------------------------------===//
420 // Initializer implementations
421 //===----------------------------------------------------------------------===//
423 void Init::anchor() { }
424 void Init::dump() const { return print(errs()); }
426 void UnsetInit::anchor() { }
428 UnsetInit *UnsetInit::get() {
429 static UnsetInit TheInit;
433 void BitInit::anchor() { }
435 BitInit *BitInit::get(bool V) {
436 static BitInit True(true);
437 static BitInit False(false);
439 return V ? &True : &False;
443 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
444 ID.AddInteger(Range.size());
446 for (Init *I : Range)
450 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
451 static FoldingSet<BitsInit> ThePool;
452 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
455 ProfileBitsInit(ID, Range);
458 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
461 BitsInit *I = new BitsInit(Range);
462 ThePool.InsertNode(I, IP);
463 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
467 void BitsInit::Profile(FoldingSetNodeID &ID) const {
468 ProfileBitsInit(ID, Bits);
472 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
473 SmallVector<Init *, 16> NewBits(Bits.size());
475 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
476 if (Bits[i] >= getNumBits())
478 NewBits[i] = getBit(Bits[i]);
480 return BitsInit::get(NewBits);
483 std::string BitsInit::getAsString() const {
484 std::string Result = "{ ";
485 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
486 if (i) Result += ", ";
487 if (Init *Bit = getBit(e-i-1))
488 Result += Bit->getAsString();
492 return Result + " }";
495 // Fix bit initializer to preserve the behavior that bit reference from a unset
496 // bits initializer will resolve into VarBitInit to keep the field name and bit
497 // number used in targets with fixed insn length.
498 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
499 if (RV || !isa<UnsetInit>(After))
504 // resolveReferences - If there are any field references that refer to fields
505 // that have been filled in, we can propagate the values now.
507 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
508 bool Changed = false;
509 SmallVector<Init *, 16> NewBits(getNumBits());
511 Init *CachedInit = nullptr;
512 Init *CachedBitVar = nullptr;
513 bool CachedBitVarChanged = false;
515 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
516 Init *CurBit = Bits[i];
517 Init *CurBitVar = CurBit->getBitVar();
521 if (CurBitVar == CachedBitVar) {
522 if (CachedBitVarChanged) {
523 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
524 NewBits[i] = fixBitInit(RV, CurBit, Bit);
528 CachedBitVar = CurBitVar;
529 CachedBitVarChanged = false;
534 CurBitVar = CurBitVar->resolveReferences(R, RV);
535 CachedBitVarChanged |= B != CurBitVar;
536 Changed |= B != CurBitVar;
537 } while (B != CurBitVar);
538 CachedInit = CurBitVar;
540 if (CachedBitVarChanged) {
541 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
542 NewBits[i] = fixBitInit(RV, CurBit, Bit);
547 return BitsInit::get(NewBits);
549 return const_cast<BitsInit *>(this);
552 IntInit *IntInit::get(int64_t V) {
553 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
555 std::unique_ptr<IntInit> &I = ThePool[V];
556 if (!I) I.reset(new IntInit(V));
560 std::string IntInit::getAsString() const {
561 return itostr(Value);
565 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
566 SmallVector<Init *, 16> NewBits(Bits.size());
568 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
572 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
574 return BitsInit::get(NewBits);
577 void StringInit::anchor() { }
579 StringInit *StringInit::get(StringRef V) {
580 static StringMap<std::unique_ptr<StringInit>> ThePool;
582 std::unique_ptr<StringInit> &I = ThePool[V];
583 if (!I) I.reset(new StringInit(V));
587 static void ProfileListInit(FoldingSetNodeID &ID,
588 ArrayRef<Init *> Range,
590 ID.AddInteger(Range.size());
591 ID.AddPointer(EltTy);
593 for (Init *I : Range)
597 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
598 static FoldingSet<ListInit> ThePool;
599 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
602 ProfileListInit(ID, Range, EltTy);
605 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
608 ListInit *I = new ListInit(Range, EltTy);
609 ThePool.InsertNode(I, IP);
610 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
614 void ListInit::Profile(FoldingSetNodeID &ID) const {
615 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
617 ProfileListInit(ID, Values, EltTy);
621 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
622 std::vector<Init*> Vals;
623 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
624 if (Elements[i] >= getSize())
626 Vals.push_back(getElement(Elements[i]));
628 return ListInit::get(Vals, getType());
631 Record *ListInit::getElementAsRecord(unsigned i) const {
632 assert(i < Values.size() && "List element index out of range!");
633 DefInit *DI = dyn_cast<DefInit>(Values[i]);
635 PrintFatalError("Expected record in list!");
639 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
640 std::vector<Init*> Resolved;
641 Resolved.reserve(getSize());
642 bool Changed = false;
644 for (unsigned i = 0, e = getSize(); i != e; ++i) {
646 Init *CurElt = getElement(i);
650 CurElt = CurElt->resolveReferences(R, RV);
651 Changed |= E != CurElt;
652 } while (E != CurElt);
653 Resolved.push_back(E);
657 return ListInit::get(Resolved, getType());
658 return const_cast<ListInit *>(this);
661 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
662 unsigned Elt) const {
663 if (Elt >= getSize())
664 return nullptr; // Out of range reference.
665 Init *E = getElement(Elt);
666 // If the element is set to some value, or if we are resolving a reference
667 // to a specific variable and that variable is explicitly unset, then
668 // replace the VarListElementInit with it.
669 if (IRV || !isa<UnsetInit>(E))
674 std::string ListInit::getAsString() const {
675 std::string Result = "[";
676 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
677 if (i) Result += ", ";
678 Result += Values[i]->getAsString();
683 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
684 unsigned Elt) const {
685 Init *Resolved = resolveReferences(R, IRV);
686 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
688 Resolved = OResolved->Fold(&R, nullptr);
691 if (Resolved != this) {
692 TypedInit *Typed = cast<TypedInit>(Resolved);
693 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
695 return VarListElementInit::get(Typed, Elt);
701 Init *OpInit::getBit(unsigned Bit) const {
702 if (getType() == BitRecTy::get())
703 return const_cast<OpInit*>(this);
704 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
707 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
708 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
709 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
711 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
713 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
714 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
718 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
719 switch (getOpcode()) {
721 if (getType()->getAsString() == "string") {
722 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
725 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
726 return StringInit::get(LHSd->getDef()->getName());
728 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
729 return StringInit::get(LHSi->getAsString());
731 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
732 std::string Name = LHSs->getValue();
734 // From TGParser::ParseIDValue
736 if (const RecordVal *RV = CurRec->getValue(Name)) {
737 if (RV->getType() != getType())
738 PrintFatalError("type mismatch in cast");
739 return VarInit::get(Name, RV->getType());
742 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
745 if (CurRec->isTemplateArg(TemplateArgName)) {
746 const RecordVal *RV = CurRec->getValue(TemplateArgName);
747 assert(RV && "Template arg doesn't exist??");
749 if (RV->getType() != getType())
750 PrintFatalError("type mismatch in cast");
752 return VarInit::get(TemplateArgName, RV->getType());
757 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
759 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
760 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
761 assert(RV && "Template arg doesn't exist??");
763 if (RV->getType() != getType())
764 PrintFatalError("type mismatch in cast");
766 return VarInit::get(MCName, RV->getType());
769 assert(CurRec && "NULL pointer");
770 if (Record *D = (CurRec->getRecords()).getDef(Name))
771 return DefInit::get(D);
773 PrintFatalError(CurRec->getLoc(),
774 "Undefined reference:'" + Name + "'\n");
780 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
781 assert(LHSl->getSize() != 0 && "Empty list in car");
782 return LHSl->getElement(0);
787 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
788 assert(LHSl->getSize() != 0 && "Empty list in cdr");
789 // Note the +1. We can't just pass the result of getValues()
791 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
792 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
794 ListInit::get(ArrayRef<Init *>(begin, end - begin),
801 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
802 if (LHSl->getSize() == 0) {
803 return IntInit::get(1);
805 return IntInit::get(0);
808 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
809 if (LHSs->getValue().empty()) {
810 return IntInit::get(1);
812 return IntInit::get(0);
819 return const_cast<UnOpInit *>(this);
822 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
823 Init *lhs = LHS->resolveReferences(R, RV);
826 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
827 return Fold(&R, nullptr);
830 std::string UnOpInit::getAsString() const {
833 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
834 case HEAD: Result = "!head"; break;
835 case TAIL: Result = "!tail"; break;
836 case EMPTY: Result = "!empty"; break;
838 return Result + "(" + LHS->getAsString() + ")";
841 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
842 Init *rhs, RecTy *Type) {
844 std::pair<std::pair<unsigned, Init *>, Init *>,
848 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
850 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
853 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
854 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
858 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
859 switch (getOpcode()) {
861 DagInit *LHSs = dyn_cast<DagInit>(LHS);
862 DagInit *RHSs = dyn_cast<DagInit>(RHS);
864 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
865 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
866 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
867 PrintFatalError("Concated Dag operators do not match!");
868 std::vector<Init*> Args;
869 std::vector<std::string> ArgNames;
870 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
871 Args.push_back(LHSs->getArg(i));
872 ArgNames.push_back(LHSs->getArgName(i));
874 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
875 Args.push_back(RHSs->getArg(i));
876 ArgNames.push_back(RHSs->getArgName(i));
878 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
883 ListInit *LHSs = dyn_cast<ListInit>(LHS);
884 ListInit *RHSs = dyn_cast<ListInit>(RHS);
886 std::vector<Init *> Args;
887 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
888 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
889 return ListInit::get(
890 Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
895 StringInit *LHSs = dyn_cast<StringInit>(LHS);
896 StringInit *RHSs = dyn_cast<StringInit>(RHS);
898 return StringInit::get(LHSs->getValue() + RHSs->getValue());
902 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
903 // to string objects.
905 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
907 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
910 return IntInit::get(L->getValue() == R->getValue());
912 StringInit *LHSs = dyn_cast<StringInit>(LHS);
913 StringInit *RHSs = dyn_cast<StringInit>(RHS);
915 // Make sure we've resolved
917 return IntInit::get(LHSs->getValue() == RHSs->getValue());
927 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
929 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
931 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
933 switch (getOpcode()) {
934 default: llvm_unreachable("Bad opcode!");
935 case ADD: Result = LHSv + RHSv; break;
936 case AND: Result = LHSv & RHSv; break;
937 case SHL: Result = LHSv << RHSv; break;
938 case SRA: Result = LHSv >> RHSv; break;
939 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
941 return IntInit::get(Result);
946 return const_cast<BinOpInit *>(this);
949 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
950 Init *lhs = LHS->resolveReferences(R, RV);
951 Init *rhs = RHS->resolveReferences(R, RV);
953 if (LHS != lhs || RHS != rhs)
954 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
955 return Fold(&R, nullptr);
958 std::string BinOpInit::getAsString() const {
961 case CONCAT: Result = "!con"; break;
962 case ADD: Result = "!add"; break;
963 case AND: Result = "!and"; break;
964 case SHL: Result = "!shl"; break;
965 case SRA: Result = "!sra"; break;
966 case SRL: Result = "!srl"; break;
967 case EQ: Result = "!eq"; break;
968 case LISTCONCAT: Result = "!listconcat"; break;
969 case STRCONCAT: Result = "!strconcat"; break;
971 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
974 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
975 Init *mhs, Init *rhs,
979 std::pair<std::pair<unsigned, RecTy *>, Init *>,
985 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
987 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
993 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
994 if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
998 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
999 Record *CurRec, MultiClass *CurMultiClass);
1001 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
1002 RecTy *Type, Record *CurRec,
1003 MultiClass *CurMultiClass) {
1004 // If this is a dag, recurse
1005 if (auto *TArg = dyn_cast<TypedInit>(Arg))
1006 if (TArg->getType()->getAsString() == "dag")
1007 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
1009 std::vector<Init *> NewOperands;
1010 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1011 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
1012 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1013 Type, CurRec, CurMultiClass))
1014 NewOperands.push_back(Result);
1016 NewOperands.push_back(Arg);
1017 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1018 NewOperands.push_back(Arg);
1020 NewOperands.push_back(RHSo->getOperand(i));
1024 // Now run the operator and use its result as the new leaf
1025 const OpInit *NewOp = RHSo->clone(NewOperands);
1026 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1027 return (NewVal != NewOp) ? NewVal : nullptr;
1030 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1031 Record *CurRec, MultiClass *CurMultiClass) {
1032 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1033 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1035 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1038 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1041 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1044 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1046 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1048 Init *Val = MHSd->getOperator();
1049 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1050 Type, CurRec, CurMultiClass);
1055 std::vector<std::pair<Init *, std::string> > args;
1056 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1058 std::string ArgName;
1059 Arg = MHSd->getArg(i);
1060 ArgName = MHSd->getArgName(i);
1063 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1064 CurRec, CurMultiClass);
1069 // TODO: Process arg names
1070 args.push_back(std::make_pair(Arg, ArgName));
1073 return DagInit::get(Val, "", args);
1076 std::vector<Init *> NewOperands;
1077 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1079 for (std::vector<Init *>::iterator li = NewList.begin(),
1080 liend = NewList.end();
1084 NewOperands.clear();
1085 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1086 // First, replace the foreach variable with the list item
1087 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1088 NewOperands.push_back(Item);
1090 NewOperands.push_back(RHSo->getOperand(i));
1094 // Now run the operator and use its result as the new list item
1095 const OpInit *NewOp = RHSo->clone(NewOperands);
1096 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1097 if (NewItem != NewOp)
1100 return ListInit::get(NewList, MHSl->getType());
1106 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1107 switch (getOpcode()) {
1109 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1110 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1111 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1113 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1114 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1115 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1117 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1118 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1119 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1121 if ((LHSd && MHSd && RHSd)
1122 || (LHSv && MHSv && RHSv)
1123 || (LHSs && MHSs && RHSs)) {
1125 Record *Val = RHSd->getDef();
1126 if (LHSd->getAsString() == RHSd->getAsString()) {
1127 Val = MHSd->getDef();
1129 return DefInit::get(Val);
1132 std::string Val = RHSv->getName();
1133 if (LHSv->getAsString() == RHSv->getAsString()) {
1134 Val = MHSv->getName();
1136 return VarInit::get(Val, getType());
1139 std::string Val = RHSs->getValue();
1141 std::string::size_type found;
1142 std::string::size_type idx = 0;
1144 found = Val.find(LHSs->getValue(), idx);
1145 if (found != std::string::npos) {
1146 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1148 idx = found + MHSs->getValue().size();
1149 } while (found != std::string::npos);
1151 return StringInit::get(Val);
1158 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1159 CurRec, CurMultiClass);
1167 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1168 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1169 LHSi = dyn_cast<IntInit>(I);
1171 if (LHSi->getValue()) {
1181 return const_cast<TernOpInit *>(this);
1184 Init *TernOpInit::resolveReferences(Record &R,
1185 const RecordVal *RV) const {
1186 Init *lhs = LHS->resolveReferences(R, RV);
1188 if (Opc == IF && lhs != LHS) {
1189 IntInit *Value = dyn_cast<IntInit>(lhs);
1190 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1191 Value = dyn_cast<IntInit>(I);
1194 if (Value->getValue()) {
1195 Init *mhs = MHS->resolveReferences(R, RV);
1196 return (TernOpInit::get(getOpcode(), lhs, mhs,
1197 RHS, getType()))->Fold(&R, nullptr);
1199 Init *rhs = RHS->resolveReferences(R, RV);
1200 return (TernOpInit::get(getOpcode(), lhs, MHS,
1201 rhs, getType()))->Fold(&R, nullptr);
1206 Init *mhs = MHS->resolveReferences(R, RV);
1207 Init *rhs = RHS->resolveReferences(R, RV);
1209 if (LHS != lhs || MHS != mhs || RHS != rhs)
1210 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1211 getType()))->Fold(&R, nullptr);
1212 return Fold(&R, nullptr);
1215 std::string TernOpInit::getAsString() const {
1218 case SUBST: Result = "!subst"; break;
1219 case FOREACH: Result = "!foreach"; break;
1220 case IF: Result = "!if"; break;
1222 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1223 + RHS->getAsString() + ")";
1226 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1227 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1228 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1229 return Field->getType();
1234 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1235 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1236 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1237 unsigned NumBits = T->getNumBits();
1239 SmallVector<Init *, 16> NewBits(Bits.size());
1240 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1241 if (Bits[i] >= NumBits)
1244 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1246 return BitsInit::get(NewBits);
1250 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1251 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1252 if (!T) return nullptr; // Cannot subscript a non-list variable.
1254 if (Elements.size() == 1)
1255 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1257 std::vector<Init*> ListInits;
1258 ListInits.reserve(Elements.size());
1259 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1260 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1262 return ListInit::get(ListInits, T);
1266 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1267 Init *Value = StringInit::get(VN);
1268 return VarInit::get(Value, T);
1271 VarInit *VarInit::get(Init *VN, RecTy *T) {
1272 typedef std::pair<RecTy *, Init *> Key;
1273 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1275 Key TheKey(std::make_pair(T, VN));
1277 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1278 if (!I) I.reset(new VarInit(VN, T));
1282 const std::string &VarInit::getName() const {
1283 StringInit *NameString = cast<StringInit>(getNameInit());
1284 return NameString->getValue();
1287 Init *VarInit::getBit(unsigned Bit) const {
1288 if (getType() == BitRecTy::get())
1289 return const_cast<VarInit*>(this);
1290 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1293 Init *VarInit::resolveListElementReference(Record &R,
1294 const RecordVal *IRV,
1295 unsigned Elt) const {
1296 if (R.isTemplateArg(getNameInit())) return nullptr;
1297 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1299 RecordVal *RV = R.getValue(getNameInit());
1300 assert(RV && "Reference to a non-existent variable?");
1301 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1303 TypedInit *VI = cast<TypedInit>(RV->getValue());
1304 return VarListElementInit::get(VI, Elt);
1307 if (Elt >= LI->getSize())
1308 return nullptr; // Out of range reference.
1309 Init *E = LI->getElement(Elt);
1310 // If the element is set to some value, or if we are resolving a reference
1311 // to a specific variable and that variable is explicitly unset, then
1312 // replace the VarListElementInit with it.
1313 if (IRV || !isa<UnsetInit>(E))
1319 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1320 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1321 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1322 return RV->getType();
1326 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1327 const std::string &FieldName) const {
1328 if (isa<RecordRecTy>(getType()))
1329 if (const RecordVal *Val = R.getValue(VarName)) {
1330 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1332 Init *TheInit = Val->getValue();
1333 assert(TheInit != this && "Infinite loop detected!");
1334 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1342 /// resolveReferences - This method is used by classes that refer to other
1343 /// variables which may not be defined at the time the expression is formed.
1344 /// If a value is set for the variable later, this method will be called on
1345 /// users of the value to allow the value to propagate out.
1347 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1348 if (RecordVal *Val = R.getValue(VarName))
1349 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1350 return Val->getValue();
1351 return const_cast<VarInit *>(this);
1354 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1355 typedef std::pair<TypedInit *, unsigned> Key;
1356 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1358 Key TheKey(std::make_pair(T, B));
1360 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1361 if (!I) I.reset(new VarBitInit(T, B));
1365 std::string VarBitInit::getAsString() const {
1366 return TI->getAsString() + "{" + utostr(Bit) + "}";
1369 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1370 Init *I = TI->resolveReferences(R, RV);
1372 return I->getBit(getBitNum());
1374 return const_cast<VarBitInit*>(this);
1377 VarListElementInit *VarListElementInit::get(TypedInit *T,
1379 typedef std::pair<TypedInit *, unsigned> Key;
1380 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1382 Key TheKey(std::make_pair(T, E));
1384 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1385 if (!I) I.reset(new VarListElementInit(T, E));
1389 std::string VarListElementInit::getAsString() const {
1390 return TI->getAsString() + "[" + utostr(Element) + "]";
1394 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1398 return const_cast<VarListElementInit *>(this);
1401 Init *VarListElementInit::getBit(unsigned Bit) const {
1402 if (getType() == BitRecTy::get())
1403 return const_cast<VarListElementInit*>(this);
1404 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1407 Init *VarListElementInit:: resolveListElementReference(Record &R,
1408 const RecordVal *RV,
1409 unsigned Elt) const {
1410 Init *Result = TI->resolveListElementReference(R, RV, Element);
1413 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1414 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1415 if (Result2) return Result2;
1416 return VarListElementInit::get(TInit, Elt);
1424 DefInit *DefInit::get(Record *R) {
1425 return R->getDefInit();
1428 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1429 if (const RecordVal *RV = Def->getValue(FieldName))
1430 return RV->getType();
1434 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1435 const std::string &FieldName) const {
1436 return Def->getValue(FieldName)->getValue();
1440 std::string DefInit::getAsString() const {
1441 return Def->getName();
1444 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1445 typedef std::pair<Init *, TableGenStringKey> Key;
1446 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1448 Key TheKey(std::make_pair(R, FN));
1450 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1451 if (!I) I.reset(new FieldInit(R, FN));
1455 Init *FieldInit::getBit(unsigned Bit) const {
1456 if (getType() == BitRecTy::get())
1457 return const_cast<FieldInit*>(this);
1458 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1461 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1462 unsigned Elt) const {
1463 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1464 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1465 if (Elt >= LI->getSize()) return nullptr;
1466 Init *E = LI->getElement(Elt);
1468 // If the element is set to some value, or if we are resolving a
1469 // reference to a specific variable and that variable is explicitly
1470 // unset, then replace the VarListElementInit with it.
1471 if (RV || !isa<UnsetInit>(E))
1477 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1478 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1480 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1482 Init *BVR = BitsVal->resolveReferences(R, RV);
1483 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1486 if (NewRec != Rec) {
1487 return FieldInit::get(NewRec, FieldName);
1489 return const_cast<FieldInit *>(this);
1492 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1493 ArrayRef<Init *> ArgRange,
1494 ArrayRef<std::string> NameRange) {
1498 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1499 ArrayRef<std::string>::iterator Name = NameRange.begin();
1500 while (Arg != ArgRange.end()) {
1501 assert(Name != NameRange.end() && "Arg name underflow!");
1502 ID.AddPointer(*Arg++);
1503 ID.AddString(*Name++);
1505 assert(Name == NameRange.end() && "Arg name overflow!");
1509 DagInit::get(Init *V, const std::string &VN,
1510 ArrayRef<Init *> ArgRange,
1511 ArrayRef<std::string> NameRange) {
1512 static FoldingSet<DagInit> ThePool;
1513 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1515 FoldingSetNodeID ID;
1516 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1519 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1522 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1523 ThePool.InsertNode(I, IP);
1524 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1529 DagInit::get(Init *V, const std::string &VN,
1530 const std::vector<std::pair<Init*, std::string> > &args) {
1531 std::vector<Init *> Args;
1532 std::vector<std::string> Names;
1534 for (const auto &Arg : args) {
1535 Args.push_back(Arg.first);
1536 Names.push_back(Arg.second);
1539 return DagInit::get(V, VN, Args, Names);
1542 void DagInit::Profile(FoldingSetNodeID &ID) const {
1543 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1546 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1547 std::vector<Init*> NewArgs;
1548 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1549 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1551 Init *Op = Val->resolveReferences(R, RV);
1553 if (Args != NewArgs || Op != Val)
1554 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1556 return const_cast<DagInit *>(this);
1560 std::string DagInit::getAsString() const {
1561 std::string Result = "(" + Val->getAsString();
1562 if (!ValName.empty())
1563 Result += ":" + ValName;
1564 if (!Args.empty()) {
1565 Result += " " + Args[0]->getAsString();
1566 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1567 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1568 Result += ", " + Args[i]->getAsString();
1569 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1572 return Result + ")";
1576 //===----------------------------------------------------------------------===//
1577 // Other implementations
1578 //===----------------------------------------------------------------------===//
1580 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1581 : Name(N), Ty(T), Prefix(P) {
1582 Value = Ty->convertValue(UnsetInit::get());
1583 assert(Value && "Cannot create unset value for current type!");
1586 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1587 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1588 Value = Ty->convertValue(UnsetInit::get());
1589 assert(Value && "Cannot create unset value for current type!");
1592 const std::string &RecordVal::getName() const {
1593 return cast<StringInit>(Name)->getValue();
1596 void RecordVal::dump() const { errs() << *this; }
1598 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1599 if (getPrefix()) OS << "field ";
1600 OS << *getType() << " " << getNameInitAsString();
1603 OS << " = " << *getValue();
1605 if (PrintSem) OS << ";\n";
1608 unsigned Record::LastID = 0;
1610 void Record::init() {
1613 // Every record potentially has a def at the top. This value is
1614 // replaced with the top-level def name at instantiation time.
1615 RecordVal DN("NAME", StringRecTy::get(), 0);
1619 void Record::checkName() {
1620 // Ensure the record name has string type.
1621 const TypedInit *TypedName = cast<const TypedInit>(Name);
1622 RecTy *Type = TypedName->getType();
1623 if (!isa<StringRecTy>(Type))
1624 PrintFatalError(getLoc(), "Record name is not a string!");
1627 DefInit *Record::getDefInit() {
1628 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1632 std::unique_ptr<DefInit> &I = ThePool[this];
1633 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1637 const std::string &Record::getName() const {
1638 return cast<StringInit>(Name)->getValue();
1641 void Record::setName(Init *NewName) {
1644 // DO NOT resolve record values to the name at this point because
1645 // there might be default values for arguments of this def. Those
1646 // arguments might not have been resolved yet so we don't want to
1647 // prematurely assume values for those arguments were not passed to
1650 // Nonetheless, it may be that some of this Record's values
1651 // reference the record name. Indeed, the reason for having the
1652 // record name be an Init is to provide this flexibility. The extra
1653 // resolve steps after completely instantiating defs takes care of
1654 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1657 void Record::setName(const std::string &Name) {
1658 setName(StringInit::get(Name));
1661 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1662 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1664 void Record::resolveReferencesTo(const RecordVal *RV) {
1665 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1666 if (RV == &Values[i]) // Skip resolve the same field as the given one
1668 if (Init *V = Values[i].getValue())
1669 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1670 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1671 + Values[i].getNameInitAsString()
1672 + "' after resolving references"
1673 + (RV ? " against '" + RV->getNameInitAsString()
1675 + RV->getValue()->getAsUnquotedString() + ")"
1679 Init *OldName = getNameInit();
1680 Init *NewName = Name->resolveReferences(*this, RV);
1681 if (NewName != OldName) {
1682 // Re-register with RecordKeeper.
1687 void Record::dump() const { errs() << *this; }
1689 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1690 OS << R.getNameInitAsString();
1692 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1693 if (!TArgs.empty()) {
1695 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1697 const RecordVal *RV = R.getValue(TArgs[i]);
1698 assert(RV && "Template argument record not found??");
1699 RV->print(OS, false);
1705 const std::vector<Record*> &SC = R.getSuperClasses();
1708 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1709 OS << " " << SC[i]->getNameInitAsString();
1713 const std::vector<RecordVal> &Vals = R.getValues();
1714 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1715 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1717 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1718 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1724 /// getValueInit - Return the initializer for a value with the specified name,
1725 /// or abort if the field does not exist.
1727 Init *Record::getValueInit(StringRef FieldName) const {
1728 const RecordVal *R = getValue(FieldName);
1729 if (!R || !R->getValue())
1730 PrintFatalError(getLoc(), "Record `" + getName() +
1731 "' does not have a field named `" + FieldName + "'!\n");
1732 return R->getValue();
1736 /// getValueAsString - This method looks up the specified field and returns its
1737 /// value as a string, aborts if the field does not exist or if
1738 /// the value is not a string.
1740 std::string Record::getValueAsString(StringRef FieldName) const {
1741 const RecordVal *R = getValue(FieldName);
1742 if (!R || !R->getValue())
1743 PrintFatalError(getLoc(), "Record `" + getName() +
1744 "' does not have a field named `" + FieldName + "'!\n");
1746 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1747 return SI->getValue();
1748 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1749 FieldName + "' does not have a string initializer!");
1752 /// getValueAsBitsInit - This method looks up the specified field and returns
1753 /// its value as a BitsInit, aborts if the field does not exist or if
1754 /// the value is not the right type.
1756 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1757 const RecordVal *R = getValue(FieldName);
1758 if (!R || !R->getValue())
1759 PrintFatalError(getLoc(), "Record `" + getName() +
1760 "' does not have a field named `" + FieldName + "'!\n");
1762 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1764 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1765 FieldName + "' does not have a BitsInit initializer!");
1768 /// getValueAsListInit - This method looks up the specified field and returns
1769 /// its value as a ListInit, aborting if the field does not exist or if
1770 /// the value is not the right type.
1772 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1773 const RecordVal *R = getValue(FieldName);
1774 if (!R || !R->getValue())
1775 PrintFatalError(getLoc(), "Record `" + getName() +
1776 "' does not have a field named `" + FieldName + "'!\n");
1778 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1780 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1781 FieldName + "' does not have a list initializer!");
1784 /// getValueAsListOfDefs - This method looks up the specified field and returns
1785 /// its value as a vector of records, aborting if the field does not exist
1786 /// or if the value is not the right type.
1788 std::vector<Record*>
1789 Record::getValueAsListOfDefs(StringRef FieldName) const {
1790 ListInit *List = getValueAsListInit(FieldName);
1791 std::vector<Record*> Defs;
1792 for (unsigned i = 0; i < List->getSize(); i++) {
1793 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1794 Defs.push_back(DI->getDef());
1796 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1797 FieldName + "' list is not entirely DefInit!");
1803 /// getValueAsInt - This method looks up the specified field and returns its
1804 /// value as an int64_t, aborting if the field does not exist or if the value
1805 /// is not the right type.
1807 int64_t Record::getValueAsInt(StringRef FieldName) const {
1808 const RecordVal *R = getValue(FieldName);
1809 if (!R || !R->getValue())
1810 PrintFatalError(getLoc(), "Record `" + getName() +
1811 "' does not have a field named `" + FieldName + "'!\n");
1813 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1814 return II->getValue();
1815 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1816 FieldName + "' does not have an int initializer!");
1819 /// getValueAsListOfInts - This method looks up the specified field and returns
1820 /// its value as a vector of integers, aborting if the field does not exist or
1821 /// if the value is not the right type.
1823 std::vector<int64_t>
1824 Record::getValueAsListOfInts(StringRef FieldName) const {
1825 ListInit *List = getValueAsListInit(FieldName);
1826 std::vector<int64_t> Ints;
1827 for (unsigned i = 0; i < List->getSize(); i++) {
1828 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1829 Ints.push_back(II->getValue());
1831 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1832 FieldName + "' does not have a list of ints initializer!");
1838 /// getValueAsListOfStrings - This method looks up the specified field and
1839 /// returns its value as a vector of strings, aborting if the field does not
1840 /// exist or if the value is not the right type.
1842 std::vector<std::string>
1843 Record::getValueAsListOfStrings(StringRef FieldName) const {
1844 ListInit *List = getValueAsListInit(FieldName);
1845 std::vector<std::string> Strings;
1846 for (unsigned i = 0; i < List->getSize(); i++) {
1847 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1848 Strings.push_back(II->getValue());
1850 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1851 FieldName + "' does not have a list of strings initializer!");
1857 /// getValueAsDef - This method looks up the specified field and returns its
1858 /// value as a Record, aborting if the field does not exist or if the value
1859 /// is not the right type.
1861 Record *Record::getValueAsDef(StringRef FieldName) const {
1862 const RecordVal *R = getValue(FieldName);
1863 if (!R || !R->getValue())
1864 PrintFatalError(getLoc(), "Record `" + getName() +
1865 "' does not have a field named `" + FieldName + "'!\n");
1867 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1868 return DI->getDef();
1869 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1870 FieldName + "' does not have a def initializer!");
1873 /// getValueAsBit - This method looks up the specified field and returns its
1874 /// value as a bit, aborting if the field does not exist or if the value is
1875 /// not the right type.
1877 bool Record::getValueAsBit(StringRef FieldName) const {
1878 const RecordVal *R = getValue(FieldName);
1879 if (!R || !R->getValue())
1880 PrintFatalError(getLoc(), "Record `" + getName() +
1881 "' does not have a field named `" + FieldName + "'!\n");
1883 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1884 return BI->getValue();
1885 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1886 FieldName + "' does not have a bit initializer!");
1889 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1890 const RecordVal *R = getValue(FieldName);
1891 if (!R || !R->getValue())
1892 PrintFatalError(getLoc(), "Record `" + getName() +
1893 "' does not have a field named `" + FieldName.str() + "'!\n");
1895 if (isa<UnsetInit>(R->getValue())) {
1900 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1901 return BI->getValue();
1902 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1903 FieldName + "' does not have a bit initializer!");
1906 /// getValueAsDag - This method looks up the specified field and returns its
1907 /// value as an Dag, aborting if the field does not exist or if the value is
1908 /// not the right type.
1910 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1911 const RecordVal *R = getValue(FieldName);
1912 if (!R || !R->getValue())
1913 PrintFatalError(getLoc(), "Record `" + getName() +
1914 "' does not have a field named `" + FieldName + "'!\n");
1916 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1918 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1919 FieldName + "' does not have a dag initializer!");
1923 void MultiClass::dump() const {
1924 errs() << "Record:\n";
1927 errs() << "Defs:\n";
1928 for (const auto &Proto : DefPrototypes) {
1934 void RecordKeeper::dump() const { errs() << *this; }
1936 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1937 OS << "------------- Classes -----------------\n";
1938 const auto &Classes = RK.getClasses();
1939 for (const auto &C : Classes)
1940 OS << "class " << *C.second;
1942 OS << "------------- Defs -----------------\n";
1943 const auto &Defs = RK.getDefs();
1944 for (const auto &D : Defs)
1945 OS << "def " << *D.second;
1950 /// getAllDerivedDefinitions - This method returns all concrete definitions
1951 /// that derive from the specified class name. If a class with the specified
1952 /// name does not exist, an error is printed and true is returned.
1953 std::vector<Record*>
1954 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1955 Record *Class = getClass(ClassName);
1957 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1959 std::vector<Record*> Defs;
1960 for (const auto &D : getDefs())
1961 if (D.second->isSubClassOf(Class))
1962 Defs.push_back(D.second.get());
1967 /// QualifyName - Return an Init with a qualifier prefix referring
1968 /// to CurRec's name.
1969 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1970 Init *Name, const std::string &Scoper) {
1971 RecTy *Type = cast<TypedInit>(Name)->getType();
1973 BinOpInit *NewName =
1974 BinOpInit::get(BinOpInit::STRCONCAT,
1975 BinOpInit::get(BinOpInit::STRCONCAT,
1976 CurRec.getNameInit(),
1977 StringInit::get(Scoper),
1978 Type)->Fold(&CurRec, CurMultiClass),
1982 if (CurMultiClass && Scoper != "::") {
1984 BinOpInit::get(BinOpInit::STRCONCAT,
1985 BinOpInit::get(BinOpInit::STRCONCAT,
1986 CurMultiClass->Rec.getNameInit(),
1987 StringInit::get("::"),
1988 Type)->Fold(&CurRec, CurMultiClass),
1989 NewName->Fold(&CurRec, CurMultiClass),
1993 return NewName->Fold(&CurRec, CurMultiClass);
1996 /// QualifyName - Return an Init with a qualifier prefix referring
1997 /// to CurRec's name.
1998 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1999 const std::string &Name,
2000 const std::string &Scoper) {
2001 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);