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 (dynamic_cast<BitRecTy*>(Ty) ||
117 dynamic_cast<BitsRecTy*>(Ty) ||
118 dynamic_cast<IntRecTy*>(Ty))
119 return VI; // Accept variable if it is already of bit type!
123 BitsRecTy *BitsRecTy::get(unsigned Sz) {
124 static std::vector<BitsRecTy*> Shared;
125 if (Sz >= Shared.size())
126 Shared.resize(Sz + 1);
127 BitsRecTy *&Ty = Shared[Sz];
129 Ty = new BitsRecTy(Sz);
133 std::string BitsRecTy::getAsString() const {
134 return "bits<" + utostr(Size) + ">";
137 Init *BitsRecTy::convertValue(UnsetInit *UI) {
138 SmallVector<Init *, 16> NewBits(Size);
140 for (unsigned i = 0; i != Size; ++i)
141 NewBits[i] = UnsetInit::get();
143 return BitsInit::get(NewBits);
146 Init *BitsRecTy::convertValue(BitInit *UI) {
147 if (Size != 1) return 0; // Can only convert single bit.
148 return BitsInit::get(UI);
151 /// canFitInBitfield - Return true if the number of bits is large enough to hold
152 /// the integer value.
153 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
154 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
155 return (NumBits >= sizeof(Value) * 8) ||
156 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
159 /// convertValue from Int initializer to bits type: Split the integer up into the
160 /// appropriate bits.
162 Init *BitsRecTy::convertValue(IntInit *II) {
163 int64_t Value = II->getValue();
164 // Make sure this bitfield is large enough to hold the integer value.
165 if (!canFitInBitfield(Value, Size))
168 SmallVector<Init *, 16> NewBits(Size);
170 for (unsigned i = 0; i != Size; ++i)
171 NewBits[i] = BitInit::get(Value & (1LL << i));
173 return BitsInit::get(NewBits);
176 Init *BitsRecTy::convertValue(BitsInit *BI) {
177 // If the number of bits is right, return it. Otherwise we need to expand or
179 if (BI->getNumBits() == Size) return BI;
183 Init *BitsRecTy::convertValue(TypedInit *VI) {
184 if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType()))
185 return BitsInit::get(VI);
187 if (VI->getType()->typeIsConvertibleTo(this)) {
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = VarBitInit::get(VI, i);
192 return BitsInit::get(NewBits);
198 Init *IntRecTy::convertValue(BitInit *BI) {
199 return IntInit::get(BI->getValue());
202 Init *IntRecTy::convertValue(BitsInit *BI) {
204 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
205 if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
206 Result |= Bit->getValue() << i;
210 return IntInit::get(Result);
213 Init *IntRecTy::convertValue(TypedInit *TI) {
214 if (TI->getType()->typeIsConvertibleTo(this))
215 return TI; // Accept variable if already of the right type!
219 Init *StringRecTy::convertValue(UnOpInit *BO) {
220 if (BO->getOpcode() == UnOpInit::CAST) {
221 Init *L = BO->getOperand()->convertInitializerTo(this);
222 if (L == 0) return 0;
223 if (L != BO->getOperand())
224 return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
228 return convertValue((TypedInit*)BO);
231 Init *StringRecTy::convertValue(BinOpInit *BO) {
232 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
233 Init *L = BO->getLHS()->convertInitializerTo(this);
234 Init *R = BO->getRHS()->convertInitializerTo(this);
235 if (L == 0 || R == 0) return 0;
236 if (L != BO->getLHS() || R != BO->getRHS())
237 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
241 return convertValue((TypedInit*)BO);
245 Init *StringRecTy::convertValue(TypedInit *TI) {
246 if (dynamic_cast<StringRecTy*>(TI->getType()))
247 return TI; // Accept variable if already of the right type!
251 std::string ListRecTy::getAsString() const {
252 return "list<" + Ty->getAsString() + ">";
255 Init *ListRecTy::convertValue(ListInit *LI) {
256 std::vector<Init*> Elements;
258 // Verify that all of the elements of the list are subclasses of the
259 // appropriate class!
260 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
261 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
262 Elements.push_back(CI);
266 ListRecTy *LType = dynamic_cast<ListRecTy*>(LI->getType());
271 return ListInit::get(Elements, this);
274 Init *ListRecTy::convertValue(TypedInit *TI) {
275 // Ensure that TI is compatible with our class.
276 if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
277 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
282 Init *DagRecTy::convertValue(TypedInit *TI) {
283 if (TI->getType()->typeIsConvertibleTo(this))
288 Init *DagRecTy::convertValue(UnOpInit *BO) {
289 if (BO->getOpcode() == UnOpInit::CAST) {
290 Init *L = BO->getOperand()->convertInitializerTo(this);
291 if (L == 0) return 0;
292 if (L != BO->getOperand())
293 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
299 Init *DagRecTy::convertValue(BinOpInit *BO) {
300 if (BO->getOpcode() == BinOpInit::CONCAT) {
301 Init *L = BO->getLHS()->convertInitializerTo(this);
302 Init *R = BO->getRHS()->convertInitializerTo(this);
303 if (L == 0 || R == 0) return 0;
304 if (L != BO->getLHS() || R != BO->getRHS())
305 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
311 RecordRecTy *RecordRecTy::get(Record *R) {
312 return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
315 std::string RecordRecTy::getAsString() const {
316 return Rec->getName();
319 Init *RecordRecTy::convertValue(DefInit *DI) {
320 // Ensure that DI is a subclass of Rec.
321 if (!DI->getDef()->isSubClassOf(Rec))
326 Init *RecordRecTy::convertValue(TypedInit *TI) {
327 // Ensure that TI is compatible with Rec.
328 if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
329 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
330 RRT->getRecord() == getRecord())
335 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
336 if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
339 const std::vector<Record*> &SC = Rec->getSuperClasses();
340 for (unsigned i = 0, e = SC.size(); i != e; ++i)
341 if (RHS->getRecord()->isSubClassOf(SC[i]))
348 /// resolveTypes - Find a common type that T1 and T2 convert to.
349 /// Return 0 if no such type exists.
351 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
352 if (!T1->typeIsConvertibleTo(T2)) {
353 if (!T2->typeIsConvertibleTo(T1)) {
354 // If one is a Record type, check superclasses
355 RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
357 // See if T2 inherits from a type T1 also inherits from
358 const std::vector<Record *> &T1SuperClasses =
359 RecTy1->getRecord()->getSuperClasses();
360 for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
361 iend = T1SuperClasses.end();
364 RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
365 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
367 if (NewType1 != SuperRecTy1) {
374 RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
376 // See if T1 inherits from a type T2 also inherits from
377 const std::vector<Record *> &T2SuperClasses =
378 RecTy2->getRecord()->getSuperClasses();
379 for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
380 iend = T2SuperClasses.end();
383 RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
384 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
386 if (NewType2 != SuperRecTy2) {
401 //===----------------------------------------------------------------------===//
402 // Initializer implementations
403 //===----------------------------------------------------------------------===//
405 void Init::anchor() { }
406 void Init::dump() const { return print(errs()); }
408 void UnsetInit::anchor() { }
410 UnsetInit *UnsetInit::get() {
411 static UnsetInit TheInit;
415 void BitInit::anchor() { }
417 BitInit *BitInit::get(bool V) {
418 static BitInit True(true);
419 static BitInit False(false);
421 return V ? &True : &False;
425 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
426 ID.AddInteger(Range.size());
428 for (ArrayRef<Init *>::iterator i = Range.begin(),
435 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
436 typedef FoldingSet<BitsInit> Pool;
440 ProfileBitsInit(ID, Range);
443 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
446 BitsInit *I = new BitsInit(Range);
447 ThePool.InsertNode(I, IP);
452 void BitsInit::Profile(FoldingSetNodeID &ID) const {
453 ProfileBitsInit(ID, Bits);
457 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
458 SmallVector<Init *, 16> NewBits(Bits.size());
460 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
461 if (Bits[i] >= getNumBits())
463 NewBits[i] = getBit(Bits[i]);
465 return BitsInit::get(NewBits);
468 std::string BitsInit::getAsString() const {
469 std::string Result = "{ ";
470 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
471 if (i) Result += ", ";
472 if (Init *Bit = getBit(e-i-1))
473 Result += Bit->getAsString();
477 return Result + " }";
480 // Fix bit initializer to preserve the behavior that bit reference from a unset
481 // bits initializer will resolve into VarBitInit to keep the field name and bit
482 // number used in targets with fixed insn length.
483 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
484 if (RV || After != UnsetInit::get())
489 // resolveReferences - If there are any field references that refer to fields
490 // that have been filled in, we can propagate the values now.
492 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
493 bool Changed = false;
494 SmallVector<Init *, 16> NewBits(getNumBits());
496 Init *CachedInit = 0;
497 Init *CachedBitVar = 0;
498 bool CachedBitVarChanged = false;
500 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
501 Init *CurBit = Bits[i];
502 Init *CurBitVar = CurBit->getBitVar();
506 if (CurBitVar == CachedBitVar) {
507 if (CachedBitVarChanged) {
508 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
509 NewBits[i] = fixBitInit(RV, CurBit, Bit);
513 CachedBitVar = CurBitVar;
514 CachedBitVarChanged = false;
519 CurBitVar = CurBitVar->resolveReferences(R, RV);
520 CachedBitVarChanged |= B != CurBitVar;
521 Changed |= B != CurBitVar;
522 } while (B != CurBitVar);
523 CachedInit = CurBitVar;
525 if (CachedBitVarChanged) {
526 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
527 NewBits[i] = fixBitInit(RV, CurBit, Bit);
532 return BitsInit::get(NewBits);
534 return const_cast<BitsInit *>(this);
537 IntInit *IntInit::get(int64_t V) {
538 typedef DenseMap<int64_t, IntInit *> Pool;
541 IntInit *&I = ThePool[V];
542 if (!I) I = new IntInit(V);
546 std::string IntInit::getAsString() const {
547 return itostr(Value);
551 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
552 SmallVector<Init *, 16> NewBits(Bits.size());
554 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
558 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
560 return BitsInit::get(NewBits);
563 void StringInit::anchor() { }
565 StringInit *StringInit::get(StringRef V) {
566 typedef StringMap<StringInit *> Pool;
569 StringInit *&I = ThePool[V];
570 if (!I) I = new StringInit(V);
574 static void ProfileListInit(FoldingSetNodeID &ID,
575 ArrayRef<Init *> Range,
577 ID.AddInteger(Range.size());
578 ID.AddPointer(EltTy);
580 for (ArrayRef<Init *>::iterator i = Range.begin(),
587 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
588 typedef FoldingSet<ListInit> Pool;
591 // Just use the FoldingSetNodeID to compute a hash. Use a DenseMap
592 // for actual storage.
594 ProfileListInit(ID, Range, EltTy);
597 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
600 ListInit *I = new ListInit(Range, EltTy);
601 ThePool.InsertNode(I, IP);
605 void ListInit::Profile(FoldingSetNodeID &ID) const {
606 ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
607 assert(ListType && "Bad type for ListInit!");
608 RecTy *EltTy = ListType->getElementType();
610 ProfileListInit(ID, Values, EltTy);
614 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
615 std::vector<Init*> Vals;
616 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
617 if (Elements[i] >= getSize())
619 Vals.push_back(getElement(Elements[i]));
621 return ListInit::get(Vals, getType());
624 Record *ListInit::getElementAsRecord(unsigned i) const {
625 assert(i < Values.size() && "List element index out of range!");
626 DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
627 if (DI == 0) throw "Expected record in list!";
631 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
632 std::vector<Init*> Resolved;
633 Resolved.reserve(getSize());
634 bool Changed = false;
636 for (unsigned i = 0, e = getSize(); i != e; ++i) {
638 Init *CurElt = getElement(i);
642 CurElt = CurElt->resolveReferences(R, RV);
643 Changed |= E != CurElt;
644 } while (E != CurElt);
645 Resolved.push_back(E);
649 return ListInit::get(Resolved, getType());
650 return const_cast<ListInit *>(this);
653 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
654 unsigned Elt) const {
655 if (Elt >= getSize())
656 return 0; // Out of range reference.
657 Init *E = getElement(Elt);
658 // If the element is set to some value, or if we are resolving a reference
659 // to a specific variable and that variable is explicitly unset, then
660 // replace the VarListElementInit with it.
661 if (IRV || !dynamic_cast<UnsetInit*>(E))
666 std::string ListInit::getAsString() const {
667 std::string Result = "[";
668 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
669 if (i) Result += ", ";
670 Result += Values[i]->getAsString();
675 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
676 unsigned Elt) const {
677 Init *Resolved = resolveReferences(R, IRV);
678 OpInit *OResolved = dynamic_cast<OpInit *>(Resolved);
680 Resolved = OResolved->Fold(&R, 0);
683 if (Resolved != this) {
684 TypedInit *Typed = dynamic_cast<TypedInit *>(Resolved);
685 assert(Typed && "Expected typed init for list reference");
687 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
690 return VarListElementInit::get(Typed, Elt);
697 Init *OpInit::getBit(unsigned Bit) const {
698 if (getType() == BitRecTy::get())
699 return const_cast<OpInit*>(this);
700 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
703 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
704 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
706 typedef DenseMap<Key, UnOpInit *> Pool;
709 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
711 UnOpInit *&I = ThePool[TheKey];
712 if (!I) I = new UnOpInit(opc, lhs, Type);
716 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
717 switch (getOpcode()) {
719 if (getType()->getAsString() == "string") {
720 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
725 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
727 return StringInit::get(LHSd->getDef()->getName());
730 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
732 return StringInit::get(LHSi->getAsString());
735 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
737 std::string Name = LHSs->getValue();
739 // From TGParser::ParseIDValue
741 if (const RecordVal *RV = CurRec->getValue(Name)) {
742 if (RV->getType() != getType())
743 throw "type mismatch in cast";
744 return VarInit::get(Name, RV->getType());
747 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
750 if (CurRec->isTemplateArg(TemplateArgName)) {
751 const RecordVal *RV = CurRec->getValue(TemplateArgName);
752 assert(RV && "Template arg doesn't exist??");
754 if (RV->getType() != getType())
755 throw "type mismatch in cast";
757 return VarInit::get(TemplateArgName, RV->getType());
762 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
764 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
765 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
766 assert(RV && "Template arg doesn't exist??");
768 if (RV->getType() != getType())
769 throw "type mismatch in cast";
771 return VarInit::get(MCName, RV->getType());
775 if (Record *D = (CurRec->getRecords()).getDef(Name))
776 return DefInit::get(D);
778 throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
784 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
786 if (LHSl->getSize() == 0) {
787 assert(0 && "Empty list in car");
790 return LHSl->getElement(0);
795 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
797 if (LHSl->getSize() == 0) {
798 assert(0 && "Empty list in cdr");
801 // Note the +1. We can't just pass the result of getValues()
803 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
804 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
806 ListInit::get(ArrayRef<Init *>(begin, end - begin),
813 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
815 if (LHSl->getSize() == 0) {
816 return IntInit::get(1);
818 return IntInit::get(0);
821 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
823 if (LHSs->getValue().empty()) {
824 return IntInit::get(1);
826 return IntInit::get(0);
833 return const_cast<UnOpInit *>(this);
836 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
837 Init *lhs = LHS->resolveReferences(R, RV);
840 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
844 std::string UnOpInit::getAsString() const {
847 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
848 case HEAD: Result = "!head"; break;
849 case TAIL: Result = "!tail"; break;
850 case EMPTY: Result = "!empty"; break;
852 return Result + "(" + LHS->getAsString() + ")";
855 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
856 Init *rhs, RecTy *Type) {
858 std::pair<std::pair<unsigned, Init *>, Init *>,
862 typedef DenseMap<Key, BinOpInit *> Pool;
865 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
868 BinOpInit *&I = ThePool[TheKey];
869 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
873 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
874 switch (getOpcode()) {
876 DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
877 DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
879 DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
880 DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
881 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
882 throw "Concated Dag operators do not match!";
883 std::vector<Init*> Args;
884 std::vector<std::string> ArgNames;
885 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
886 Args.push_back(LHSs->getArg(i));
887 ArgNames.push_back(LHSs->getArgName(i));
889 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
890 Args.push_back(RHSs->getArg(i));
891 ArgNames.push_back(RHSs->getArgName(i));
893 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
898 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
899 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
901 return StringInit::get(LHSs->getValue() + RHSs->getValue());
905 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
906 // to string objects.
908 dynamic_cast<IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
910 dynamic_cast<IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
913 return IntInit::get(L->getValue() == R->getValue());
915 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
916 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
918 // Make sure we've resolved
920 return IntInit::get(LHSs->getValue() == RHSs->getValue());
927 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
928 IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
930 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
932 switch (getOpcode()) {
933 default: llvm_unreachable("Bad opcode!");
934 case SHL: Result = LHSv << RHSv; break;
935 case SRA: Result = LHSv >> RHSv; break;
936 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
938 return IntInit::get(Result);
943 return const_cast<BinOpInit *>(this);
946 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
947 Init *lhs = LHS->resolveReferences(R, RV);
948 Init *rhs = RHS->resolveReferences(R, RV);
950 if (LHS != lhs || RHS != rhs)
951 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
955 std::string BinOpInit::getAsString() const {
958 case CONCAT: Result = "!con"; break;
959 case SHL: Result = "!shl"; break;
960 case SRA: Result = "!sra"; break;
961 case SRL: Result = "!srl"; break;
962 case EQ: Result = "!eq"; break;
963 case STRCONCAT: Result = "!strconcat"; break;
965 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
968 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
969 Init *mhs, Init *rhs,
973 std::pair<std::pair<unsigned, RecTy *>, Init *>,
979 typedef DenseMap<Key, TernOpInit *> Pool;
982 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
988 TernOpInit *&I = ThePool[TheKey];
989 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
993 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
994 Record *CurRec, MultiClass *CurMultiClass);
996 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
997 RecTy *Type, Record *CurRec,
998 MultiClass *CurMultiClass) {
999 std::vector<Init *> NewOperands;
1001 TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
1003 // If this is a dag, recurse
1004 if (TArg && TArg->getType()->getAsString() == "dag") {
1005 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1006 CurRec, CurMultiClass);
1014 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1015 OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
1018 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1019 Type, CurRec, CurMultiClass);
1021 NewOperands.push_back(Result);
1023 NewOperands.push_back(Arg);
1025 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1026 NewOperands.push_back(Arg);
1028 NewOperands.push_back(RHSo->getOperand(i));
1032 // Now run the operator and use its result as the new leaf
1033 const OpInit *NewOp = RHSo->clone(NewOperands);
1034 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1035 if (NewVal != NewOp)
1041 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1042 Record *CurRec, MultiClass *CurMultiClass) {
1043 DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
1044 ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
1046 DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1047 ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1049 OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
1052 throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1055 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
1058 throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1061 if ((MHSd && DagType) || (MHSl && ListType)) {
1063 Init *Val = MHSd->getOperator();
1064 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1065 Type, CurRec, CurMultiClass);
1070 std::vector<std::pair<Init *, std::string> > args;
1071 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1073 std::string ArgName;
1074 Arg = MHSd->getArg(i);
1075 ArgName = MHSd->getArgName(i);
1078 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1079 CurRec, CurMultiClass);
1084 // TODO: Process arg names
1085 args.push_back(std::make_pair(Arg, ArgName));
1088 return DagInit::get(Val, "", args);
1091 std::vector<Init *> NewOperands;
1092 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1094 for (std::vector<Init *>::iterator li = NewList.begin(),
1095 liend = NewList.end();
1099 NewOperands.clear();
1100 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1101 // First, replace the foreach variable with the list item
1102 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1103 NewOperands.push_back(Item);
1105 NewOperands.push_back(RHSo->getOperand(i));
1109 // Now run the operator and use its result as the new list item
1110 const OpInit *NewOp = RHSo->clone(NewOperands);
1111 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1112 if (NewItem != NewOp)
1115 return ListInit::get(NewList, MHSl->getType());
1121 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1122 switch (getOpcode()) {
1124 DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
1125 VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
1126 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
1128 DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
1129 VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
1130 StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
1132 DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
1133 VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
1134 StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
1136 if ((LHSd && MHSd && RHSd)
1137 || (LHSv && MHSv && RHSv)
1138 || (LHSs && MHSs && RHSs)) {
1140 Record *Val = RHSd->getDef();
1141 if (LHSd->getAsString() == RHSd->getAsString()) {
1142 Val = MHSd->getDef();
1144 return DefInit::get(Val);
1147 std::string Val = RHSv->getName();
1148 if (LHSv->getAsString() == RHSv->getAsString()) {
1149 Val = MHSv->getName();
1151 return VarInit::get(Val, getType());
1154 std::string Val = RHSs->getValue();
1156 std::string::size_type found;
1157 std::string::size_type idx = 0;
1159 found = Val.find(LHSs->getValue(), idx);
1160 if (found != std::string::npos) {
1161 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1163 idx = found + MHSs->getValue().size();
1164 } while (found != std::string::npos);
1166 return StringInit::get(Val);
1173 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1174 CurRec, CurMultiClass);
1182 IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1183 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1184 LHSi = dynamic_cast<IntInit*>(I);
1186 if (LHSi->getValue()) {
1196 return const_cast<TernOpInit *>(this);
1199 Init *TernOpInit::resolveReferences(Record &R,
1200 const RecordVal *RV) const {
1201 Init *lhs = LHS->resolveReferences(R, RV);
1203 if (Opc == IF && lhs != LHS) {
1204 IntInit *Value = dynamic_cast<IntInit*>(lhs);
1205 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1206 Value = dynamic_cast<IntInit*>(I);
1209 if (Value->getValue()) {
1210 Init *mhs = MHS->resolveReferences(R, RV);
1211 return (TernOpInit::get(getOpcode(), lhs, mhs,
1212 RHS, getType()))->Fold(&R, 0);
1214 Init *rhs = RHS->resolveReferences(R, RV);
1215 return (TernOpInit::get(getOpcode(), lhs, MHS,
1216 rhs, getType()))->Fold(&R, 0);
1221 Init *mhs = MHS->resolveReferences(R, RV);
1222 Init *rhs = RHS->resolveReferences(R, RV);
1224 if (LHS != lhs || MHS != mhs || RHS != rhs)
1225 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1226 getType()))->Fold(&R, 0);
1230 std::string TernOpInit::getAsString() const {
1233 case SUBST: Result = "!subst"; break;
1234 case FOREACH: Result = "!foreach"; break;
1235 case IF: Result = "!if"; break;
1237 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1238 + RHS->getAsString() + ")";
1241 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1242 RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1244 RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1246 return Field->getType();
1253 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1254 BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1255 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1256 unsigned NumBits = T->getNumBits();
1258 SmallVector<Init *, 16> NewBits(Bits.size());
1259 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1260 if (Bits[i] >= NumBits)
1263 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1265 return BitsInit::get(NewBits);
1269 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1270 ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1271 if (T == 0) return 0; // Cannot subscript a non-list variable.
1273 if (Elements.size() == 1)
1274 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1276 std::vector<Init*> ListInits;
1277 ListInits.reserve(Elements.size());
1278 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1279 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1281 return ListInit::get(ListInits, T);
1285 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1286 Init *Value = StringInit::get(VN);
1287 return VarInit::get(Value, T);
1290 VarInit *VarInit::get(Init *VN, RecTy *T) {
1291 typedef std::pair<RecTy *, Init *> Key;
1292 typedef DenseMap<Key, VarInit *> Pool;
1293 static Pool ThePool;
1295 Key TheKey(std::make_pair(T, VN));
1297 VarInit *&I = ThePool[TheKey];
1298 if (!I) I = new VarInit(VN, T);
1302 const std::string &VarInit::getName() const {
1303 StringInit *NameString =
1304 dynamic_cast<StringInit *>(getNameInit());
1305 assert(NameString && "VarInit name is not a string!");
1306 return NameString->getValue();
1309 Init *VarInit::getBit(unsigned Bit) const {
1310 if (getType() == BitRecTy::get())
1311 return const_cast<VarInit*>(this);
1312 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1315 Init *VarInit::resolveListElementReference(Record &R,
1316 const RecordVal *IRV,
1317 unsigned Elt) const {
1318 if (R.isTemplateArg(getNameInit())) return 0;
1319 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1321 RecordVal *RV = R.getValue(getNameInit());
1322 assert(RV && "Reference to a non-existent variable?");
1323 ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1325 TypedInit *VI = dynamic_cast<TypedInit*>(RV->getValue());
1326 assert(VI && "Invalid list element!");
1327 return VarListElementInit::get(VI, Elt);
1330 if (Elt >= LI->getSize())
1331 return 0; // Out of range reference.
1332 Init *E = LI->getElement(Elt);
1333 // If the element is set to some value, or if we are resolving a reference
1334 // to a specific variable and that variable is explicitly unset, then
1335 // replace the VarListElementInit with it.
1336 if (IRV || !dynamic_cast<UnsetInit*>(E))
1342 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1343 if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1344 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1345 return RV->getType();
1349 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1350 const std::string &FieldName) const {
1351 if (dynamic_cast<RecordRecTy*>(getType()))
1352 if (const RecordVal *Val = R.getValue(VarName)) {
1353 if (RV != Val && (RV || dynamic_cast<UnsetInit*>(Val->getValue())))
1355 Init *TheInit = Val->getValue();
1356 assert(TheInit != this && "Infinite loop detected!");
1357 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1365 /// resolveReferences - This method is used by classes that refer to other
1366 /// variables which may not be defined at the time the expression is formed.
1367 /// If a value is set for the variable later, this method will be called on
1368 /// users of the value to allow the value to propagate out.
1370 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1371 if (RecordVal *Val = R.getValue(VarName))
1372 if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1373 return Val->getValue();
1374 return const_cast<VarInit *>(this);
1377 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1378 typedef std::pair<TypedInit *, unsigned> Key;
1379 typedef DenseMap<Key, VarBitInit *> Pool;
1381 static Pool ThePool;
1383 Key TheKey(std::make_pair(T, B));
1385 VarBitInit *&I = ThePool[TheKey];
1386 if (!I) I = new VarBitInit(T, B);
1390 std::string VarBitInit::getAsString() const {
1391 return TI->getAsString() + "{" + utostr(Bit) + "}";
1394 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1395 Init *I = TI->resolveReferences(R, RV);
1397 return I->getBit(getBitNum());
1399 return const_cast<VarBitInit*>(this);
1402 VarListElementInit *VarListElementInit::get(TypedInit *T,
1404 typedef std::pair<TypedInit *, unsigned> Key;
1405 typedef DenseMap<Key, VarListElementInit *> Pool;
1407 static Pool ThePool;
1409 Key TheKey(std::make_pair(T, E));
1411 VarListElementInit *&I = ThePool[TheKey];
1412 if (!I) I = new VarListElementInit(T, E);
1416 std::string VarListElementInit::getAsString() const {
1417 return TI->getAsString() + "[" + utostr(Element) + "]";
1421 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1422 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1425 return const_cast<VarListElementInit *>(this);
1428 Init *VarListElementInit::getBit(unsigned Bit) const {
1429 if (getType() == BitRecTy::get())
1430 return const_cast<VarListElementInit*>(this);
1431 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1434 Init *VarListElementInit:: resolveListElementReference(Record &R,
1435 const RecordVal *RV,
1436 unsigned Elt) const {
1437 Init *Result = TI->resolveListElementReference(R, RV, Element);
1440 TypedInit *TInit = dynamic_cast<TypedInit *>(Result);
1442 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1443 if (Result2) return Result2;
1444 return new VarListElementInit(TInit, Elt);
1452 DefInit *DefInit::get(Record *R) {
1453 return R->getDefInit();
1456 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1457 if (const RecordVal *RV = Def->getValue(FieldName))
1458 return RV->getType();
1462 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1463 const std::string &FieldName) const {
1464 return Def->getValue(FieldName)->getValue();
1468 std::string DefInit::getAsString() const {
1469 return Def->getName();
1472 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1473 typedef std::pair<Init *, TableGenStringKey> Key;
1474 typedef DenseMap<Key, FieldInit *> Pool;
1475 static Pool ThePool;
1477 Key TheKey(std::make_pair(R, FN));
1479 FieldInit *&I = ThePool[TheKey];
1480 if (!I) I = new FieldInit(R, FN);
1484 Init *FieldInit::getBit(unsigned Bit) const {
1485 if (getType() == BitRecTy::get())
1486 return const_cast<FieldInit*>(this);
1487 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1490 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1491 unsigned Elt) const {
1492 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1493 if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1494 if (Elt >= LI->getSize()) return 0;
1495 Init *E = LI->getElement(Elt);
1497 // If the element is set to some value, or if we are resolving a
1498 // reference to a specific variable and that variable is explicitly
1499 // unset, then replace the VarListElementInit with it.
1500 if (RV || !dynamic_cast<UnsetInit*>(E))
1506 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1507 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1509 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1511 Init *BVR = BitsVal->resolveReferences(R, RV);
1512 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1515 if (NewRec != Rec) {
1516 return FieldInit::get(NewRec, FieldName);
1518 return const_cast<FieldInit *>(this);
1521 void ProfileDagInit(FoldingSetNodeID &ID,
1523 const std::string &VN,
1524 ArrayRef<Init *> ArgRange,
1525 ArrayRef<std::string> NameRange) {
1529 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1530 ArrayRef<std::string>::iterator Name = NameRange.begin();
1531 while (Arg != ArgRange.end()) {
1532 assert(Name != NameRange.end() && "Arg name underflow!");
1533 ID.AddPointer(*Arg++);
1534 ID.AddString(*Name++);
1536 assert(Name == NameRange.end() && "Arg name overflow!");
1540 DagInit::get(Init *V, const std::string &VN,
1541 ArrayRef<Init *> ArgRange,
1542 ArrayRef<std::string> NameRange) {
1543 typedef FoldingSet<DagInit> Pool;
1544 static Pool ThePool;
1546 FoldingSetNodeID ID;
1547 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1550 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1553 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1554 ThePool.InsertNode(I, IP);
1560 DagInit::get(Init *V, const std::string &VN,
1561 const std::vector<std::pair<Init*, std::string> > &args) {
1562 typedef std::pair<Init*, std::string> PairType;
1564 std::vector<Init *> Args;
1565 std::vector<std::string> Names;
1567 for (std::vector<PairType>::const_iterator i = args.begin(),
1571 Args.push_back(i->first);
1572 Names.push_back(i->second);
1575 return DagInit::get(V, VN, Args, Names);
1578 void DagInit::Profile(FoldingSetNodeID &ID) const {
1579 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1582 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1583 std::vector<Init*> NewArgs;
1584 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1585 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1587 Init *Op = Val->resolveReferences(R, RV);
1589 if (Args != NewArgs || Op != Val)
1590 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1592 return const_cast<DagInit *>(this);
1596 std::string DagInit::getAsString() const {
1597 std::string Result = "(" + Val->getAsString();
1598 if (!ValName.empty())
1599 Result += ":" + ValName;
1601 Result += " " + Args[0]->getAsString();
1602 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1603 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1604 Result += ", " + Args[i]->getAsString();
1605 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1608 return Result + ")";
1612 //===----------------------------------------------------------------------===//
1613 // Other implementations
1614 //===----------------------------------------------------------------------===//
1616 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1617 : Name(N), Ty(T), Prefix(P) {
1618 Value = Ty->convertValue(UnsetInit::get());
1619 assert(Value && "Cannot create unset value for current type!");
1622 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1623 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1624 Value = Ty->convertValue(UnsetInit::get());
1625 assert(Value && "Cannot create unset value for current type!");
1628 const std::string &RecordVal::getName() const {
1629 StringInit *NameString = dynamic_cast<StringInit *>(Name);
1630 assert(NameString && "RecordVal name is not a string!");
1631 return NameString->getValue();
1634 void RecordVal::dump() const { errs() << *this; }
1636 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1637 if (getPrefix()) OS << "field ";
1638 OS << *getType() << " " << getNameInitAsString();
1641 OS << " = " << *getValue();
1643 if (PrintSem) OS << ";\n";
1646 unsigned Record::LastID = 0;
1648 void Record::init() {
1651 // Every record potentially has a def at the top. This value is
1652 // replaced with the top-level def name at instantiation time.
1653 RecordVal DN("NAME", StringRecTy::get(), 0);
1657 void Record::checkName() {
1658 // Ensure the record name has string type.
1659 const TypedInit *TypedName = dynamic_cast<const TypedInit *>(Name);
1660 assert(TypedName && "Record name is not typed!");
1661 RecTy *Type = TypedName->getType();
1662 if (dynamic_cast<StringRecTy *>(Type) == 0) {
1663 throw TGError(getLoc(), "Record name is not a string!");
1667 DefInit *Record::getDefInit() {
1669 TheInit = new DefInit(this, new RecordRecTy(this));
1673 const std::string &Record::getName() const {
1674 const StringInit *NameString =
1675 dynamic_cast<const StringInit *>(Name);
1676 assert(NameString && "Record name is not a string!");
1677 return NameString->getValue();
1680 void Record::setName(Init *NewName) {
1681 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1682 TrackedRecords.removeDef(Name->getAsUnquotedString());
1683 TrackedRecords.addDef(this);
1684 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1685 TrackedRecords.removeClass(Name->getAsUnquotedString());
1686 TrackedRecords.addClass(this);
1687 } // Otherwise this isn't yet registered.
1690 // DO NOT resolve record values to the name at this point because
1691 // there might be default values for arguments of this def. Those
1692 // arguments might not have been resolved yet so we don't want to
1693 // prematurely assume values for those arguments were not passed to
1696 // Nonetheless, it may be that some of this Record's values
1697 // reference the record name. Indeed, the reason for having the
1698 // record name be an Init is to provide this flexibility. The extra
1699 // resolve steps after completely instantiating defs takes care of
1700 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1703 void Record::setName(const std::string &Name) {
1704 setName(StringInit::get(Name));
1707 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1708 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1710 void Record::resolveReferencesTo(const RecordVal *RV) {
1711 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1712 if (RV == &Values[i]) // Skip resolve the same field as the given one
1714 if (Init *V = Values[i].getValue())
1715 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1716 throw TGError(getLoc(), "Invalid value is found when setting '"
1717 + Values[i].getNameInitAsString()
1718 + "' after resolving references"
1719 + (RV ? " against '" + RV->getNameInitAsString()
1721 + RV->getValue()->getAsUnquotedString() + ")"
1725 Init *OldName = getNameInit();
1726 Init *NewName = Name->resolveReferences(*this, RV);
1727 if (NewName != OldName) {
1728 // Re-register with RecordKeeper.
1733 void Record::dump() const { errs() << *this; }
1735 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1736 OS << R.getNameInitAsString();
1738 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1739 if (!TArgs.empty()) {
1741 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1743 const RecordVal *RV = R.getValue(TArgs[i]);
1744 assert(RV && "Template argument record not found??");
1745 RV->print(OS, false);
1751 const std::vector<Record*> &SC = R.getSuperClasses();
1754 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1755 OS << " " << SC[i]->getNameInitAsString();
1759 const std::vector<RecordVal> &Vals = R.getValues();
1760 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1761 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1763 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1764 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1770 /// getValueInit - Return the initializer for a value with the specified name,
1771 /// or throw an exception if the field does not exist.
1773 Init *Record::getValueInit(StringRef FieldName) const {
1774 const RecordVal *R = getValue(FieldName);
1775 if (R == 0 || R->getValue() == 0)
1776 throw "Record `" + getName() + "' does not have a field named `" +
1777 FieldName.str() + "'!\n";
1778 return R->getValue();
1782 /// getValueAsString - This method looks up the specified field and returns its
1783 /// value as a string, throwing an exception if the field does not exist or if
1784 /// the value is not a string.
1786 std::string Record::getValueAsString(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 (StringInit *SI = dynamic_cast<StringInit*>(R->getValue()))
1793 return SI->getValue();
1794 throw "Record `" + getName() + "', field `" + FieldName.str() +
1795 "' does not have a string initializer!";
1798 /// getValueAsBitsInit - This method looks up the specified field and returns
1799 /// its value as a BitsInit, throwing an exception if the field does not exist
1800 /// or if the value is not the right type.
1802 BitsInit *Record::getValueAsBitsInit(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 (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1810 throw "Record `" + getName() + "', field `" + FieldName.str() +
1811 "' does not have a BitsInit initializer!";
1814 /// getValueAsListInit - This method looks up the specified field and returns
1815 /// its value as a ListInit, throwing an exception if the field does not exist
1816 /// or if the value is not the right type.
1818 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1819 const RecordVal *R = getValue(FieldName);
1820 if (R == 0 || R->getValue() == 0)
1821 throw "Record `" + getName() + "' does not have a field named `" +
1822 FieldName.str() + "'!\n";
1824 if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1826 throw "Record `" + getName() + "', field `" + FieldName.str() +
1827 "' does not have a list initializer!";
1830 /// getValueAsListOfDefs - This method looks up the specified field and returns
1831 /// its value as a vector of records, throwing an exception if the field does
1832 /// not exist or if the value is not the right type.
1834 std::vector<Record*>
1835 Record::getValueAsListOfDefs(StringRef FieldName) const {
1836 ListInit *List = getValueAsListInit(FieldName);
1837 std::vector<Record*> Defs;
1838 for (unsigned i = 0; i < List->getSize(); i++) {
1839 if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1840 Defs.push_back(DI->getDef());
1842 throw "Record `" + getName() + "', field `" + FieldName.str() +
1843 "' list is not entirely DefInit!";
1849 /// getValueAsInt - This method looks up the specified field and returns its
1850 /// value as an int64_t, throwing an exception if the field does not exist or if
1851 /// the value is not the right type.
1853 int64_t Record::getValueAsInt(StringRef FieldName) const {
1854 const RecordVal *R = getValue(FieldName);
1855 if (R == 0 || R->getValue() == 0)
1856 throw "Record `" + getName() + "' does not have a field named `" +
1857 FieldName.str() + "'!\n";
1859 if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1860 return II->getValue();
1861 throw "Record `" + getName() + "', field `" + FieldName.str() +
1862 "' does not have an int initializer!";
1865 /// getValueAsListOfInts - This method looks up the specified field and returns
1866 /// its value as a vector of integers, throwing an exception if the field does
1867 /// not exist or if the value is not the right type.
1869 std::vector<int64_t>
1870 Record::getValueAsListOfInts(StringRef FieldName) const {
1871 ListInit *List = getValueAsListInit(FieldName);
1872 std::vector<int64_t> Ints;
1873 for (unsigned i = 0; i < List->getSize(); i++) {
1874 if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1875 Ints.push_back(II->getValue());
1877 throw "Record `" + getName() + "', field `" + FieldName.str() +
1878 "' does not have a list of ints initializer!";
1884 /// getValueAsListOfStrings - This method looks up the specified field and
1885 /// returns its value as a vector of strings, throwing an exception if the
1886 /// field does not exist or if the value is not the right type.
1888 std::vector<std::string>
1889 Record::getValueAsListOfStrings(StringRef FieldName) const {
1890 ListInit *List = getValueAsListInit(FieldName);
1891 std::vector<std::string> Strings;
1892 for (unsigned i = 0; i < List->getSize(); i++) {
1893 if (StringInit *II = dynamic_cast<StringInit*>(List->getElement(i))) {
1894 Strings.push_back(II->getValue());
1896 throw "Record `" + getName() + "', field `" + FieldName.str() +
1897 "' does not have a list of strings initializer!";
1903 /// getValueAsDef - This method looks up the specified field and returns its
1904 /// value as a Record, throwing an exception if the field does not exist or if
1905 /// the value is not the right type.
1907 Record *Record::getValueAsDef(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 (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1914 return DI->getDef();
1915 throw "Record `" + getName() + "', field `" + FieldName.str() +
1916 "' does not have a def initializer!";
1919 /// getValueAsBit - This method looks up the specified field and returns its
1920 /// value as a bit, throwing an exception if the field does not exist or if
1921 /// the value is not the right type.
1923 bool Record::getValueAsBit(StringRef FieldName) const {
1924 const RecordVal *R = getValue(FieldName);
1925 if (R == 0 || R->getValue() == 0)
1926 throw "Record `" + getName() + "' does not have a field named `" +
1927 FieldName.str() + "'!\n";
1929 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1930 return BI->getValue();
1931 throw "Record `" + getName() + "', field `" + FieldName.str() +
1932 "' does not have a bit initializer!";
1935 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1936 const RecordVal *R = getValue(FieldName);
1937 if (R == 0 || R->getValue() == 0)
1938 throw "Record `" + getName() + "' does not have a field named `" +
1939 FieldName.str() + "'!\n";
1941 if (R->getValue() == UnsetInit::get()) {
1946 if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1947 return BI->getValue();
1948 throw "Record `" + getName() + "', field `" + FieldName.str() +
1949 "' does not have a bit initializer!";
1952 /// getValueAsDag - This method looks up the specified field and returns its
1953 /// value as an Dag, throwing an exception if the field does not exist or if
1954 /// the value is not the right type.
1956 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1957 const RecordVal *R = getValue(FieldName);
1958 if (R == 0 || R->getValue() == 0)
1959 throw "Record `" + getName() + "' does not have a field named `" +
1960 FieldName.str() + "'!\n";
1962 if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1964 throw "Record `" + getName() + "', field `" + FieldName.str() +
1965 "' does not have a dag initializer!";
1969 void MultiClass::dump() const {
1970 errs() << "Record:\n";
1973 errs() << "Defs:\n";
1974 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1975 rend = DefPrototypes.end();
1983 void RecordKeeper::dump() const { errs() << *this; }
1985 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1986 OS << "------------- Classes -----------------\n";
1987 const std::map<std::string, Record*> &Classes = RK.getClasses();
1988 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1989 E = Classes.end(); I != E; ++I)
1990 OS << "class " << *I->second;
1992 OS << "------------- Defs -----------------\n";
1993 const std::map<std::string, Record*> &Defs = RK.getDefs();
1994 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1995 E = Defs.end(); I != E; ++I)
1996 OS << "def " << *I->second;
2001 /// getAllDerivedDefinitions - This method returns all concrete definitions
2002 /// that derive from the specified class name. If a class with the specified
2003 /// name does not exist, an error is printed and true is returned.
2004 std::vector<Record*>
2005 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
2006 Record *Class = getClass(ClassName);
2008 throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
2010 std::vector<Record*> Defs;
2011 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
2012 E = getDefs().end(); I != E; ++I)
2013 if (I->second->isSubClassOf(Class))
2014 Defs.push_back(I->second);
2019 /// QualifyName - Return an Init with a qualifier prefix referring
2020 /// to CurRec's name.
2021 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2022 Init *Name, const std::string &Scoper) {
2023 RecTy *Type = dynamic_cast<TypedInit *>(Name)->getType();
2025 BinOpInit *NewName =
2026 BinOpInit::get(BinOpInit::STRCONCAT,
2027 BinOpInit::get(BinOpInit::STRCONCAT,
2028 CurRec.getNameInit(),
2029 StringInit::get(Scoper),
2030 Type)->Fold(&CurRec, CurMultiClass),
2034 if (CurMultiClass && Scoper != "::") {
2036 BinOpInit::get(BinOpInit::STRCONCAT,
2037 BinOpInit::get(BinOpInit::STRCONCAT,
2038 CurMultiClass->Rec.getNameInit(),
2039 StringInit::get("::"),
2040 Type)->Fold(&CurRec, CurMultiClass),
2041 NewName->Fold(&CurRec, CurMultiClass),
2045 return NewName->Fold(&CurRec, CurMultiClass);
2048 /// QualifyName - Return an Init with a qualifier prefix referring
2049 /// to CurRec's name.
2050 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2051 const std::string &Name,
2052 const std::string &Scoper) {
2053 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);