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/TableGen/Error.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/Hashing.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.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 Init *BitRecTy::convertValue(BitsInit *BI) {
99 if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
100 return BI->getBit(0);
103 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
104 return RHS->getNumBits() == 1;
107 Init *BitRecTy::convertValue(IntInit *II) {
108 int64_t Val = II->getValue();
109 if (Val != 0 && Val != 1) return 0; // Only accept 0 or 1 for a bit!
111 return BitInit::get(Val != 0);
114 Init *BitRecTy::convertValue(TypedInit *VI) {
115 RecTy *Ty = VI->getType();
116 if (isa<BitRecTy>(Ty) || isa<BitsRecTy>(Ty) || isa<IntRecTy>(Ty))
117 return VI; // Accept variable if it is already of bit type!
121 BitsRecTy *BitsRecTy::get(unsigned Sz) {
122 static std::vector<BitsRecTy*> Shared;
123 if (Sz >= Shared.size())
124 Shared.resize(Sz + 1);
125 BitsRecTy *&Ty = Shared[Sz];
127 Ty = new BitsRecTy(Sz);
131 std::string BitsRecTy::getAsString() const {
132 return "bits<" + utostr(Size) + ">";
135 Init *BitsRecTy::convertValue(UnsetInit *UI) {
136 SmallVector<Init *, 16> NewBits(Size);
138 for (unsigned i = 0; i != Size; ++i)
139 NewBits[i] = UnsetInit::get();
141 return BitsInit::get(NewBits);
144 Init *BitsRecTy::convertValue(BitInit *UI) {
145 if (Size != 1) return 0; // Can only convert single bit.
146 return BitsInit::get(UI);
149 /// canFitInBitfield - Return true if the number of bits is large enough to hold
150 /// the integer value.
151 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
152 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
153 return (NumBits >= sizeof(Value) * 8) ||
154 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
157 /// convertValue from Int initializer to bits type: Split the integer up into the
158 /// appropriate bits.
160 Init *BitsRecTy::convertValue(IntInit *II) {
161 int64_t Value = II->getValue();
162 // Make sure this bitfield is large enough to hold the integer value.
163 if (!canFitInBitfield(Value, Size))
166 SmallVector<Init *, 16> NewBits(Size);
168 for (unsigned i = 0; i != Size; ++i)
169 NewBits[i] = BitInit::get(Value & (1LL << i));
171 return BitsInit::get(NewBits);
174 Init *BitsRecTy::convertValue(BitsInit *BI) {
175 // If the number of bits is right, return it. Otherwise we need to expand or
177 if (BI->getNumBits() == Size) return BI;
181 Init *BitsRecTy::convertValue(TypedInit *VI) {
182 if (Size == 1 && isa<BitRecTy>(VI->getType()))
183 return BitsInit::get(VI);
185 if (VI->getType()->typeIsConvertibleTo(this)) {
186 SmallVector<Init *, 16> NewBits(Size);
188 for (unsigned i = 0; i != Size; ++i)
189 NewBits[i] = VarBitInit::get(VI, i);
190 return BitsInit::get(NewBits);
196 Init *IntRecTy::convertValue(BitInit *BI) {
197 return IntInit::get(BI->getValue());
200 Init *IntRecTy::convertValue(BitsInit *BI) {
202 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
203 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
204 Result |= Bit->getValue() << i;
208 return IntInit::get(Result);
211 Init *IntRecTy::convertValue(TypedInit *TI) {
212 if (TI->getType()->typeIsConvertibleTo(this))
213 return TI; // Accept variable if already of the right type!
217 Init *StringRecTy::convertValue(UnOpInit *BO) {
218 if (BO->getOpcode() == UnOpInit::CAST) {
219 Init *L = BO->getOperand()->convertInitializerTo(this);
220 if (L == 0) return 0;
221 if (L != BO->getOperand())
222 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
226 return convertValue((TypedInit*)BO);
229 Init *StringRecTy::convertValue(BinOpInit *BO) {
230 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
231 Init *L = BO->getLHS()->convertInitializerTo(this);
232 Init *R = BO->getRHS()->convertInitializerTo(this);
233 if (L == 0 || R == 0) return 0;
234 if (L != BO->getLHS() || R != BO->getRHS())
235 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
239 return convertValue((TypedInit*)BO);
243 Init *StringRecTy::convertValue(TypedInit *TI) {
244 if (isa<StringRecTy>(TI->getType()))
245 return TI; // Accept variable if already of the right type!
249 std::string ListRecTy::getAsString() const {
250 return "list<" + Ty->getAsString() + ">";
253 Init *ListRecTy::convertValue(ListInit *LI) {
254 std::vector<Init*> Elements;
256 // Verify that all of the elements of the list are subclasses of the
257 // appropriate class!
258 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
259 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
260 Elements.push_back(CI);
264 if (!isa<ListRecTy>(LI->getType()))
267 return ListInit::get(Elements, this);
270 Init *ListRecTy::convertValue(TypedInit *TI) {
271 // Ensure that TI is compatible with our class.
272 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
273 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
278 Init *DagRecTy::convertValue(TypedInit *TI) {
279 if (TI->getType()->typeIsConvertibleTo(this))
284 Init *DagRecTy::convertValue(UnOpInit *BO) {
285 if (BO->getOpcode() == UnOpInit::CAST) {
286 Init *L = BO->getOperand()->convertInitializerTo(this);
287 if (L == 0) return 0;
288 if (L != BO->getOperand())
289 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
295 Init *DagRecTy::convertValue(BinOpInit *BO) {
296 if (BO->getOpcode() == BinOpInit::CONCAT) {
297 Init *L = BO->getLHS()->convertInitializerTo(this);
298 Init *R = BO->getRHS()->convertInitializerTo(this);
299 if (L == 0 || R == 0) return 0;
300 if (L != BO->getLHS() || R != BO->getRHS())
301 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
307 RecordRecTy *RecordRecTy::get(Record *R) {
308 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
311 std::string RecordRecTy::getAsString() const {
312 return Rec->getName();
315 Init *RecordRecTy::convertValue(DefInit *DI) {
316 // Ensure that DI is a subclass of Rec.
317 if (!DI->getDef()->isSubClassOf(Rec))
322 Init *RecordRecTy::convertValue(TypedInit *TI) {
323 // Ensure that TI is compatible with Rec.
324 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
325 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
326 RRT->getRecord() == getRecord())
331 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
332 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
335 const std::vector<Record*> &SC = Rec->getSuperClasses();
336 for (unsigned i = 0, e = SC.size(); i != e; ++i)
337 if (RHS->getRecord()->isSubClassOf(SC[i]))
343 /// resolveTypes - Find a common type that T1 and T2 convert to.
344 /// Return 0 if no such type exists.
346 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
347 if (T1->typeIsConvertibleTo(T2))
349 if (T2->typeIsConvertibleTo(T1))
352 // If one is a Record type, check superclasses
353 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
354 // See if T2 inherits from a type T1 also inherits from
355 const std::vector<Record *> &T1SuperClasses =
356 RecTy1->getRecord()->getSuperClasses();
357 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
358 iend = T1SuperClasses.end();
361 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
362 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
364 if (NewType1 != SuperRecTy1) {
371 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
372 // See if T1 inherits from a type T2 also inherits from
373 const std::vector<Record *> &T2SuperClasses =
374 RecTy2->getRecord()->getSuperClasses();
375 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
376 iend = T2SuperClasses.end();
379 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
380 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
382 if (NewType2 != SuperRecTy2) {
393 //===----------------------------------------------------------------------===//
394 // Initializer implementations
395 //===----------------------------------------------------------------------===//
397 void Init::anchor() { }
398 void Init::dump() const { return print(errs()); }
400 void UnsetInit::anchor() { }
402 UnsetInit *UnsetInit::get() {
403 static UnsetInit TheInit;
407 void BitInit::anchor() { }
409 BitInit *BitInit::get(bool V) {
410 static BitInit True(true);
411 static BitInit False(false);
413 return V ? &True : &False;
417 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
418 ID.AddInteger(Range.size());
420 for (ArrayRef<Init *>::iterator i = Range.begin(),
427 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
428 typedef FoldingSet<BitsInit> Pool;
432 ProfileBitsInit(ID, Range);
435 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
438 BitsInit *I = new BitsInit(Range);
439 ThePool.InsertNode(I, IP);
444 void BitsInit::Profile(FoldingSetNodeID &ID) const {
445 ProfileBitsInit(ID, Bits);
449 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
450 SmallVector<Init *, 16> NewBits(Bits.size());
452 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
453 if (Bits[i] >= getNumBits())
455 NewBits[i] = getBit(Bits[i]);
457 return BitsInit::get(NewBits);
460 std::string BitsInit::getAsString() const {
461 std::string Result = "{ ";
462 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
463 if (i) Result += ", ";
464 if (Init *Bit = getBit(e-i-1))
465 Result += Bit->getAsString();
469 return Result + " }";
472 // Fix bit initializer to preserve the behavior that bit reference from a unset
473 // bits initializer will resolve into VarBitInit to keep the field name and bit
474 // number used in targets with fixed insn length.
475 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
476 if (RV || After != UnsetInit::get())
481 // resolveReferences - If there are any field references that refer to fields
482 // that have been filled in, we can propagate the values now.
484 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
485 bool Changed = false;
486 SmallVector<Init *, 16> NewBits(getNumBits());
488 Init *CachedInit = 0;
489 Init *CachedBitVar = 0;
490 bool CachedBitVarChanged = false;
492 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
493 Init *CurBit = Bits[i];
494 Init *CurBitVar = CurBit->getBitVar();
498 if (CurBitVar == CachedBitVar) {
499 if (CachedBitVarChanged) {
500 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
501 NewBits[i] = fixBitInit(RV, CurBit, Bit);
505 CachedBitVar = CurBitVar;
506 CachedBitVarChanged = false;
511 CurBitVar = CurBitVar->resolveReferences(R, RV);
512 CachedBitVarChanged |= B != CurBitVar;
513 Changed |= B != CurBitVar;
514 } while (B != CurBitVar);
515 CachedInit = CurBitVar;
517 if (CachedBitVarChanged) {
518 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
519 NewBits[i] = fixBitInit(RV, CurBit, Bit);
524 return BitsInit::get(NewBits);
526 return const_cast<BitsInit *>(this);
529 IntInit *IntInit::get(int64_t V) {
530 typedef DenseMap<int64_t, IntInit *> Pool;
533 IntInit *&I = ThePool[V];
534 if (!I) I = new IntInit(V);
538 std::string IntInit::getAsString() const {
539 return itostr(Value);
543 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
544 SmallVector<Init *, 16> NewBits(Bits.size());
546 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
550 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
552 return BitsInit::get(NewBits);
555 void StringInit::anchor() { }
557 StringInit *StringInit::get(StringRef V) {
558 typedef StringMap<StringInit *> Pool;
561 StringInit *&I = ThePool[V];
562 if (!I) I = new StringInit(V);
566 static void ProfileListInit(FoldingSetNodeID &ID,
567 ArrayRef<Init *> Range,
569 ID.AddInteger(Range.size());
570 ID.AddPointer(EltTy);
572 for (ArrayRef<Init *>::iterator i = Range.begin(),
579 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
580 typedef FoldingSet<ListInit> Pool;
583 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
584 // for actual storage.
586 ProfileListInit(ID, Range, EltTy);
589 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
592 ListInit *I = new ListInit(Range, EltTy);
593 ThePool.InsertNode(I, IP);
597 void ListInit::Profile(FoldingSetNodeID &ID) const {
598 ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
599 assert(ListType && "Bad type for ListInit!");
600 RecTy *EltTy = ListType->getElementType();
602 ProfileListInit(ID, Values, EltTy);
606 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
607 std::vector<Init*> Vals;
608 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
609 if (Elements[i] >= getSize())
611 Vals.push_back(getElement(Elements[i]));
613 return ListInit::get(Vals, getType());
616 Record *ListInit::getElementAsRecord(unsigned i) const {
617 assert(i < Values.size() && "List element index out of range!");
618 DefInit *DI = dyn_cast<DefInit>(Values[i]);
619 if (DI == 0) throw "Expected record in list!";
623 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
624 std::vector<Init*> Resolved;
625 Resolved.reserve(getSize());
626 bool Changed = false;
628 for (unsigned i = 0, e = getSize(); i != e; ++i) {
630 Init *CurElt = getElement(i);
634 CurElt = CurElt->resolveReferences(R, RV);
635 Changed |= E != CurElt;
636 } while (E != CurElt);
637 Resolved.push_back(E);
641 return ListInit::get(Resolved, getType());
642 return const_cast<ListInit *>(this);
645 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
646 unsigned Elt) const {
647 if (Elt >= getSize())
648 return 0; // Out of range reference.
649 Init *E = getElement(Elt);
650 // If the element is set to some value, or if we are resolving a reference
651 // to a specific variable and that variable is explicitly unset, then
652 // replace the VarListElementInit with it.
653 if (IRV || !dyn_cast<UnsetInit>(E))
658 std::string ListInit::getAsString() const {
659 std::string Result = "[";
660 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
661 if (i) Result += ", ";
662 Result += Values[i]->getAsString();
667 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
668 unsigned Elt) const {
669 Init *Resolved = resolveReferences(R, IRV);
670 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
672 Resolved = OResolved->Fold(&R, 0);
675 if (Resolved != this) {
676 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
677 assert(Typed && "Expected typed init for list reference");
679 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
682 return VarListElementInit::get(Typed, Elt);
689 Init *OpInit::getBit(unsigned Bit) const {
690 if (getType() == BitRecTy::get())
691 return const_cast<OpInit*>(this);
692 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
695 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
696 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
698 typedef DenseMap<Key, UnOpInit *> Pool;
701 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
703 UnOpInit *&I = ThePool[TheKey];
704 if (!I) I = new UnOpInit(opc, lhs, Type);
708 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
709 switch (getOpcode()) {
711 if (getType()->getAsString() == "string") {
712 StringInit *LHSs = dyn_cast<StringInit>(LHS);
717 DefInit *LHSd = dyn_cast<DefInit>(LHS);
719 return StringInit::get(LHSd->getDef()->getName());
722 IntInit *LHSi = dyn_cast<IntInit>(LHS);
724 return StringInit::get(LHSi->getAsString());
727 StringInit *LHSs = dyn_cast<StringInit>(LHS);
729 std::string Name = LHSs->getValue();
731 // From TGParser::ParseIDValue
733 if (const RecordVal *RV = CurRec->getValue(Name)) {
734 if (RV->getType() != getType())
735 throw "type mismatch in cast";
736 return VarInit::get(Name, RV->getType());
739 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
742 if (CurRec->isTemplateArg(TemplateArgName)) {
743 const RecordVal *RV = CurRec->getValue(TemplateArgName);
744 assert(RV && "Template arg doesn't exist??");
746 if (RV->getType() != getType())
747 throw "type mismatch in cast";
749 return VarInit::get(TemplateArgName, RV->getType());
754 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
756 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
757 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
758 assert(RV && "Template arg doesn't exist??");
760 if (RV->getType() != getType())
761 throw "type mismatch in cast";
763 return VarInit::get(MCName, RV->getType());
767 if (Record *D = (CurRec->getRecords()).getDef(Name))
768 return DefInit::get(D);
770 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
776 ListInit *LHSl = dyn_cast<ListInit>(LHS);
778 if (LHSl->getSize() == 0) {
779 assert(0 && "Empty list in car");
782 return LHSl->getElement(0);
787 ListInit *LHSl = dyn_cast<ListInit>(LHS);
789 if (LHSl->getSize() == 0) {
790 assert(0 && "Empty list in cdr");
793 // Note the +1. We can't just pass the result of getValues()
795 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
796 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
798 ListInit::get(ArrayRef<Init *>(begin, end - begin),
805 ListInit *LHSl = dyn_cast<ListInit>(LHS);
807 if (LHSl->getSize() == 0) {
808 return IntInit::get(1);
810 return IntInit::get(0);
813 StringInit *LHSs = dyn_cast<StringInit>(LHS);
815 if (LHSs->getValue().empty()) {
816 return IntInit::get(1);
818 return IntInit::get(0);
825 return const_cast<UnOpInit *>(this);
828 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
829 Init *lhs = LHS->resolveReferences(R, RV);
832 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
836 std::string UnOpInit::getAsString() const {
839 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
840 case HEAD: Result = "!head"; break;
841 case TAIL: Result = "!tail"; break;
842 case EMPTY: Result = "!empty"; break;
844 return Result + "(" + LHS->getAsString() + ")";
847 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
848 Init *rhs, RecTy *Type) {
850 std::pair<std::pair<unsigned, Init *>, Init *>,
854 typedef DenseMap<Key, BinOpInit *> Pool;
857 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
860 BinOpInit *&I = ThePool[TheKey];
861 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
865 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
866 switch (getOpcode()) {
868 DagInit *LHSs = dyn_cast<DagInit>(LHS);
869 DagInit *RHSs = dyn_cast<DagInit>(RHS);
871 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
872 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
873 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
874 throw "Concated Dag operators do not match!";
875 std::vector<Init*> Args;
876 std::vector<std::string> ArgNames;
877 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
878 Args.push_back(LHSs->getArg(i));
879 ArgNames.push_back(LHSs->getArgName(i));
881 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
882 Args.push_back(RHSs->getArg(i));
883 ArgNames.push_back(RHSs->getArgName(i));
885 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
890 StringInit *LHSs = dyn_cast<StringInit>(LHS);
891 StringInit *RHSs = dyn_cast<StringInit>(RHS);
893 return StringInit::get(LHSs->getValue() + RHSs->getValue());
897 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
898 // to string objects.
900 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
902 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
905 return IntInit::get(L->getValue() == R->getValue());
907 StringInit *LHSs = dyn_cast<StringInit>(LHS);
908 StringInit *RHSs = dyn_cast<StringInit>(RHS);
910 // Make sure we've resolved
912 return IntInit::get(LHSs->getValue() == RHSs->getValue());
919 IntInit *LHSi = dyn_cast<IntInit>(LHS);
920 IntInit *RHSi = dyn_cast<IntInit>(RHS);
922 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
924 switch (getOpcode()) {
925 default: llvm_unreachable("Bad opcode!");
926 case SHL: Result = LHSv << RHSv; break;
927 case SRA: Result = LHSv >> RHSv; break;
928 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
930 return IntInit::get(Result);
935 return const_cast<BinOpInit *>(this);
938 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
939 Init *lhs = LHS->resolveReferences(R, RV);
940 Init *rhs = RHS->resolveReferences(R, RV);
942 if (LHS != lhs || RHS != rhs)
943 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
947 std::string BinOpInit::getAsString() const {
950 case CONCAT: Result = "!con"; break;
951 case SHL: Result = "!shl"; break;
952 case SRA: Result = "!sra"; break;
953 case SRL: Result = "!srl"; break;
954 case EQ: Result = "!eq"; break;
955 case STRCONCAT: Result = "!strconcat"; break;
957 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
960 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
961 Init *mhs, Init *rhs,
965 std::pair<std::pair<unsigned, RecTy *>, Init *>,
971 typedef DenseMap<Key, TernOpInit *> Pool;
974 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
980 TernOpInit *&I = ThePool[TheKey];
981 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
985 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
986 Record *CurRec, MultiClass *CurMultiClass);
988 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
989 RecTy *Type, Record *CurRec,
990 MultiClass *CurMultiClass) {
991 std::vector<Init *> NewOperands;
993 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
995 // If this is a dag, recurse
996 if (TArg && TArg->getType()->getAsString() == "dag") {
997 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
998 CurRec, CurMultiClass);
1006 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1007 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1010 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1011 Type, CurRec, CurMultiClass);
1013 NewOperands.push_back(Result);
1015 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 if (NewVal != NewOp)
1033 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1034 Record *CurRec, MultiClass *CurMultiClass) {
1035 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1036 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1038 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1041 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1044 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1047 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1050 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1052 Init *Val = MHSd->getOperator();
1053 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1054 Type, CurRec, CurMultiClass);
1059 std::vector<std::pair<Init *, std::string> > args;
1060 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1062 std::string ArgName;
1063 Arg = MHSd->getArg(i);
1064 ArgName = MHSd->getArgName(i);
1067 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1068 CurRec, CurMultiClass);
1073 // TODO: Process arg names
1074 args.push_back(std::make_pair(Arg, ArgName));
1077 return DagInit::get(Val, "", args);
1080 std::vector<Init *> NewOperands;
1081 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1083 for (std::vector<Init *>::iterator li = NewList.begin(),
1084 liend = NewList.end();
1088 NewOperands.clear();
1089 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1090 // First, replace the foreach variable with the list item
1091 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1092 NewOperands.push_back(Item);
1094 NewOperands.push_back(RHSo->getOperand(i));
1098 // Now run the operator and use its result as the new list item
1099 const OpInit *NewOp = RHSo->clone(NewOperands);
1100 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1101 if (NewItem != NewOp)
1104 return ListInit::get(NewList, MHSl->getType());
1110 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1111 switch (getOpcode()) {
1113 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1114 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1115 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1117 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1118 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1119 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1121 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1122 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1123 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1125 if ((LHSd && MHSd && RHSd)
1126 || (LHSv && MHSv && RHSv)
1127 || (LHSs && MHSs && RHSs)) {
1129 Record *Val = RHSd->getDef();
1130 if (LHSd->getAsString() == RHSd->getAsString()) {
1131 Val = MHSd->getDef();
1133 return DefInit::get(Val);
1136 std::string Val = RHSv->getName();
1137 if (LHSv->getAsString() == RHSv->getAsString()) {
1138 Val = MHSv->getName();
1140 return VarInit::get(Val, getType());
1143 std::string Val = RHSs->getValue();
1145 std::string::size_type found;
1146 std::string::size_type idx = 0;
1148 found = Val.find(LHSs->getValue(), idx);
1149 if (found != std::string::npos) {
1150 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1152 idx = found + MHSs->getValue().size();
1153 } while (found != std::string::npos);
1155 return StringInit::get(Val);
1162 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1163 CurRec, CurMultiClass);
1171 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1172 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1173 LHSi = dyn_cast<IntInit>(I);
1175 if (LHSi->getValue()) {
1185 return const_cast<TernOpInit *>(this);
1188 Init *TernOpInit::resolveReferences(Record &R,
1189 const RecordVal *RV) const {
1190 Init *lhs = LHS->resolveReferences(R, RV);
1192 if (Opc == IF && lhs != LHS) {
1193 IntInit *Value = dyn_cast<IntInit>(lhs);
1194 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1195 Value = dyn_cast<IntInit>(I);
1198 if (Value->getValue()) {
1199 Init *mhs = MHS->resolveReferences(R, RV);
1200 return (TernOpInit::get(getOpcode(), lhs, mhs,
1201 RHS, getType()))->Fold(&R, 0);
1203 Init *rhs = RHS->resolveReferences(R, RV);
1204 return (TernOpInit::get(getOpcode(), lhs, MHS,
1205 rhs, getType()))->Fold(&R, 0);
1210 Init *mhs = MHS->resolveReferences(R, RV);
1211 Init *rhs = RHS->resolveReferences(R, RV);
1213 if (LHS != lhs || MHS != mhs || RHS != rhs)
1214 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1215 getType()))->Fold(&R, 0);
1219 std::string TernOpInit::getAsString() const {
1222 case SUBST: Result = "!subst"; break;
1223 case FOREACH: Result = "!foreach"; break;
1224 case IF: Result = "!if"; break;
1226 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1227 + RHS->getAsString() + ")";
1230 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1231 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1232 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1233 return Field->getType();
1238 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1239 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1240 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1241 unsigned NumBits = T->getNumBits();
1243 SmallVector<Init *, 16> NewBits(Bits.size());
1244 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1245 if (Bits[i] >= NumBits)
1248 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1250 return BitsInit::get(NewBits);
1254 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1255 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1256 if (T == 0) return 0; // Cannot subscript a non-list variable.
1258 if (Elements.size() == 1)
1259 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1261 std::vector<Init*> ListInits;
1262 ListInits.reserve(Elements.size());
1263 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1264 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1266 return ListInit::get(ListInits, T);
1270 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1271 Init *Value = StringInit::get(VN);
1272 return VarInit::get(Value, T);
1275 VarInit *VarInit::get(Init *VN, RecTy *T) {
1276 typedef std::pair<RecTy *, Init *> Key;
1277 typedef DenseMap<Key, VarInit *> Pool;
1278 static Pool ThePool;
1280 Key TheKey(std::make_pair(T, VN));
1282 VarInit *&I = ThePool[TheKey];
1283 if (!I) I = new VarInit(VN, T);
1287 const std::string &VarInit::getName() const {
1288 StringInit *NameString =
1289 dyn_cast<StringInit>(getNameInit());
1290 assert(NameString && "VarInit name is not a string!");
1291 return NameString->getValue();
1294 Init *VarInit::getBit(unsigned Bit) const {
1295 if (getType() == BitRecTy::get())
1296 return const_cast<VarInit*>(this);
1297 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1300 Init *VarInit::resolveListElementReference(Record &R,
1301 const RecordVal *IRV,
1302 unsigned Elt) const {
1303 if (R.isTemplateArg(getNameInit())) return 0;
1304 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1306 RecordVal *RV = R.getValue(getNameInit());
1307 assert(RV && "Reference to a non-existent variable?");
1308 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1310 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1311 assert(VI && "Invalid list element!");
1312 return VarListElementInit::get(VI, Elt);
1315 if (Elt >= LI->getSize())
1316 return 0; // Out of range reference.
1317 Init *E = LI->getElement(Elt);
1318 // If the element is set to some value, or if we are resolving a reference
1319 // to a specific variable and that variable is explicitly unset, then
1320 // replace the VarListElementInit with it.
1321 if (IRV || !dyn_cast<UnsetInit>(E))
1327 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1328 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1329 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1330 return RV->getType();
1334 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1335 const std::string &FieldName) const {
1336 if (isa<RecordRecTy>(getType()))
1337 if (const RecordVal *Val = R.getValue(VarName)) {
1338 if (RV != Val && (RV || dyn_cast<UnsetInit>(Val->getValue())))
1340 Init *TheInit = Val->getValue();
1341 assert(TheInit != this && "Infinite loop detected!");
1342 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1350 /// resolveReferences - This method is used by classes that refer to other
1351 /// variables which may not be defined at the time the expression is formed.
1352 /// If a value is set for the variable later, this method will be called on
1353 /// users of the value to allow the value to propagate out.
1355 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1356 if (RecordVal *Val = R.getValue(VarName))
1357 if (RV == Val || (RV == 0 && !dyn_cast<UnsetInit>(Val->getValue())))
1358 return Val->getValue();
1359 return const_cast<VarInit *>(this);
1362 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1363 typedef std::pair<TypedInit *, unsigned> Key;
1364 typedef DenseMap<Key, VarBitInit *> Pool;
1366 static Pool ThePool;
1368 Key TheKey(std::make_pair(T, B));
1370 VarBitInit *&I = ThePool[TheKey];
1371 if (!I) I = new VarBitInit(T, B);
1375 std::string VarBitInit::getAsString() const {
1376 return TI->getAsString() + "{" + utostr(Bit) + "}";
1379 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1380 Init *I = TI->resolveReferences(R, RV);
1382 return I->getBit(getBitNum());
1384 return const_cast<VarBitInit*>(this);
1387 VarListElementInit *VarListElementInit::get(TypedInit *T,
1389 typedef std::pair<TypedInit *, unsigned> Key;
1390 typedef DenseMap<Key, VarListElementInit *> Pool;
1392 static Pool ThePool;
1394 Key TheKey(std::make_pair(T, E));
1396 VarListElementInit *&I = ThePool[TheKey];
1397 if (!I) I = new VarListElementInit(T, E);
1401 std::string VarListElementInit::getAsString() const {
1402 return TI->getAsString() + "[" + utostr(Element) + "]";
1406 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1407 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1410 return const_cast<VarListElementInit *>(this);
1413 Init *VarListElementInit::getBit(unsigned Bit) const {
1414 if (getType() == BitRecTy::get())
1415 return const_cast<VarListElementInit*>(this);
1416 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1419 Init *VarListElementInit:: resolveListElementReference(Record &R,
1420 const RecordVal *RV,
1421 unsigned Elt) const {
1422 Init *Result = TI->resolveListElementReference(R, RV, Element);
1425 TypedInit *TInit = dyn_cast<TypedInit>(Result);
1427 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1428 if (Result2) return Result2;
1429 return new VarListElementInit(TInit, Elt);
1437 DefInit *DefInit::get(Record *R) {
1438 return R->getDefInit();
1441 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1442 if (const RecordVal *RV = Def->getValue(FieldName))
1443 return RV->getType();
1447 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1448 const std::string &FieldName) const {
1449 return Def->getValue(FieldName)->getValue();
1453 std::string DefInit::getAsString() const {
1454 return Def->getName();
1457 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1458 typedef std::pair<Init *, TableGenStringKey> Key;
1459 typedef DenseMap<Key, FieldInit *> Pool;
1460 static Pool ThePool;
1462 Key TheKey(std::make_pair(R, FN));
1464 FieldInit *&I = ThePool[TheKey];
1465 if (!I) I = new FieldInit(R, FN);
1469 Init *FieldInit::getBit(unsigned Bit) const {
1470 if (getType() == BitRecTy::get())
1471 return const_cast<FieldInit*>(this);
1472 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1475 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1476 unsigned Elt) const {
1477 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1478 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1479 if (Elt >= LI->getSize()) return 0;
1480 Init *E = LI->getElement(Elt);
1482 // If the element is set to some value, or if we are resolving a
1483 // reference to a specific variable and that variable is explicitly
1484 // unset, then replace the VarListElementInit with it.
1485 if (RV || !dyn_cast<UnsetInit>(E))
1491 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1492 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1494 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1496 Init *BVR = BitsVal->resolveReferences(R, RV);
1497 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1500 if (NewRec != Rec) {
1501 return FieldInit::get(NewRec, FieldName);
1503 return const_cast<FieldInit *>(this);
1506 void ProfileDagInit(FoldingSetNodeID &ID,
1508 const std::string &VN,
1509 ArrayRef<Init *> ArgRange,
1510 ArrayRef<std::string> NameRange) {
1514 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1515 ArrayRef<std::string>::iterator Name = NameRange.begin();
1516 while (Arg != ArgRange.end()) {
1517 assert(Name != NameRange.end() && "Arg name underflow!");
1518 ID.AddPointer(*Arg++);
1519 ID.AddString(*Name++);
1521 assert(Name == NameRange.end() && "Arg name overflow!");
1525 DagInit::get(Init *V, const std::string &VN,
1526 ArrayRef<Init *> ArgRange,
1527 ArrayRef<std::string> NameRange) {
1528 typedef FoldingSet<DagInit> Pool;
1529 static Pool ThePool;
1531 FoldingSetNodeID ID;
1532 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1535 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1538 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1539 ThePool.InsertNode(I, IP);
1545 DagInit::get(Init *V, const std::string &VN,
1546 const std::vector<std::pair<Init*, std::string> > &args) {
1547 typedef std::pair<Init*, std::string> PairType;
1549 std::vector<Init *> Args;
1550 std::vector<std::string> Names;
1552 for (std::vector<PairType>::const_iterator i = args.begin(),
1556 Args.push_back(i->first);
1557 Names.push_back(i->second);
1560 return DagInit::get(V, VN, Args, Names);
1563 void DagInit::Profile(FoldingSetNodeID &ID) const {
1564 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1567 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1568 std::vector<Init*> NewArgs;
1569 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1570 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1572 Init *Op = Val->resolveReferences(R, RV);
1574 if (Args != NewArgs || Op != Val)
1575 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1577 return const_cast<DagInit *>(this);
1581 std::string DagInit::getAsString() const {
1582 std::string Result = "(" + Val->getAsString();
1583 if (!ValName.empty())
1584 Result += ":" + ValName;
1586 Result += " " + Args[0]->getAsString();
1587 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1588 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1589 Result += ", " + Args[i]->getAsString();
1590 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1593 return Result + ")";
1597 //===----------------------------------------------------------------------===//
1598 // Other implementations
1599 //===----------------------------------------------------------------------===//
1601 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1602 : Name(N), Ty(T), Prefix(P) {
1603 Value = Ty->convertValue(UnsetInit::get());
1604 assert(Value && "Cannot create unset value for current type!");
1607 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1608 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1609 Value = Ty->convertValue(UnsetInit::get());
1610 assert(Value && "Cannot create unset value for current type!");
1613 const std::string &RecordVal::getName() const {
1614 StringInit *NameString = dyn_cast<StringInit>(Name);
1615 assert(NameString && "RecordVal name is not a string!");
1616 return NameString->getValue();
1619 void RecordVal::dump() const { errs() << *this; }
1621 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1622 if (getPrefix()) OS << "field ";
1623 OS << *getType() << " " << getNameInitAsString();
1626 OS << " = " << *getValue();
1628 if (PrintSem) OS << ";\n";
1631 unsigned Record::LastID = 0;
1633 void Record::init() {
1636 // Every record potentially has a def at the top. This value is
1637 // replaced with the top-level def name at instantiation time.
1638 RecordVal DN("NAME", StringRecTy::get(), 0);
1642 void Record::checkName() {
1643 // Ensure the record name has string type.
1644 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1645 assert(TypedName && "Record name is not typed!");
1646 RecTy *Type = TypedName->getType();
1647 if (!isa<StringRecTy>(Type))
1648 throw TGError(getLoc(), "Record name is not a string!");
1651 DefInit *Record::getDefInit() {
1653 TheInit = new DefInit(this, new RecordRecTy(this));
1657 const std::string &Record::getName() const {
1658 const StringInit *NameString =
1659 dyn_cast<const StringInit>(Name);
1660 assert(NameString && "Record name is not a string!");
1661 return NameString->getValue();
1664 void Record::setName(Init *NewName) {
1665 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1666 TrackedRecords.removeDef(Name->getAsUnquotedString());
1667 TrackedRecords.addDef(this);
1668 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1669 TrackedRecords.removeClass(Name->getAsUnquotedString());
1670 TrackedRecords.addClass(this);
1671 } // Otherwise this isn't yet registered.
1674 // DO NOT resolve record values to the name at this point because
1675 // there might be default values for arguments of this def. Those
1676 // arguments might not have been resolved yet so we don't want to
1677 // prematurely assume values for those arguments were not passed to
1680 // Nonetheless, it may be that some of this Record's values
1681 // reference the record name. Indeed, the reason for having the
1682 // record name be an Init is to provide this flexibility. The extra
1683 // resolve steps after completely instantiating defs takes care of
1684 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1687 void Record::setName(const std::string &Name) {
1688 setName(StringInit::get(Name));
1691 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1692 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1694 void Record::resolveReferencesTo(const RecordVal *RV) {
1695 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1696 if (RV == &Values[i]) // Skip resolve the same field as the given one
1698 if (Init *V = Values[i].getValue())
1699 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1700 throw TGError(getLoc(), "Invalid value is found when setting '"
1701 + Values[i].getNameInitAsString()
1702 + "' after resolving references"
1703 + (RV ? " against '" + RV->getNameInitAsString()
1705 + RV->getValue()->getAsUnquotedString() + ")"
1709 Init *OldName = getNameInit();
1710 Init *NewName = Name->resolveReferences(*this, RV);
1711 if (NewName != OldName) {
1712 // Re-register with RecordKeeper.
1717 void Record::dump() const { errs() << *this; }
1719 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1720 OS << R.getNameInitAsString();
1722 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1723 if (!TArgs.empty()) {
1725 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1727 const RecordVal *RV = R.getValue(TArgs[i]);
1728 assert(RV && "Template argument record not found??");
1729 RV->print(OS, false);
1735 const std::vector<Record*> &SC = R.getSuperClasses();
1738 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1739 OS << " " << SC[i]->getNameInitAsString();
1743 const std::vector<RecordVal> &Vals = R.getValues();
1744 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1745 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1747 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1748 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1754 /// getValueInit - Return the initializer for a value with the specified name,
1755 /// or throw an exception if the field does not exist.
1757 Init *Record::getValueInit(StringRef FieldName) const {
1758 const RecordVal *R = getValue(FieldName);
1759 if (R == 0 || R->getValue() == 0)
1760 throw "Record `" + getName() + "' does not have a field named `" +
1761 FieldName.str() + "'!\n";
1762 return R->getValue();
1766 /// getValueAsString - This method looks up the specified field and returns its
1767 /// value as a string, throwing an exception if the field does not exist or if
1768 /// the value is not a string.
1770 std::string Record::getValueAsString(StringRef FieldName) const {
1771 const RecordVal *R = getValue(FieldName);
1772 if (R == 0 || R->getValue() == 0)
1773 throw "Record `" + getName() + "' does not have a field named `" +
1774 FieldName.str() + "'!\n";
1776 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1777 return SI->getValue();
1778 throw "Record `" + getName() + "', field `" + FieldName.str() +
1779 "' does not have a string initializer!";
1782 /// getValueAsBitsInit - This method looks up the specified field and returns
1783 /// its value as a BitsInit, throwing an exception if the field does not exist
1784 /// or if the value is not the right type.
1786 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1787 const RecordVal *R = getValue(FieldName);
1788 if (R == 0 || R->getValue() == 0)
1789 throw "Record `" + getName() + "' does not have a field named `" +
1790 FieldName.str() + "'!\n";
1792 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1794 throw "Record `" + getName() + "', field `" + FieldName.str() +
1795 "' does not have a BitsInit initializer!";
1798 /// getValueAsListInit - This method looks up the specified field and returns
1799 /// its value as a ListInit, throwing an exception if the field does not exist
1800 /// or if the value is not the right type.
1802 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1803 const RecordVal *R = getValue(FieldName);
1804 if (R == 0 || R->getValue() == 0)
1805 throw "Record `" + getName() + "' does not have a field named `" +
1806 FieldName.str() + "'!\n";
1808 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1810 throw "Record `" + getName() + "', field `" + FieldName.str() +
1811 "' does not have a list initializer!";
1814 /// getValueAsListOfDefs - This method looks up the specified field and returns
1815 /// its value as a vector of records, throwing an exception if the field does
1816 /// not exist or if the value is not the right type.
1818 std::vector<Record*>
1819 Record::getValueAsListOfDefs(StringRef FieldName) const {
1820 ListInit *List = getValueAsListInit(FieldName);
1821 std::vector<Record*> Defs;
1822 for (unsigned i = 0; i < List->getSize(); i++) {
1823 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1824 Defs.push_back(DI->getDef());
1826 throw "Record `" + getName() + "', field `" + FieldName.str() +
1827 "' list is not entirely DefInit!";
1833 /// getValueAsInt - This method looks up the specified field and returns its
1834 /// value as an int64_t, throwing an exception if the field does not exist or if
1835 /// the value is not the right type.
1837 int64_t Record::getValueAsInt(StringRef FieldName) const {
1838 const RecordVal *R = getValue(FieldName);
1839 if (R == 0 || R->getValue() == 0)
1840 throw "Record `" + getName() + "' does not have a field named `" +
1841 FieldName.str() + "'!\n";
1843 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1844 return II->getValue();
1845 throw "Record `" + getName() + "', field `" + FieldName.str() +
1846 "' does not have an int initializer!";
1849 /// getValueAsListOfInts - This method looks up the specified field and returns
1850 /// its value as a vector of integers, throwing an exception if the field does
1851 /// not exist or if the value is not the right type.
1853 std::vector<int64_t>
1854 Record::getValueAsListOfInts(StringRef FieldName) const {
1855 ListInit *List = getValueAsListInit(FieldName);
1856 std::vector<int64_t> Ints;
1857 for (unsigned i = 0; i < List->getSize(); i++) {
1858 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1859 Ints.push_back(II->getValue());
1861 throw "Record `" + getName() + "', field `" + FieldName.str() +
1862 "' does not have a list of ints initializer!";
1868 /// getValueAsListOfStrings - This method looks up the specified field and
1869 /// returns its value as a vector of strings, throwing an exception if the
1870 /// field does not exist or if the value is not the right type.
1872 std::vector<std::string>
1873 Record::getValueAsListOfStrings(StringRef FieldName) const {
1874 ListInit *List = getValueAsListInit(FieldName);
1875 std::vector<std::string> Strings;
1876 for (unsigned i = 0; i < List->getSize(); i++) {
1877 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1878 Strings.push_back(II->getValue());
1880 throw "Record `" + getName() + "', field `" + FieldName.str() +
1881 "' does not have a list of strings initializer!";
1887 /// getValueAsDef - This method looks up the specified field and returns its
1888 /// value as a Record, throwing an exception if the field does not exist or if
1889 /// the value is not the right type.
1891 Record *Record::getValueAsDef(StringRef FieldName) const {
1892 const RecordVal *R = getValue(FieldName);
1893 if (R == 0 || R->getValue() == 0)
1894 throw "Record `" + getName() + "' does not have a field named `" +
1895 FieldName.str() + "'!\n";
1897 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1898 return DI->getDef();
1899 throw "Record `" + getName() + "', field `" + FieldName.str() +
1900 "' does not have a def initializer!";
1903 /// getValueAsBit - This method looks up the specified field and returns its
1904 /// value as a bit, throwing an exception if the field does not exist or if
1905 /// the value is not the right type.
1907 bool Record::getValueAsBit(StringRef FieldName) const {
1908 const RecordVal *R = getValue(FieldName);
1909 if (R == 0 || R->getValue() == 0)
1910 throw "Record `" + getName() + "' does not have a field named `" +
1911 FieldName.str() + "'!\n";
1913 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1914 return BI->getValue();
1915 throw "Record `" + getName() + "', field `" + FieldName.str() +
1916 "' does not have a bit initializer!";
1919 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1920 const RecordVal *R = getValue(FieldName);
1921 if (R == 0 || R->getValue() == 0)
1922 throw "Record `" + getName() + "' does not have a field named `" +
1923 FieldName.str() + "'!\n";
1925 if (R->getValue() == UnsetInit::get()) {
1930 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1931 return BI->getValue();
1932 throw "Record `" + getName() + "', field `" + FieldName.str() +
1933 "' does not have a bit initializer!";
1936 /// getValueAsDag - This method looks up the specified field and returns its
1937 /// value as an Dag, throwing an exception if the field does not exist or if
1938 /// the value is not the right type.
1940 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1941 const RecordVal *R = getValue(FieldName);
1942 if (R == 0 || R->getValue() == 0)
1943 throw "Record `" + getName() + "' does not have a field named `" +
1944 FieldName.str() + "'!\n";
1946 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1948 throw "Record `" + getName() + "', field `" + FieldName.str() +
1949 "' does not have a dag initializer!";
1953 void MultiClass::dump() const {
1954 errs() << "Record:\n";
1957 errs() << "Defs:\n";
1958 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1959 rend = DefPrototypes.end();
1967 void RecordKeeper::dump() const { errs() << *this; }
1969 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1970 OS << "------------- Classes -----------------\n";
1971 const std::map<std::string, Record*> &Classes = RK.getClasses();
1972 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1973 E = Classes.end(); I != E; ++I)
1974 OS << "class " << *I->second;
1976 OS << "------------- Defs -----------------\n";
1977 const std::map<std::string, Record*> &Defs = RK.getDefs();
1978 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1979 E = Defs.end(); I != E; ++I)
1980 OS << "def " << *I->second;
1985 /// getAllDerivedDefinitions - This method returns all concrete definitions
1986 /// that derive from the specified class name. If a class with the specified
1987 /// name does not exist, an error is printed and true is returned.
1988 std::vector<Record*>
1989 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1990 Record *Class = getClass(ClassName);
1992 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1994 std::vector<Record*> Defs;
1995 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1996 E = getDefs().end(); I != E; ++I)
1997 if (I->second->isSubClassOf(Class))
1998 Defs.push_back(I->second);
2003 /// QualifyName - Return an Init with a qualifier prefix referring
2004 /// to CurRec's name.
2005 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2006 Init *Name, const std::string &Scoper) {
2007 RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
2009 BinOpInit *NewName =
2010 BinOpInit::get(BinOpInit::STRCONCAT,
2011 BinOpInit::get(BinOpInit::STRCONCAT,
2012 CurRec.getNameInit(),
2013 StringInit::get(Scoper),
2014 Type)->Fold(&CurRec, CurMultiClass),
2018 if (CurMultiClass && Scoper != "::") {
2020 BinOpInit::get(BinOpInit::STRCONCAT,
2021 BinOpInit::get(BinOpInit::STRCONCAT,
2022 CurMultiClass->Rec.getNameInit(),
2023 StringInit::get("::"),
2024 Type)->Fold(&CurRec, CurMultiClass),
2025 NewName->Fold(&CurRec, CurMultiClass),
2029 return NewName->Fold(&CurRec, CurMultiClass);
2032 /// QualifyName - Return an Init with a qualifier prefix referring
2033 /// to CurRec's name.
2034 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2035 const std::string &Name,
2036 const std::string &Scoper) {
2037 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);