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]);
620 PrintFatalError("Expected record in list!");
624 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
625 std::vector<Init*> Resolved;
626 Resolved.reserve(getSize());
627 bool Changed = false;
629 for (unsigned i = 0, e = getSize(); i != e; ++i) {
631 Init *CurElt = getElement(i);
635 CurElt = CurElt->resolveReferences(R, RV);
636 Changed |= E != CurElt;
637 } while (E != CurElt);
638 Resolved.push_back(E);
642 return ListInit::get(Resolved, getType());
643 return const_cast<ListInit *>(this);
646 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
647 unsigned Elt) const {
648 if (Elt >= getSize())
649 return 0; // Out of range reference.
650 Init *E = getElement(Elt);
651 // If the element is set to some value, or if we are resolving a reference
652 // to a specific variable and that variable is explicitly unset, then
653 // replace the VarListElementInit with it.
654 if (IRV || !isa<UnsetInit>(E))
659 std::string ListInit::getAsString() const {
660 std::string Result = "[";
661 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
662 if (i) Result += ", ";
663 Result += Values[i]->getAsString();
668 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
669 unsigned Elt) const {
670 Init *Resolved = resolveReferences(R, IRV);
671 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
673 Resolved = OResolved->Fold(&R, 0);
676 if (Resolved != this) {
677 TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
678 assert(Typed && "Expected typed init for list reference");
680 Init *New = Typed->resolveListElementReference(R, IRV, Elt);
683 return VarListElementInit::get(Typed, Elt);
690 Init *OpInit::getBit(unsigned Bit) const {
691 if (getType() == BitRecTy::get())
692 return const_cast<OpInit*>(this);
693 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
696 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
697 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
699 typedef DenseMap<Key, UnOpInit *> Pool;
702 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
704 UnOpInit *&I = ThePool[TheKey];
705 if (!I) I = new UnOpInit(opc, lhs, Type);
709 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
710 switch (getOpcode()) {
712 if (getType()->getAsString() == "string") {
713 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
716 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
717 return StringInit::get(LHSd->getDef()->getName());
719 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
720 return StringInit::get(LHSi->getAsString());
722 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
723 std::string Name = LHSs->getValue();
725 // From TGParser::ParseIDValue
727 if (const RecordVal *RV = CurRec->getValue(Name)) {
728 if (RV->getType() != getType())
729 PrintFatalError("type mismatch in cast");
730 return VarInit::get(Name, RV->getType());
733 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
736 if (CurRec->isTemplateArg(TemplateArgName)) {
737 const RecordVal *RV = CurRec->getValue(TemplateArgName);
738 assert(RV && "Template arg doesn't exist??");
740 if (RV->getType() != getType())
741 PrintFatalError("type mismatch in cast");
743 return VarInit::get(TemplateArgName, RV->getType());
748 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
750 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
751 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
752 assert(RV && "Template arg doesn't exist??");
754 if (RV->getType() != getType())
755 PrintFatalError("type mismatch in cast");
757 return VarInit::get(MCName, RV->getType());
761 if (Record *D = (CurRec->getRecords()).getDef(Name))
762 return DefInit::get(D);
764 PrintFatalError(CurRec->getLoc(),
765 "Undefined reference:'" + Name + "'\n");
771 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
772 if (LHSl->getSize() == 0) {
773 assert(0 && "Empty list in car");
776 return LHSl->getElement(0);
781 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
782 if (LHSl->getSize() == 0) {
783 assert(0 && "Empty list in cdr");
786 // Note the +1. We can't just pass the result of getValues()
788 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
789 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
791 ListInit::get(ArrayRef<Init *>(begin, end - begin),
798 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
799 if (LHSl->getSize() == 0) {
800 return IntInit::get(1);
802 return IntInit::get(0);
805 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
806 if (LHSs->getValue().empty()) {
807 return IntInit::get(1);
809 return IntInit::get(0);
816 return const_cast<UnOpInit *>(this);
819 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
820 Init *lhs = LHS->resolveReferences(R, RV);
823 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
827 std::string UnOpInit::getAsString() const {
830 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
831 case HEAD: Result = "!head"; break;
832 case TAIL: Result = "!tail"; break;
833 case EMPTY: Result = "!empty"; break;
835 return Result + "(" + LHS->getAsString() + ")";
838 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
839 Init *rhs, RecTy *Type) {
841 std::pair<std::pair<unsigned, Init *>, Init *>,
845 typedef DenseMap<Key, BinOpInit *> Pool;
848 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
851 BinOpInit *&I = ThePool[TheKey];
852 if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
856 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
857 switch (getOpcode()) {
859 DagInit *LHSs = dyn_cast<DagInit>(LHS);
860 DagInit *RHSs = dyn_cast<DagInit>(RHS);
862 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
863 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
864 if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
865 PrintFatalError("Concated Dag operators do not match!");
866 std::vector<Init*> Args;
867 std::vector<std::string> ArgNames;
868 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
869 Args.push_back(LHSs->getArg(i));
870 ArgNames.push_back(LHSs->getArgName(i));
872 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
873 Args.push_back(RHSs->getArg(i));
874 ArgNames.push_back(RHSs->getArgName(i));
876 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
881 StringInit *LHSs = dyn_cast<StringInit>(LHS);
882 StringInit *RHSs = dyn_cast<StringInit>(RHS);
884 return StringInit::get(LHSs->getValue() + RHSs->getValue());
888 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
889 // to string objects.
891 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
893 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
896 return IntInit::get(L->getValue() == R->getValue());
898 StringInit *LHSs = dyn_cast<StringInit>(LHS);
899 StringInit *RHSs = dyn_cast<StringInit>(RHS);
901 // Make sure we've resolved
903 return IntInit::get(LHSs->getValue() == RHSs->getValue());
910 IntInit *LHSi = dyn_cast<IntInit>(LHS);
911 IntInit *RHSi = dyn_cast<IntInit>(RHS);
913 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
915 switch (getOpcode()) {
916 default: llvm_unreachable("Bad opcode!");
917 case SHL: Result = LHSv << RHSv; break;
918 case SRA: Result = LHSv >> RHSv; break;
919 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
921 return IntInit::get(Result);
926 return const_cast<BinOpInit *>(this);
929 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
930 Init *lhs = LHS->resolveReferences(R, RV);
931 Init *rhs = RHS->resolveReferences(R, RV);
933 if (LHS != lhs || RHS != rhs)
934 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
938 std::string BinOpInit::getAsString() const {
941 case CONCAT: Result = "!con"; break;
942 case SHL: Result = "!shl"; break;
943 case SRA: Result = "!sra"; break;
944 case SRL: Result = "!srl"; break;
945 case EQ: Result = "!eq"; break;
946 case STRCONCAT: Result = "!strconcat"; break;
948 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
951 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
952 Init *mhs, Init *rhs,
956 std::pair<std::pair<unsigned, RecTy *>, Init *>,
962 typedef DenseMap<Key, TernOpInit *> Pool;
965 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
971 TernOpInit *&I = ThePool[TheKey];
972 if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
976 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
977 Record *CurRec, MultiClass *CurMultiClass);
979 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
980 RecTy *Type, Record *CurRec,
981 MultiClass *CurMultiClass) {
982 std::vector<Init *> NewOperands;
984 TypedInit *TArg = dyn_cast<TypedInit>(Arg);
986 // If this is a dag, recurse
987 if (TArg && TArg->getType()->getAsString() == "dag") {
988 Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
989 CurRec, CurMultiClass);
997 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
998 OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
1001 Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1002 Type, CurRec, CurMultiClass);
1004 NewOperands.push_back(Result);
1006 NewOperands.push_back(Arg);
1008 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1009 NewOperands.push_back(Arg);
1011 NewOperands.push_back(RHSo->getOperand(i));
1015 // Now run the operator and use its result as the new leaf
1016 const OpInit *NewOp = RHSo->clone(NewOperands);
1017 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1018 if (NewVal != NewOp)
1024 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1025 Record *CurRec, MultiClass *CurMultiClass) {
1026 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1027 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1029 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1032 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
1035 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
1038 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
1040 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
1042 Init *Val = MHSd->getOperator();
1043 Init *Result = EvaluateOperation(RHSo, LHS, Val,
1044 Type, CurRec, CurMultiClass);
1049 std::vector<std::pair<Init *, std::string> > args;
1050 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1052 std::string ArgName;
1053 Arg = MHSd->getArg(i);
1054 ArgName = MHSd->getArgName(i);
1057 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1058 CurRec, CurMultiClass);
1063 // TODO: Process arg names
1064 args.push_back(std::make_pair(Arg, ArgName));
1067 return DagInit::get(Val, "", args);
1070 std::vector<Init *> NewOperands;
1071 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1073 for (std::vector<Init *>::iterator li = NewList.begin(),
1074 liend = NewList.end();
1078 NewOperands.clear();
1079 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1080 // First, replace the foreach variable with the list item
1081 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1082 NewOperands.push_back(Item);
1084 NewOperands.push_back(RHSo->getOperand(i));
1088 // Now run the operator and use its result as the new list item
1089 const OpInit *NewOp = RHSo->clone(NewOperands);
1090 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1091 if (NewItem != NewOp)
1094 return ListInit::get(NewList, MHSl->getType());
1100 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1101 switch (getOpcode()) {
1103 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1104 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1105 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1107 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1108 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1109 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1111 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1112 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1113 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1115 if ((LHSd && MHSd && RHSd)
1116 || (LHSv && MHSv && RHSv)
1117 || (LHSs && MHSs && RHSs)) {
1119 Record *Val = RHSd->getDef();
1120 if (LHSd->getAsString() == RHSd->getAsString()) {
1121 Val = MHSd->getDef();
1123 return DefInit::get(Val);
1126 std::string Val = RHSv->getName();
1127 if (LHSv->getAsString() == RHSv->getAsString()) {
1128 Val = MHSv->getName();
1130 return VarInit::get(Val, getType());
1133 std::string Val = RHSs->getValue();
1135 std::string::size_type found;
1136 std::string::size_type idx = 0;
1138 found = Val.find(LHSs->getValue(), idx);
1139 if (found != std::string::npos) {
1140 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1142 idx = found + MHSs->getValue().size();
1143 } while (found != std::string::npos);
1145 return StringInit::get(Val);
1152 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1153 CurRec, CurMultiClass);
1161 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1162 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1163 LHSi = dyn_cast<IntInit>(I);
1165 if (LHSi->getValue()) {
1175 return const_cast<TernOpInit *>(this);
1178 Init *TernOpInit::resolveReferences(Record &R,
1179 const RecordVal *RV) const {
1180 Init *lhs = LHS->resolveReferences(R, RV);
1182 if (Opc == IF && lhs != LHS) {
1183 IntInit *Value = dyn_cast<IntInit>(lhs);
1184 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1185 Value = dyn_cast<IntInit>(I);
1188 if (Value->getValue()) {
1189 Init *mhs = MHS->resolveReferences(R, RV);
1190 return (TernOpInit::get(getOpcode(), lhs, mhs,
1191 RHS, getType()))->Fold(&R, 0);
1193 Init *rhs = RHS->resolveReferences(R, RV);
1194 return (TernOpInit::get(getOpcode(), lhs, MHS,
1195 rhs, getType()))->Fold(&R, 0);
1200 Init *mhs = MHS->resolveReferences(R, RV);
1201 Init *rhs = RHS->resolveReferences(R, RV);
1203 if (LHS != lhs || MHS != mhs || RHS != rhs)
1204 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1205 getType()))->Fold(&R, 0);
1209 std::string TernOpInit::getAsString() const {
1212 case SUBST: Result = "!subst"; break;
1213 case FOREACH: Result = "!foreach"; break;
1214 case IF: Result = "!if"; break;
1216 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1217 + RHS->getAsString() + ")";
1220 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1221 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1222 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1223 return Field->getType();
1228 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1229 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1230 if (T == 0) return 0; // Cannot subscript a non-bits variable.
1231 unsigned NumBits = T->getNumBits();
1233 SmallVector<Init *, 16> NewBits(Bits.size());
1234 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1235 if (Bits[i] >= NumBits)
1238 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1240 return BitsInit::get(NewBits);
1244 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1245 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1246 if (T == 0) return 0; // Cannot subscript a non-list variable.
1248 if (Elements.size() == 1)
1249 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1251 std::vector<Init*> ListInits;
1252 ListInits.reserve(Elements.size());
1253 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1254 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1256 return ListInit::get(ListInits, T);
1260 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1261 Init *Value = StringInit::get(VN);
1262 return VarInit::get(Value, T);
1265 VarInit *VarInit::get(Init *VN, RecTy *T) {
1266 typedef std::pair<RecTy *, Init *> Key;
1267 typedef DenseMap<Key, VarInit *> Pool;
1268 static Pool ThePool;
1270 Key TheKey(std::make_pair(T, VN));
1272 VarInit *&I = ThePool[TheKey];
1273 if (!I) I = new VarInit(VN, T);
1277 const std::string &VarInit::getName() const {
1278 StringInit *NameString = dyn_cast<StringInit>(getNameInit());
1279 assert(NameString && "VarInit name is not a string!");
1280 return NameString->getValue();
1283 Init *VarInit::getBit(unsigned Bit) const {
1284 if (getType() == BitRecTy::get())
1285 return const_cast<VarInit*>(this);
1286 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1289 Init *VarInit::resolveListElementReference(Record &R,
1290 const RecordVal *IRV,
1291 unsigned Elt) const {
1292 if (R.isTemplateArg(getNameInit())) return 0;
1293 if (IRV && IRV->getNameInit() != getNameInit()) return 0;
1295 RecordVal *RV = R.getValue(getNameInit());
1296 assert(RV && "Reference to a non-existent variable?");
1297 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1299 TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
1300 assert(VI && "Invalid list element!");
1301 return VarListElementInit::get(VI, Elt);
1304 if (Elt >= LI->getSize())
1305 return 0; // Out of range reference.
1306 Init *E = LI->getElement(Elt);
1307 // If the element is set to some value, or if we are resolving a reference
1308 // to a specific variable and that variable is explicitly unset, then
1309 // replace the VarListElementInit with it.
1310 if (IRV || !isa<UnsetInit>(E))
1316 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1317 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1318 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1319 return RV->getType();
1323 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1324 const std::string &FieldName) const {
1325 if (isa<RecordRecTy>(getType()))
1326 if (const RecordVal *Val = R.getValue(VarName)) {
1327 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1329 Init *TheInit = Val->getValue();
1330 assert(TheInit != this && "Infinite loop detected!");
1331 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1339 /// resolveReferences - This method is used by classes that refer to other
1340 /// variables which may not be defined at the time the expression is formed.
1341 /// If a value is set for the variable later, this method will be called on
1342 /// users of the value to allow the value to propagate out.
1344 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1345 if (RecordVal *Val = R.getValue(VarName))
1346 if (RV == Val || (RV == 0 && !isa<UnsetInit>(Val->getValue())))
1347 return Val->getValue();
1348 return const_cast<VarInit *>(this);
1351 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1352 typedef std::pair<TypedInit *, unsigned> Key;
1353 typedef DenseMap<Key, VarBitInit *> Pool;
1355 static Pool ThePool;
1357 Key TheKey(std::make_pair(T, B));
1359 VarBitInit *&I = ThePool[TheKey];
1360 if (!I) I = new VarBitInit(T, B);
1364 std::string VarBitInit::getAsString() const {
1365 return TI->getAsString() + "{" + utostr(Bit) + "}";
1368 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1369 Init *I = TI->resolveReferences(R, RV);
1371 return I->getBit(getBitNum());
1373 return const_cast<VarBitInit*>(this);
1376 VarListElementInit *VarListElementInit::get(TypedInit *T,
1378 typedef std::pair<TypedInit *, unsigned> Key;
1379 typedef DenseMap<Key, VarListElementInit *> Pool;
1381 static Pool ThePool;
1383 Key TheKey(std::make_pair(T, E));
1385 VarListElementInit *&I = ThePool[TheKey];
1386 if (!I) I = new VarListElementInit(T, E);
1390 std::string VarListElementInit::getAsString() const {
1391 return TI->getAsString() + "[" + utostr(Element) + "]";
1395 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1396 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1399 return const_cast<VarListElementInit *>(this);
1402 Init *VarListElementInit::getBit(unsigned Bit) const {
1403 if (getType() == BitRecTy::get())
1404 return const_cast<VarListElementInit*>(this);
1405 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1408 Init *VarListElementInit:: resolveListElementReference(Record &R,
1409 const RecordVal *RV,
1410 unsigned Elt) const {
1411 Init *Result = TI->resolveListElementReference(R, RV, Element);
1414 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1415 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1416 if (Result2) return Result2;
1417 return new VarListElementInit(TInit, Elt);
1425 DefInit *DefInit::get(Record *R) {
1426 return R->getDefInit();
1429 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1430 if (const RecordVal *RV = Def->getValue(FieldName))
1431 return RV->getType();
1435 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1436 const std::string &FieldName) const {
1437 return Def->getValue(FieldName)->getValue();
1441 std::string DefInit::getAsString() const {
1442 return Def->getName();
1445 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1446 typedef std::pair<Init *, TableGenStringKey> Key;
1447 typedef DenseMap<Key, FieldInit *> Pool;
1448 static Pool ThePool;
1450 Key TheKey(std::make_pair(R, FN));
1452 FieldInit *&I = ThePool[TheKey];
1453 if (!I) I = new FieldInit(R, FN);
1457 Init *FieldInit::getBit(unsigned Bit) const {
1458 if (getType() == BitRecTy::get())
1459 return const_cast<FieldInit*>(this);
1460 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1463 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1464 unsigned Elt) const {
1465 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1466 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1467 if (Elt >= LI->getSize()) return 0;
1468 Init *E = LI->getElement(Elt);
1470 // If the element is set to some value, or if we are resolving a
1471 // reference to a specific variable and that variable is explicitly
1472 // unset, then replace the VarListElementInit with it.
1473 if (RV || !isa<UnsetInit>(E))
1479 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1480 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1482 Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1484 Init *BVR = BitsVal->resolveReferences(R, RV);
1485 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1488 if (NewRec != Rec) {
1489 return FieldInit::get(NewRec, FieldName);
1491 return const_cast<FieldInit *>(this);
1494 void ProfileDagInit(FoldingSetNodeID &ID,
1496 const std::string &VN,
1497 ArrayRef<Init *> ArgRange,
1498 ArrayRef<std::string> NameRange) {
1502 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1503 ArrayRef<std::string>::iterator Name = NameRange.begin();
1504 while (Arg != ArgRange.end()) {
1505 assert(Name != NameRange.end() && "Arg name underflow!");
1506 ID.AddPointer(*Arg++);
1507 ID.AddString(*Name++);
1509 assert(Name == NameRange.end() && "Arg name overflow!");
1513 DagInit::get(Init *V, const std::string &VN,
1514 ArrayRef<Init *> ArgRange,
1515 ArrayRef<std::string> NameRange) {
1516 typedef FoldingSet<DagInit> Pool;
1517 static Pool ThePool;
1519 FoldingSetNodeID ID;
1520 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1523 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1526 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1527 ThePool.InsertNode(I, IP);
1533 DagInit::get(Init *V, const std::string &VN,
1534 const std::vector<std::pair<Init*, std::string> > &args) {
1535 typedef std::pair<Init*, std::string> PairType;
1537 std::vector<Init *> Args;
1538 std::vector<std::string> Names;
1540 for (std::vector<PairType>::const_iterator i = args.begin(),
1544 Args.push_back(i->first);
1545 Names.push_back(i->second);
1548 return DagInit::get(V, VN, Args, Names);
1551 void DagInit::Profile(FoldingSetNodeID &ID) const {
1552 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1555 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1556 std::vector<Init*> NewArgs;
1557 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1558 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1560 Init *Op = Val->resolveReferences(R, RV);
1562 if (Args != NewArgs || Op != Val)
1563 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1565 return const_cast<DagInit *>(this);
1569 std::string DagInit::getAsString() const {
1570 std::string Result = "(" + Val->getAsString();
1571 if (!ValName.empty())
1572 Result += ":" + ValName;
1574 Result += " " + Args[0]->getAsString();
1575 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1576 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1577 Result += ", " + Args[i]->getAsString();
1578 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1581 return Result + ")";
1585 //===----------------------------------------------------------------------===//
1586 // Other implementations
1587 //===----------------------------------------------------------------------===//
1589 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1590 : Name(N), Ty(T), Prefix(P) {
1591 Value = Ty->convertValue(UnsetInit::get());
1592 assert(Value && "Cannot create unset value for current type!");
1595 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1596 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1597 Value = Ty->convertValue(UnsetInit::get());
1598 assert(Value && "Cannot create unset value for current type!");
1601 const std::string &RecordVal::getName() const {
1602 StringInit *NameString = dyn_cast<StringInit>(Name);
1603 assert(NameString && "RecordVal name is not a string!");
1604 return NameString->getValue();
1607 void RecordVal::dump() const { errs() << *this; }
1609 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1610 if (getPrefix()) OS << "field ";
1611 OS << *getType() << " " << getNameInitAsString();
1614 OS << " = " << *getValue();
1616 if (PrintSem) OS << ";\n";
1619 unsigned Record::LastID = 0;
1621 void Record::init() {
1624 // Every record potentially has a def at the top. This value is
1625 // replaced with the top-level def name at instantiation time.
1626 RecordVal DN("NAME", StringRecTy::get(), 0);
1630 void Record::checkName() {
1631 // Ensure the record name has string type.
1632 const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
1633 assert(TypedName && "Record name is not typed!");
1634 RecTy *Type = TypedName->getType();
1635 if (!isa<StringRecTy>(Type))
1636 PrintFatalError(getLoc(), "Record name is not a string!");
1639 DefInit *Record::getDefInit() {
1641 TheInit = new DefInit(this, new RecordRecTy(this));
1645 const std::string &Record::getName() const {
1646 const StringInit *NameString = dyn_cast<StringInit>(Name);
1647 assert(NameString && "Record name is not a string!");
1648 return NameString->getValue();
1651 void Record::setName(Init *NewName) {
1652 if (TrackedRecords.getDef(Name->getAsUnquotedString()) == this) {
1653 TrackedRecords.removeDef(Name->getAsUnquotedString());
1654 TrackedRecords.addDef(this);
1655 } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) == this) {
1656 TrackedRecords.removeClass(Name->getAsUnquotedString());
1657 TrackedRecords.addClass(this);
1658 } // Otherwise this isn't yet registered.
1661 // DO NOT resolve record values to the name at this point because
1662 // there might be default values for arguments of this def. Those
1663 // arguments might not have been resolved yet so we don't want to
1664 // prematurely assume values for those arguments were not passed to
1667 // Nonetheless, it may be that some of this Record's values
1668 // reference the record name. Indeed, the reason for having the
1669 // record name be an Init is to provide this flexibility. The extra
1670 // resolve steps after completely instantiating defs takes care of
1671 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1674 void Record::setName(const std::string &Name) {
1675 setName(StringInit::get(Name));
1678 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1679 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1681 void Record::resolveReferencesTo(const RecordVal *RV) {
1682 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1683 if (RV == &Values[i]) // Skip resolve the same field as the given one
1685 if (Init *V = Values[i].getValue())
1686 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1687 PrintFatalError(getLoc(), "Invalid value is found when setting '"
1688 + Values[i].getNameInitAsString()
1689 + "' after resolving references"
1690 + (RV ? " against '" + RV->getNameInitAsString()
1692 + RV->getValue()->getAsUnquotedString() + ")"
1696 Init *OldName = getNameInit();
1697 Init *NewName = Name->resolveReferences(*this, RV);
1698 if (NewName != OldName) {
1699 // Re-register with RecordKeeper.
1704 void Record::dump() const { errs() << *this; }
1706 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1707 OS << R.getNameInitAsString();
1709 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1710 if (!TArgs.empty()) {
1712 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1714 const RecordVal *RV = R.getValue(TArgs[i]);
1715 assert(RV && "Template argument record not found??");
1716 RV->print(OS, false);
1722 const std::vector<Record*> &SC = R.getSuperClasses();
1725 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1726 OS << " " << SC[i]->getNameInitAsString();
1730 const std::vector<RecordVal> &Vals = R.getValues();
1731 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1732 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1734 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1735 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1741 /// getValueInit - Return the initializer for a value with the specified name,
1742 /// or abort if the field does not exist.
1744 Init *Record::getValueInit(StringRef FieldName) const {
1745 const RecordVal *R = getValue(FieldName);
1746 if (R == 0 || R->getValue() == 0)
1747 PrintFatalError(getLoc(), "Record `" + getName() +
1748 "' does not have a field named `" + FieldName.str() + "'!\n");
1749 return R->getValue();
1753 /// getValueAsString - This method looks up the specified field and returns its
1754 /// value as a string, aborts if the field does not exist or if
1755 /// the value is not a string.
1757 std::string Record::getValueAsString(StringRef FieldName) const {
1758 const RecordVal *R = getValue(FieldName);
1759 if (R == 0 || R->getValue() == 0)
1760 PrintFatalError(getLoc(), "Record `" + getName() +
1761 "' does not have a field named `" + FieldName.str() + "'!\n");
1763 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1764 return SI->getValue();
1765 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1766 FieldName.str() + "' does not have a string initializer!");
1769 /// getValueAsBitsInit - This method looks up the specified field and returns
1770 /// its value as a BitsInit, aborts if the field does not exist or if
1771 /// the value is not the right type.
1773 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1774 const RecordVal *R = getValue(FieldName);
1775 if (R == 0 || R->getValue() == 0)
1776 PrintFatalError(getLoc(), "Record `" + getName() +
1777 "' does not have a field named `" + FieldName.str() + "'!\n");
1779 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1781 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1782 FieldName.str() + "' does not have a BitsInit initializer!");
1785 /// getValueAsListInit - This method looks up the specified field and returns
1786 /// its value as a ListInit, aborting if the field does not exist or if
1787 /// the value is not the right type.
1789 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1790 const RecordVal *R = getValue(FieldName);
1791 if (R == 0 || R->getValue() == 0)
1792 PrintFatalError(getLoc(), "Record `" + getName() +
1793 "' does not have a field named `" + FieldName.str() + "'!\n");
1795 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1797 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1798 FieldName.str() + "' does not have a list initializer!");
1801 /// getValueAsListOfDefs - This method looks up the specified field and returns
1802 /// its value as a vector of records, aborting if the field does not exist
1803 /// or if the value is not the right type.
1805 std::vector<Record*>
1806 Record::getValueAsListOfDefs(StringRef FieldName) const {
1807 ListInit *List = getValueAsListInit(FieldName);
1808 std::vector<Record*> Defs;
1809 for (unsigned i = 0; i < List->getSize(); i++) {
1810 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
1811 Defs.push_back(DI->getDef());
1813 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1814 FieldName.str() + "' list is not entirely DefInit!");
1820 /// getValueAsInt - This method looks up the specified field and returns its
1821 /// value as an int64_t, aborting if the field does not exist or if the value
1822 /// is not the right type.
1824 int64_t Record::getValueAsInt(StringRef FieldName) const {
1825 const RecordVal *R = getValue(FieldName);
1826 if (R == 0 || R->getValue() == 0)
1827 PrintFatalError(getLoc(), "Record `" + getName() +
1828 "' does not have a field named `" + FieldName.str() + "'!\n");
1830 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1831 return II->getValue();
1832 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1833 FieldName.str() + "' does not have an int initializer!");
1836 /// getValueAsListOfInts - This method looks up the specified field and returns
1837 /// its value as a vector of integers, aborting if the field does not exist or
1838 /// if the value is not the right type.
1840 std::vector<int64_t>
1841 Record::getValueAsListOfInts(StringRef FieldName) const {
1842 ListInit *List = getValueAsListInit(FieldName);
1843 std::vector<int64_t> Ints;
1844 for (unsigned i = 0; i < List->getSize(); i++) {
1845 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
1846 Ints.push_back(II->getValue());
1848 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1849 FieldName.str() + "' does not have a list of ints initializer!");
1855 /// getValueAsListOfStrings - This method looks up the specified field and
1856 /// returns its value as a vector of strings, aborting if the field does not
1857 /// exist or if the value is not the right type.
1859 std::vector<std::string>
1860 Record::getValueAsListOfStrings(StringRef FieldName) const {
1861 ListInit *List = getValueAsListInit(FieldName);
1862 std::vector<std::string> Strings;
1863 for (unsigned i = 0; i < List->getSize(); i++) {
1864 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
1865 Strings.push_back(II->getValue());
1867 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1868 FieldName.str() + "' does not have a list of strings initializer!");
1874 /// getValueAsDef - This method looks up the specified field and returns its
1875 /// value as a Record, aborting if the field does not exist or if the value
1876 /// is not the right type.
1878 Record *Record::getValueAsDef(StringRef FieldName) const {
1879 const RecordVal *R = getValue(FieldName);
1880 if (R == 0 || R->getValue() == 0)
1881 PrintFatalError(getLoc(), "Record `" + getName() +
1882 "' does not have a field named `" + FieldName.str() + "'!\n");
1884 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1885 return DI->getDef();
1886 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1887 FieldName.str() + "' does not have a def initializer!");
1890 /// getValueAsBit - This method looks up the specified field and returns its
1891 /// value as a bit, aborting if the field does not exist or if the value is
1892 /// not the right type.
1894 bool Record::getValueAsBit(StringRef FieldName) const {
1895 const RecordVal *R = getValue(FieldName);
1896 if (R == 0 || R->getValue() == 0)
1897 PrintFatalError(getLoc(), "Record `" + getName() +
1898 "' does not have a field named `" + FieldName.str() + "'!\n");
1900 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1901 return BI->getValue();
1902 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1903 FieldName.str() + "' does not have a bit initializer!");
1906 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1907 const RecordVal *R = getValue(FieldName);
1908 if (R == 0 || R->getValue() == 0)
1909 PrintFatalError(getLoc(), "Record `" + getName() +
1910 "' does not have a field named `" + FieldName.str() + "'!\n");
1912 if (R->getValue() == UnsetInit::get()) {
1917 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1918 return BI->getValue();
1919 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1920 FieldName.str() + "' does not have a bit initializer!");
1923 /// getValueAsDag - This method looks up the specified field and returns its
1924 /// value as an Dag, aborting if the field does not exist or if the value is
1925 /// not the right type.
1927 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1928 const RecordVal *R = getValue(FieldName);
1929 if (R == 0 || R->getValue() == 0)
1930 PrintFatalError(getLoc(), "Record `" + getName() +
1931 "' does not have a field named `" + FieldName.str() + "'!\n");
1933 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1935 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1936 FieldName.str() + "' does not have a dag initializer!");
1940 void MultiClass::dump() const {
1941 errs() << "Record:\n";
1944 errs() << "Defs:\n";
1945 for (RecordVector::const_iterator r = DefPrototypes.begin(),
1946 rend = DefPrototypes.end();
1954 void RecordKeeper::dump() const { errs() << *this; }
1956 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1957 OS << "------------- Classes -----------------\n";
1958 const std::map<std::string, Record*> &Classes = RK.getClasses();
1959 for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1960 E = Classes.end(); I != E; ++I)
1961 OS << "class " << *I->second;
1963 OS << "------------- Defs -----------------\n";
1964 const std::map<std::string, Record*> &Defs = RK.getDefs();
1965 for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1966 E = Defs.end(); I != E; ++I)
1967 OS << "def " << *I->second;
1972 /// getAllDerivedDefinitions - This method returns all concrete definitions
1973 /// that derive from the specified class name. If a class with the specified
1974 /// name does not exist, an error is printed and true is returned.
1975 std::vector<Record*>
1976 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1977 Record *Class = getClass(ClassName);
1979 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1981 std::vector<Record*> Defs;
1982 for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1983 E = getDefs().end(); I != E; ++I)
1984 if (I->second->isSubClassOf(Class))
1985 Defs.push_back(I->second);
1990 /// QualifyName - Return an Init with a qualifier prefix referring
1991 /// to CurRec's name.
1992 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1993 Init *Name, const std::string &Scoper) {
1994 RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
1996 BinOpInit *NewName =
1997 BinOpInit::get(BinOpInit::STRCONCAT,
1998 BinOpInit::get(BinOpInit::STRCONCAT,
1999 CurRec.getNameInit(),
2000 StringInit::get(Scoper),
2001 Type)->Fold(&CurRec, CurMultiClass),
2005 if (CurMultiClass && Scoper != "::") {
2007 BinOpInit::get(BinOpInit::STRCONCAT,
2008 BinOpInit::get(BinOpInit::STRCONCAT,
2009 CurMultiClass->Rec.getNameInit(),
2010 StringInit::get("::"),
2011 Type)->Fold(&CurRec, CurMultiClass),
2012 NewName->Fold(&CurRec, CurMultiClass),
2016 return NewName->Fold(&CurRec, CurMultiClass);
2019 /// QualifyName - Return an Init with a qualifier prefix referring
2020 /// to CurRec's name.
2021 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
2022 const std::string &Name,
2023 const std::string &Scoper) {
2024 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);