1 //===- Record.cpp - Record implementation ---------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the tablegen record classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/TableGen/Record.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/TableGen/Error.h"
29 //===----------------------------------------------------------------------===//
30 // std::string wrapper for DenseMap purposes
31 //===----------------------------------------------------------------------===//
35 /// TableGenStringKey - This is a wrapper for std::string suitable for
36 /// using as a key to a DenseMap. Because there isn't a particularly
37 /// good way to indicate tombstone or empty keys for strings, we want
38 /// to wrap std::string to indicate that this is a "special" string
39 /// not expected to take on certain values (those of the tombstone and
40 /// empty keys). This makes things a little safer as it clarifies
41 /// that DenseMap is really not appropriate for general strings.
43 class TableGenStringKey {
45 TableGenStringKey(const std::string &str) : data(str) {}
46 TableGenStringKey(const char *str) : data(str) {}
48 const std::string &str() const { return data; }
50 friend hash_code hash_value(const TableGenStringKey &Value) {
51 using llvm::hash_value;
52 return hash_value(Value.str());
58 /// Specialize DenseMapInfo for TableGenStringKey.
59 template<> struct DenseMapInfo<TableGenStringKey> {
60 static inline TableGenStringKey getEmptyKey() {
61 TableGenStringKey Empty("<<<EMPTY KEY>>>");
64 static inline TableGenStringKey getTombstoneKey() {
65 TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
68 static unsigned getHashValue(const TableGenStringKey& Val) {
69 using llvm::hash_value;
70 return hash_value(Val);
72 static bool isEqual(const TableGenStringKey& LHS,
73 const TableGenStringKey& RHS) {
74 return LHS.str() == RHS.str();
80 //===----------------------------------------------------------------------===//
81 // Type implementations
82 //===----------------------------------------------------------------------===//
84 BitRecTy BitRecTy::Shared;
85 IntRecTy IntRecTy::Shared;
86 StringRecTy StringRecTy::Shared;
87 DagRecTy DagRecTy::Shared;
89 void RecTy::anchor() { }
90 void RecTy::dump() const { print(errs()); }
92 ListRecTy *RecTy::getListTy() {
94 ListTy.reset(new ListRecTy(this));
98 bool RecTy::baseClassOf(const RecTy *RHS) const {
99 assert (RHS && "NULL pointer");
100 return Kind == RHS->getRecTyKind();
103 Init *BitRecTy::convertValue(BitsInit *BI) {
104 if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
105 return BI->getBit(0);
108 Init *BitRecTy::convertValue(IntInit *II) {
109 int64_t Val = II->getValue();
110 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
112 return BitInit::get(Val != 0);
115 Init *BitRecTy::convertValue(TypedInit *VI) {
116 RecTy *Ty = VI->getType();
117 if (isa<BitRecTy>(Ty))
118 return VI; // Accept variable if it is already of bit type!
119 if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
120 // Accept only bits<1> expression.
121 return BitsTy->getNumBits() == 1 ? VI : nullptr;
122 // Ternary !if can be converted to bit, but only if both sides are
123 // convertible to a bit.
124 if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
125 if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
127 if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
128 !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
136 if(RecTy::baseClassOf(RHS) || RHS->getRecTyKind() == IntRecTyKind)
138 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
139 return BitsTy->getNumBits() == 1;
143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
144 static std::vector<std::unique_ptr<BitsRecTy>> Shared;
145 if (Sz >= Shared.size())
146 Shared.resize(Sz + 1);
147 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
149 Ty.reset(new BitsRecTy(Sz));
153 std::string BitsRecTy::getAsString() const {
154 return "bits<" + utostr(Size) + ">";
157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
158 SmallVector<Init *, 16> NewBits(Size);
160 for (unsigned i = 0; i != Size; ++i)
161 NewBits[i] = UnsetInit::get();
163 return BitsInit::get(NewBits);
166 Init *BitsRecTy::convertValue(BitInit *UI) {
167 if (Size != 1) return nullptr; // Can only convert single bit.
168 return BitsInit::get(UI);
171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
172 /// the integer value.
173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
174 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
175 return (NumBits >= sizeof(Value) * 8) ||
176 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
179 /// convertValue from Int initializer to bits type: Split the integer up into the
180 /// appropriate bits.
182 Init *BitsRecTy::convertValue(IntInit *II) {
183 int64_t Value = II->getValue();
184 // Make sure this bitfield is large enough to hold the integer value.
185 if (!canFitInBitfield(Value, Size))
188 SmallVector<Init *, 16> NewBits(Size);
190 for (unsigned i = 0; i != Size; ++i)
191 NewBits[i] = BitInit::get(Value & (1LL << i));
193 return BitsInit::get(NewBits);
196 Init *BitsRecTy::convertValue(BitsInit *BI) {
197 // If the number of bits is right, return it. Otherwise we need to expand or
199 if (BI->getNumBits() == Size) return BI;
203 Init *BitsRecTy::convertValue(TypedInit *VI) {
204 if (Size == 1 && isa<BitRecTy>(VI->getType()))
205 return BitsInit::get(VI);
207 if (VI->getType()->typeIsConvertibleTo(this)) {
208 SmallVector<Init *, 16> NewBits(Size);
210 for (unsigned i = 0; i != Size; ++i)
211 NewBits[i] = VarBitInit::get(VI, i);
212 return BitsInit::get(NewBits);
218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
219 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
220 return cast<BitsRecTy>(RHS)->Size == Size;
221 RecTyKind kind = RHS->getRecTyKind();
222 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
225 Init *IntRecTy::convertValue(BitInit *BI) {
226 return IntInit::get(BI->getValue());
229 Init *IntRecTy::convertValue(BitsInit *BI) {
231 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
232 if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i)))
233 Result |= Bit->getValue() << i;
236 return IntInit::get(Result);
239 Init *IntRecTy::convertValue(TypedInit *TI) {
240 if (TI->getType()->typeIsConvertibleTo(this))
241 return TI; // Accept variable if already of the right type!
245 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
246 RecTyKind kind = RHS->getRecTyKind();
247 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
250 Init *StringRecTy::convertValue(UnOpInit *BO) {
251 if (BO->getOpcode() == UnOpInit::CAST) {
252 Init *L = BO->getOperand()->convertInitializerTo(this);
253 if (!L) return nullptr;
254 if (L != BO->getOperand())
255 return UnOpInit::get(UnOpInit::CAST, L, StringRecTy::get());
259 return convertValue((TypedInit*)BO);
262 Init *StringRecTy::convertValue(BinOpInit *BO) {
263 if (BO->getOpcode() == BinOpInit::STRCONCAT) {
264 Init *L = BO->getLHS()->convertInitializerTo(this);
265 Init *R = BO->getRHS()->convertInitializerTo(this);
266 if (!L || !R) return nullptr;
267 if (L != BO->getLHS() || R != BO->getRHS())
268 return BinOpInit::get(BinOpInit::STRCONCAT, L, R, StringRecTy::get());
272 return convertValue((TypedInit*)BO);
276 Init *StringRecTy::convertValue(TypedInit *TI) {
277 if (isa<StringRecTy>(TI->getType()))
278 return TI; // Accept variable if already of the right type!
282 std::string ListRecTy::getAsString() const {
283 return "list<" + Ty->getAsString() + ">";
286 Init *ListRecTy::convertValue(ListInit *LI) {
287 std::vector<Init*> Elements;
289 // Verify that all of the elements of the list are subclasses of the
290 // appropriate class!
291 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
292 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
293 Elements.push_back(CI);
297 if (!isa<ListRecTy>(LI->getType()))
300 return ListInit::get(Elements, this);
303 Init *ListRecTy::convertValue(TypedInit *TI) {
304 // Ensure that TI is compatible with our class.
305 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
306 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
311 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
312 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
313 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
317 Init *DagRecTy::convertValue(TypedInit *TI) {
318 if (TI->getType()->typeIsConvertibleTo(this))
323 Init *DagRecTy::convertValue(UnOpInit *BO) {
324 if (BO->getOpcode() == UnOpInit::CAST) {
325 Init *L = BO->getOperand()->convertInitializerTo(this);
326 if (!L) return nullptr;
327 if (L != BO->getOperand())
328 return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
334 Init *DagRecTy::convertValue(BinOpInit *BO) {
335 if (BO->getOpcode() == BinOpInit::CONCAT) {
336 Init *L = BO->getLHS()->convertInitializerTo(this);
337 Init *R = BO->getRHS()->convertInitializerTo(this);
338 if (!L || !R) return nullptr;
339 if (L != BO->getLHS() || R != BO->getRHS())
340 return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
346 RecordRecTy *RecordRecTy::get(Record *R) {
347 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
350 std::string RecordRecTy::getAsString() const {
351 return Rec->getName();
354 Init *RecordRecTy::convertValue(DefInit *DI) {
355 // Ensure that DI is a subclass of Rec.
356 if (!DI->getDef()->isSubClassOf(Rec))
361 Init *RecordRecTy::convertValue(TypedInit *TI) {
362 // Ensure that TI is compatible with Rec.
363 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
364 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
365 RRT->getRecord() == getRecord())
370 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
371 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
375 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
378 const std::vector<Record*> &SC = Rec->getSuperClasses();
379 for (unsigned i = 0, e = SC.size(); i != e; ++i)
380 if (RTy->getRecord()->isSubClassOf(SC[i]))
386 /// resolveTypes - Find a common type that T1 and T2 convert to.
387 /// Return null if no such type exists.
389 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
390 if (T1->typeIsConvertibleTo(T2))
392 if (T2->typeIsConvertibleTo(T1))
395 // If one is a Record type, check superclasses
396 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
397 // See if T2 inherits from a type T1 also inherits from
398 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
399 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
400 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
405 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
406 // See if T1 inherits from a type T2 also inherits from
407 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
408 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
409 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
418 //===----------------------------------------------------------------------===//
419 // Initializer implementations
420 //===----------------------------------------------------------------------===//
422 void Init::anchor() { }
423 void Init::dump() const { return print(errs()); }
425 void UnsetInit::anchor() { }
427 UnsetInit *UnsetInit::get() {
428 static UnsetInit TheInit;
432 void BitInit::anchor() { }
434 BitInit *BitInit::get(bool V) {
435 static BitInit True(true);
436 static BitInit False(false);
438 return V ? &True : &False;
442 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
443 ID.AddInteger(Range.size());
445 for (Init *I : Range)
449 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
450 static FoldingSet<BitsInit> ThePool;
451 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
454 ProfileBitsInit(ID, Range);
457 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
460 BitsInit *I = new BitsInit(Range);
461 ThePool.InsertNode(I, IP);
462 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
466 void BitsInit::Profile(FoldingSetNodeID &ID) const {
467 ProfileBitsInit(ID, Bits);
471 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
472 SmallVector<Init *, 16> NewBits(Bits.size());
474 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
475 if (Bits[i] >= getNumBits())
477 NewBits[i] = getBit(Bits[i]);
479 return BitsInit::get(NewBits);
482 std::string BitsInit::getAsString() const {
483 std::string Result = "{ ";
484 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
485 if (i) Result += ", ";
486 if (Init *Bit = getBit(e-i-1))
487 Result += Bit->getAsString();
491 return Result + " }";
494 // Fix bit initializer to preserve the behavior that bit reference from a unset
495 // bits initializer will resolve into VarBitInit to keep the field name and bit
496 // number used in targets with fixed insn length.
497 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
498 if (RV || !isa<UnsetInit>(After))
503 // resolveReferences - If there are any field references that refer to fields
504 // that have been filled in, we can propagate the values now.
506 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
507 bool Changed = false;
508 SmallVector<Init *, 16> NewBits(getNumBits());
510 Init *CachedInit = nullptr;
511 Init *CachedBitVar = nullptr;
512 bool CachedBitVarChanged = false;
514 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
515 Init *CurBit = Bits[i];
516 Init *CurBitVar = CurBit->getBitVar();
520 if (CurBitVar == CachedBitVar) {
521 if (CachedBitVarChanged) {
522 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
523 NewBits[i] = fixBitInit(RV, CurBit, Bit);
527 CachedBitVar = CurBitVar;
528 CachedBitVarChanged = false;
533 CurBitVar = CurBitVar->resolveReferences(R, RV);
534 CachedBitVarChanged |= B != CurBitVar;
535 Changed |= B != CurBitVar;
536 } while (B != CurBitVar);
537 CachedInit = CurBitVar;
539 if (CachedBitVarChanged) {
540 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
541 NewBits[i] = fixBitInit(RV, CurBit, Bit);
546 return BitsInit::get(NewBits);
548 return const_cast<BitsInit *>(this);
551 IntInit *IntInit::get(int64_t V) {
552 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
554 std::unique_ptr<IntInit> &I = ThePool[V];
555 if (!I) I.reset(new IntInit(V));
559 std::string IntInit::getAsString() const {
560 return itostr(Value);
564 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
565 SmallVector<Init *, 16> NewBits(Bits.size());
567 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
571 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
573 return BitsInit::get(NewBits);
576 void StringInit::anchor() { }
578 StringInit *StringInit::get(StringRef V) {
579 static StringMap<std::unique_ptr<StringInit>> ThePool;
581 std::unique_ptr<StringInit> &I = ThePool[V];
582 if (!I) I.reset(new StringInit(V));
586 static void ProfileListInit(FoldingSetNodeID &ID,
587 ArrayRef<Init *> Range,
589 ID.AddInteger(Range.size());
590 ID.AddPointer(EltTy);
592 for (Init *I : Range)
596 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
597 static FoldingSet<ListInit> ThePool;
598 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
601 ProfileListInit(ID, Range, EltTy);
604 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
607 ListInit *I = new ListInit(Range, EltTy);
608 ThePool.InsertNode(I, IP);
609 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
613 void ListInit::Profile(FoldingSetNodeID &ID) const {
614 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
616 ProfileListInit(ID, Values, EltTy);
620 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
621 std::vector<Init*> Vals;
622 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
623 if (Elements[i] >= getSize())
625 Vals.push_back(getElement(Elements[i]));
627 return ListInit::get(Vals, getType());
630 Record *ListInit::getElementAsRecord(unsigned i) const {
631 assert(i < Values.size() && "List element index out of range!");
632 DefInit *DI = dyn_cast<DefInit>(Values[i]);
634 PrintFatalError("Expected record in list!");
638 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
639 std::vector<Init*> Resolved;
640 Resolved.reserve(getSize());
641 bool Changed = false;
643 for (unsigned i = 0, e = getSize(); i != e; ++i) {
645 Init *CurElt = getElement(i);
649 CurElt = CurElt->resolveReferences(R, RV);
650 Changed |= E != CurElt;
651 } while (E != CurElt);
652 Resolved.push_back(E);
656 return ListInit::get(Resolved, getType());
657 return const_cast<ListInit *>(this);
660 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
661 unsigned Elt) const {
662 if (Elt >= getSize())
663 return nullptr; // Out of range reference.
664 Init *E = getElement(Elt);
665 // If the element is set to some value, or if we are resolving a reference
666 // to a specific variable and that variable is explicitly unset, then
667 // replace the VarListElementInit with it.
668 if (IRV || !isa<UnsetInit>(E))
673 std::string ListInit::getAsString() const {
674 std::string Result = "[";
675 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
676 if (i) Result += ", ";
677 Result += Values[i]->getAsString();
682 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
683 unsigned Elt) const {
684 Init *Resolved = resolveReferences(R, IRV);
685 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
687 Resolved = OResolved->Fold(&R, nullptr);
690 if (Resolved != this) {
691 TypedInit *Typed = cast<TypedInit>(Resolved);
692 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
694 return VarListElementInit::get(Typed, Elt);
700 Init *OpInit::getBit(unsigned Bit) const {
701 if (getType() == BitRecTy::get())
702 return const_cast<OpInit*>(this);
703 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
706 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
707 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
708 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
710 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
712 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
713 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
717 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
718 switch (getOpcode()) {
720 if (getType()->getAsString() == "string") {
721 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
724 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
725 return StringInit::get(LHSd->getDef()->getName());
727 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
728 return StringInit::get(LHSi->getAsString());
730 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
731 std::string Name = LHSs->getValue();
733 // From TGParser::ParseIDValue
735 if (const RecordVal *RV = CurRec->getValue(Name)) {
736 if (RV->getType() != getType())
737 PrintFatalError("type mismatch in cast");
738 return VarInit::get(Name, RV->getType());
741 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
744 if (CurRec->isTemplateArg(TemplateArgName)) {
745 const RecordVal *RV = CurRec->getValue(TemplateArgName);
746 assert(RV && "Template arg doesn't exist??");
748 if (RV->getType() != getType())
749 PrintFatalError("type mismatch in cast");
751 return VarInit::get(TemplateArgName, RV->getType());
756 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
759 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
760 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
761 assert(RV && "Template arg doesn't exist??");
763 if (RV->getType() != getType())
764 PrintFatalError("type mismatch in cast");
766 return VarInit::get(MCName, RV->getType());
769 assert(CurRec && "NULL pointer");
770 if (Record *D = (CurRec->getRecords()).getDef(Name))
771 return DefInit::get(D);
773 PrintFatalError(CurRec->getLoc(),
774 "Undefined reference:'" + Name + "'\n");
780 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
781 assert(LHSl->getSize() != 0 && "Empty list in car");
782 return LHSl->getElement(0);
787 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
788 assert(LHSl->getSize() != 0 && "Empty list in cdr");
789 // Note the +1. We can't just pass the result of getValues()
791 ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
792 ArrayRef<Init *>::iterator end = LHSl->getValues().end();
794 ListInit::get(ArrayRef<Init *>(begin, end - begin),
801 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
802 if (LHSl->getSize() == 0)
803 return IntInit::get(1);
804 return IntInit::get(0);
806 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
807 if (LHSs->getValue().empty())
808 return IntInit::get(1);
809 return IntInit::get(0);
815 return const_cast<UnOpInit *>(this);
818 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
819 Init *lhs = LHS->resolveReferences(R, RV);
822 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
823 return Fold(&R, nullptr);
826 std::string UnOpInit::getAsString() const {
829 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
830 case HEAD: Result = "!head"; break;
831 case TAIL: Result = "!tail"; break;
832 case EMPTY: Result = "!empty"; break;
834 return Result + "(" + LHS->getAsString() + ")";
837 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
838 Init *rhs, RecTy *Type) {
840 std::pair<std::pair<unsigned, Init *>, Init *>,
844 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
846 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
849 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
850 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
854 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
855 switch (getOpcode()) {
857 DagInit *LHSs = dyn_cast<DagInit>(LHS);
858 DagInit *RHSs = dyn_cast<DagInit>(RHS);
860 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
861 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
862 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
863 PrintFatalError("Concated Dag operators do not match!");
864 std::vector<Init*> Args;
865 std::vector<std::string> ArgNames;
866 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
867 Args.push_back(LHSs->getArg(i));
868 ArgNames.push_back(LHSs->getArgName(i));
870 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
871 Args.push_back(RHSs->getArg(i));
872 ArgNames.push_back(RHSs->getArgName(i));
874 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
879 ListInit *LHSs = dyn_cast<ListInit>(LHS);
880 ListInit *RHSs = dyn_cast<ListInit>(RHS);
882 std::vector<Init *> Args;
883 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
884 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
885 return ListInit::get(
886 Args, cast<ListRecTy>(LHSs->getType())->getElementType());
891 StringInit *LHSs = dyn_cast<StringInit>(LHS);
892 StringInit *RHSs = dyn_cast<StringInit>(RHS);
894 return StringInit::get(LHSs->getValue() + RHSs->getValue());
898 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
899 // to string objects.
901 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
903 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
906 return IntInit::get(L->getValue() == R->getValue());
908 StringInit *LHSs = dyn_cast<StringInit>(LHS);
909 StringInit *RHSs = dyn_cast<StringInit>(RHS);
911 // Make sure we've resolved
913 return IntInit::get(LHSs->getValue() == RHSs->getValue());
923 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
925 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
927 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
929 switch (getOpcode()) {
930 default: llvm_unreachable("Bad opcode!");
931 case ADD: Result = LHSv + RHSv; break;
932 case AND: Result = LHSv & RHSv; break;
933 case SHL: Result = LHSv << RHSv; break;
934 case SRA: Result = LHSv >> RHSv; break;
935 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
937 return IntInit::get(Result);
942 return const_cast<BinOpInit *>(this);
945 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
946 Init *lhs = LHS->resolveReferences(R, RV);
947 Init *rhs = RHS->resolveReferences(R, RV);
949 if (LHS != lhs || RHS != rhs)
950 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
951 return Fold(&R, nullptr);
954 std::string BinOpInit::getAsString() const {
957 case CONCAT: Result = "!con"; break;
958 case ADD: Result = "!add"; break;
959 case AND: Result = "!and"; break;
960 case SHL: Result = "!shl"; break;
961 case SRA: Result = "!sra"; break;
962 case SRL: Result = "!srl"; break;
963 case EQ: Result = "!eq"; break;
964 case LISTCONCAT: Result = "!listconcat"; break;
965 case STRCONCAT: Result = "!strconcat"; break;
967 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
970 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
974 std::pair<std::pair<unsigned, RecTy *>, Init *>,
980 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
982 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
988 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
989 if (!I) I.reset(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 // If this is a dag, recurse
1000 if (auto *TArg = dyn_cast<TypedInit>(Arg))
1001 if (TArg->getType()->getAsString() == "dag")
1002 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
1004 std::vector<Init *> NewOperands;
1005 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1006 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
1007 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1008 Type, CurRec, CurMultiClass))
1009 NewOperands.push_back(Result);
1011 NewOperands.push_back(Arg);
1012 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1013 NewOperands.push_back(Arg);
1015 NewOperands.push_back(RHSo->getOperand(i));
1019 // Now run the operator and use its result as the new leaf
1020 const OpInit *NewOp = RHSo->clone(NewOperands);
1021 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1022 return (NewVal != NewOp) ? NewVal : nullptr;
1025 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
1026 Record *CurRec, MultiClass *CurMultiClass) {
1027 DagInit *MHSd = dyn_cast<DagInit>(MHS);
1028 ListInit *MHSl = dyn_cast<ListInit>(MHS);
1030 OpInit *RHSo = dyn_cast<OpInit>(RHS);
1033 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);
1048 std::vector<std::pair<Init *, std::string> > args;
1049 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1051 std::string ArgName;
1052 Arg = MHSd->getArg(i);
1053 ArgName = MHSd->getArgName(i);
1056 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1057 CurRec, CurMultiClass);
1061 // TODO: Process arg names
1062 args.push_back(std::make_pair(Arg, ArgName));
1065 return DagInit::get(Val, "", args);
1068 std::vector<Init *> NewOperands;
1069 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1071 for (Init *&Item : NewList) {
1072 NewOperands.clear();
1073 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1074 // First, replace the foreach variable with the list item
1075 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
1076 NewOperands.push_back(Item);
1078 NewOperands.push_back(RHSo->getOperand(i));
1081 // Now run the operator and use its result as the new list item
1082 const OpInit *NewOp = RHSo->clone(NewOperands);
1083 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1084 if (NewItem != NewOp)
1087 return ListInit::get(NewList, MHSl->getType());
1093 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1094 switch (getOpcode()) {
1096 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1097 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1098 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1100 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1101 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1102 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1104 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1105 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1106 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1108 if ((LHSd && MHSd && RHSd) ||
1109 (LHSv && MHSv && RHSv) ||
1110 (LHSs && MHSs && RHSs)) {
1112 Record *Val = RHSd->getDef();
1113 if (LHSd->getAsString() == RHSd->getAsString())
1114 Val = MHSd->getDef();
1115 return DefInit::get(Val);
1118 std::string Val = RHSv->getName();
1119 if (LHSv->getAsString() == RHSv->getAsString())
1120 Val = MHSv->getName();
1121 return VarInit::get(Val, getType());
1124 std::string Val = RHSs->getValue();
1126 std::string::size_type found;
1127 std::string::size_type idx = 0;
1129 found = Val.find(LHSs->getValue(), idx);
1130 if (found != std::string::npos)
1131 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1132 idx = found + MHSs->getValue().size();
1133 } while (found != std::string::npos);
1135 return StringInit::get(Val);
1142 Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1143 CurRec, CurMultiClass);
1150 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1151 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1152 LHSi = dyn_cast<IntInit>(I);
1154 if (LHSi->getValue())
1162 return const_cast<TernOpInit *>(this);
1165 Init *TernOpInit::resolveReferences(Record &R,
1166 const RecordVal *RV) const {
1167 Init *lhs = LHS->resolveReferences(R, RV);
1169 if (Opc == IF && lhs != LHS) {
1170 IntInit *Value = dyn_cast<IntInit>(lhs);
1171 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1172 Value = dyn_cast<IntInit>(I);
1175 if (Value->getValue()) {
1176 Init *mhs = MHS->resolveReferences(R, RV);
1177 return (TernOpInit::get(getOpcode(), lhs, mhs,
1178 RHS, getType()))->Fold(&R, nullptr);
1180 Init *rhs = RHS->resolveReferences(R, RV);
1181 return (TernOpInit::get(getOpcode(), lhs, MHS,
1182 rhs, getType()))->Fold(&R, nullptr);
1186 Init *mhs = MHS->resolveReferences(R, RV);
1187 Init *rhs = RHS->resolveReferences(R, RV);
1189 if (LHS != lhs || MHS != mhs || RHS != rhs)
1190 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1191 getType()))->Fold(&R, nullptr);
1192 return Fold(&R, nullptr);
1195 std::string TernOpInit::getAsString() const {
1198 case SUBST: Result = "!subst"; break;
1199 case FOREACH: Result = "!foreach"; break;
1200 case IF: Result = "!if"; break;
1202 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1203 RHS->getAsString() + ")";
1206 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1207 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1208 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1209 return Field->getType();
1214 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1215 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1216 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1217 unsigned NumBits = T->getNumBits();
1219 SmallVector<Init *, 16> NewBits(Bits.size());
1220 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1221 if (Bits[i] >= NumBits)
1224 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1226 return BitsInit::get(NewBits);
1230 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1231 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1232 if (!T) return nullptr; // Cannot subscript a non-list variable.
1234 if (Elements.size() == 1)
1235 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1237 std::vector<Init*> ListInits;
1238 ListInits.reserve(Elements.size());
1239 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1240 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1242 return ListInit::get(ListInits, T);
1246 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1247 Init *Value = StringInit::get(VN);
1248 return VarInit::get(Value, T);
1251 VarInit *VarInit::get(Init *VN, RecTy *T) {
1252 typedef std::pair<RecTy *, Init *> Key;
1253 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1255 Key TheKey(std::make_pair(T, VN));
1257 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1258 if (!I) I.reset(new VarInit(VN, T));
1262 const std::string &VarInit::getName() const {
1263 StringInit *NameString = cast<StringInit>(getNameInit());
1264 return NameString->getValue();
1267 Init *VarInit::getBit(unsigned Bit) const {
1268 if (getType() == BitRecTy::get())
1269 return const_cast<VarInit*>(this);
1270 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1273 Init *VarInit::resolveListElementReference(Record &R,
1274 const RecordVal *IRV,
1275 unsigned Elt) const {
1276 if (R.isTemplateArg(getNameInit())) return nullptr;
1277 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1279 RecordVal *RV = R.getValue(getNameInit());
1280 assert(RV && "Reference to a non-existent variable?");
1281 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1283 return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
1285 if (Elt >= LI->getSize())
1286 return nullptr; // Out of range reference.
1287 Init *E = LI->getElement(Elt);
1288 // If the element is set to some value, or if we are resolving a reference
1289 // to a specific variable and that variable is explicitly unset, then
1290 // replace the VarListElementInit with it.
1291 if (IRV || !isa<UnsetInit>(E))
1297 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1298 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1299 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1300 return RV->getType();
1304 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1305 const std::string &FieldName) const {
1306 if (isa<RecordRecTy>(getType()))
1307 if (const RecordVal *Val = R.getValue(VarName)) {
1308 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1310 Init *TheInit = Val->getValue();
1311 assert(TheInit != this && "Infinite loop detected!");
1312 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1319 /// resolveReferences - This method is used by classes that refer to other
1320 /// variables which may not be defined at the time the expression is formed.
1321 /// If a value is set for the variable later, this method will be called on
1322 /// users of the value to allow the value to propagate out.
1324 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1325 if (RecordVal *Val = R.getValue(VarName))
1326 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1327 return Val->getValue();
1328 return const_cast<VarInit *>(this);
1331 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1332 typedef std::pair<TypedInit *, unsigned> Key;
1333 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1335 Key TheKey(std::make_pair(T, B));
1337 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1338 if (!I) I.reset(new VarBitInit(T, B));
1342 std::string VarBitInit::getAsString() const {
1343 return TI->getAsString() + "{" + utostr(Bit) + "}";
1346 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1347 Init *I = TI->resolveReferences(R, RV);
1349 return I->getBit(getBitNum());
1351 return const_cast<VarBitInit*>(this);
1354 VarListElementInit *VarListElementInit::get(TypedInit *T,
1356 typedef std::pair<TypedInit *, unsigned> Key;
1357 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1359 Key TheKey(std::make_pair(T, E));
1361 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1362 if (!I) I.reset(new VarListElementInit(T, E));
1366 std::string VarListElementInit::getAsString() const {
1367 return TI->getAsString() + "[" + utostr(Element) + "]";
1371 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1372 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1375 return const_cast<VarListElementInit *>(this);
1378 Init *VarListElementInit::getBit(unsigned Bit) const {
1379 if (getType() == BitRecTy::get())
1380 return const_cast<VarListElementInit*>(this);
1381 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1384 Init *VarListElementInit:: resolveListElementReference(Record &R,
1385 const RecordVal *RV,
1386 unsigned Elt) const {
1387 if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
1388 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1389 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1390 if (Result2) return Result2;
1391 return VarListElementInit::get(TInit, Elt);
1399 DefInit *DefInit::get(Record *R) {
1400 return R->getDefInit();
1403 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1404 if (const RecordVal *RV = Def->getValue(FieldName))
1405 return RV->getType();
1409 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1410 const std::string &FieldName) const {
1411 return Def->getValue(FieldName)->getValue();
1415 std::string DefInit::getAsString() const {
1416 return Def->getName();
1419 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1420 typedef std::pair<Init *, TableGenStringKey> Key;
1421 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1423 Key TheKey(std::make_pair(R, FN));
1425 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1426 if (!I) I.reset(new FieldInit(R, FN));
1430 Init *FieldInit::getBit(unsigned Bit) const {
1431 if (getType() == BitRecTy::get())
1432 return const_cast<FieldInit*>(this);
1433 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1436 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1437 unsigned Elt) const {
1438 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1439 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1440 if (Elt >= LI->getSize()) return nullptr;
1441 Init *E = LI->getElement(Elt);
1443 // If the element is set to some value, or if we are resolving a
1444 // reference to a specific variable and that variable is explicitly
1445 // unset, then replace the VarListElementInit with it.
1446 if (RV || !isa<UnsetInit>(E))
1452 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1453 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1455 if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
1456 Init *BVR = BitsVal->resolveReferences(R, RV);
1457 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1461 return FieldInit::get(NewRec, FieldName);
1462 return const_cast<FieldInit *>(this);
1465 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1466 ArrayRef<Init *> ArgRange,
1467 ArrayRef<std::string> NameRange) {
1471 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1472 ArrayRef<std::string>::iterator Name = NameRange.begin();
1473 while (Arg != ArgRange.end()) {
1474 assert(Name != NameRange.end() && "Arg name underflow!");
1475 ID.AddPointer(*Arg++);
1476 ID.AddString(*Name++);
1478 assert(Name == NameRange.end() && "Arg name overflow!");
1482 DagInit::get(Init *V, const std::string &VN,
1483 ArrayRef<Init *> ArgRange,
1484 ArrayRef<std::string> NameRange) {
1485 static FoldingSet<DagInit> ThePool;
1486 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1488 FoldingSetNodeID ID;
1489 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1492 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1495 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1496 ThePool.InsertNode(I, IP);
1497 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1502 DagInit::get(Init *V, const std::string &VN,
1503 const std::vector<std::pair<Init*, std::string> > &args) {
1504 std::vector<Init *> Args;
1505 std::vector<std::string> Names;
1507 for (const auto &Arg : args) {
1508 Args.push_back(Arg.first);
1509 Names.push_back(Arg.second);
1512 return DagInit::get(V, VN, Args, Names);
1515 void DagInit::Profile(FoldingSetNodeID &ID) const {
1516 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1519 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1520 std::vector<Init*> NewArgs;
1521 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1522 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1524 Init *Op = Val->resolveReferences(R, RV);
1526 if (Args != NewArgs || Op != Val)
1527 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1529 return const_cast<DagInit *>(this);
1533 std::string DagInit::getAsString() const {
1534 std::string Result = "(" + Val->getAsString();
1535 if (!ValName.empty())
1536 Result += ":" + ValName;
1537 if (!Args.empty()) {
1538 Result += " " + Args[0]->getAsString();
1539 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1540 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1541 Result += ", " + Args[i]->getAsString();
1542 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1545 return Result + ")";
1549 //===----------------------------------------------------------------------===//
1550 // Other implementations
1551 //===----------------------------------------------------------------------===//
1553 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1554 : Name(N), Ty(T), Prefix(P) {
1555 Value = Ty->convertValue(UnsetInit::get());
1556 assert(Value && "Cannot create unset value for current type!");
1559 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1560 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1561 Value = Ty->convertValue(UnsetInit::get());
1562 assert(Value && "Cannot create unset value for current type!");
1565 const std::string &RecordVal::getName() const {
1566 return cast<StringInit>(Name)->getValue();
1569 void RecordVal::dump() const { errs() << *this; }
1571 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1572 if (getPrefix()) OS << "field ";
1573 OS << *getType() << " " << getNameInitAsString();
1576 OS << " = " << *getValue();
1578 if (PrintSem) OS << ";\n";
1581 unsigned Record::LastID = 0;
1583 void Record::init() {
1586 // Every record potentially has a def at the top. This value is
1587 // replaced with the top-level def name at instantiation time.
1588 RecordVal DN("NAME", StringRecTy::get(), 0);
1592 void Record::checkName() {
1593 // Ensure the record name has string type.
1594 const TypedInit *TypedName = cast<const TypedInit>(Name);
1595 RecTy *Type = TypedName->getType();
1596 if (!isa<StringRecTy>(Type))
1597 PrintFatalError(getLoc(), "Record name is not a string!");
1600 DefInit *Record::getDefInit() {
1601 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1605 std::unique_ptr<DefInit> &I = ThePool[this];
1606 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1610 const std::string &Record::getName() const {
1611 return cast<StringInit>(Name)->getValue();
1614 void Record::setName(Init *NewName) {
1617 // DO NOT resolve record values to the name at this point because
1618 // there might be default values for arguments of this def. Those
1619 // arguments might not have been resolved yet so we don't want to
1620 // prematurely assume values for those arguments were not passed to
1623 // Nonetheless, it may be that some of this Record's values
1624 // reference the record name. Indeed, the reason for having the
1625 // record name be an Init is to provide this flexibility. The extra
1626 // resolve steps after completely instantiating defs takes care of
1627 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1630 void Record::setName(const std::string &Name) {
1631 setName(StringInit::get(Name));
1634 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1635 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1637 void Record::resolveReferencesTo(const RecordVal *RV) {
1638 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1639 if (RV == &Values[i]) // Skip resolve the same field as the given one
1641 if (Init *V = Values[i].getValue())
1642 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1643 PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1644 Values[i].getNameInitAsString() +
1645 "' after resolving references" +
1646 (RV ? " against '" + RV->getNameInitAsString() +
1647 "' of (" + RV->getValue()->getAsUnquotedString() +
1651 Init *OldName = getNameInit();
1652 Init *NewName = Name->resolveReferences(*this, RV);
1653 if (NewName != OldName) {
1654 // Re-register with RecordKeeper.
1659 void Record::dump() const { errs() << *this; }
1661 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1662 OS << R.getNameInitAsString();
1664 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1665 if (!TArgs.empty()) {
1667 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1669 const RecordVal *RV = R.getValue(TArgs[i]);
1670 assert(RV && "Template argument record not found??");
1671 RV->print(OS, false);
1677 const std::vector<Record*> &SC = R.getSuperClasses();
1680 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1681 OS << " " << SC[i]->getNameInitAsString();
1685 const std::vector<RecordVal> &Vals = R.getValues();
1686 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1687 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1689 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1690 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1696 /// getValueInit - Return the initializer for a value with the specified name,
1697 /// or abort if the field does not exist.
1699 Init *Record::getValueInit(StringRef FieldName) const {
1700 const RecordVal *R = getValue(FieldName);
1701 if (!R || !R->getValue())
1702 PrintFatalError(getLoc(), "Record `" + getName() +
1703 "' does not have a field named `" + FieldName + "'!\n");
1704 return R->getValue();
1708 /// getValueAsString - This method looks up the specified field and returns its
1709 /// value as a string, aborts if the field does not exist or if
1710 /// the value is not a string.
1712 std::string Record::getValueAsString(StringRef FieldName) const {
1713 const RecordVal *R = getValue(FieldName);
1714 if (!R || !R->getValue())
1715 PrintFatalError(getLoc(), "Record `" + getName() +
1716 "' does not have a field named `" + FieldName + "'!\n");
1718 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1719 return SI->getValue();
1720 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1721 FieldName + "' does not have a string initializer!");
1724 /// getValueAsBitsInit - This method looks up the specified field and returns
1725 /// its value as a BitsInit, aborts if the field does not exist or if
1726 /// the value is not the right type.
1728 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1729 const RecordVal *R = getValue(FieldName);
1730 if (!R || !R->getValue())
1731 PrintFatalError(getLoc(), "Record `" + getName() +
1732 "' does not have a field named `" + FieldName + "'!\n");
1734 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1736 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1737 FieldName + "' does not have a BitsInit initializer!");
1740 /// getValueAsListInit - This method looks up the specified field and returns
1741 /// its value as a ListInit, aborting if the field does not exist or if
1742 /// the value is not the right type.
1744 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1745 const RecordVal *R = getValue(FieldName);
1746 if (!R || !R->getValue())
1747 PrintFatalError(getLoc(), "Record `" + getName() +
1748 "' does not have a field named `" + FieldName + "'!\n");
1750 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1752 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1753 FieldName + "' does not have a list initializer!");
1756 /// getValueAsListOfDefs - This method looks up the specified field and returns
1757 /// its value as a vector of records, aborting if the field does not exist
1758 /// or if the value is not the right type.
1760 std::vector<Record*>
1761 Record::getValueAsListOfDefs(StringRef FieldName) const {
1762 ListInit *List = getValueAsListInit(FieldName);
1763 std::vector<Record*> Defs;
1764 for (unsigned i = 0; i < List->getSize(); i++) {
1765 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i)))
1766 Defs.push_back(DI->getDef());
1768 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1769 FieldName + "' list is not entirely DefInit!");
1774 /// getValueAsInt - This method looks up the specified field and returns its
1775 /// value as an int64_t, aborting if the field does not exist or if the value
1776 /// is not the right type.
1778 int64_t Record::getValueAsInt(StringRef FieldName) const {
1779 const RecordVal *R = getValue(FieldName);
1780 if (!R || !R->getValue())
1781 PrintFatalError(getLoc(), "Record `" + getName() +
1782 "' does not have a field named `" + FieldName + "'!\n");
1784 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1785 return II->getValue();
1786 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1787 FieldName + "' does not have an int initializer!");
1790 /// getValueAsListOfInts - This method looks up the specified field and returns
1791 /// its value as a vector of integers, aborting if the field does not exist or
1792 /// if the value is not the right type.
1794 std::vector<int64_t>
1795 Record::getValueAsListOfInts(StringRef FieldName) const {
1796 ListInit *List = getValueAsListInit(FieldName);
1797 std::vector<int64_t> Ints;
1798 for (unsigned i = 0; i < List->getSize(); i++) {
1799 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i)))
1800 Ints.push_back(II->getValue());
1802 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1803 FieldName + "' does not have a list of ints initializer!");
1808 /// getValueAsListOfStrings - This method looks up the specified field and
1809 /// returns its value as a vector of strings, aborting if the field does not
1810 /// exist or if the value is not the right type.
1812 std::vector<std::string>
1813 Record::getValueAsListOfStrings(StringRef FieldName) const {
1814 ListInit *List = getValueAsListInit(FieldName);
1815 std::vector<std::string> Strings;
1816 for (unsigned i = 0; i < List->getSize(); i++) {
1817 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i)))
1818 Strings.push_back(II->getValue());
1820 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1821 FieldName + "' does not have a list of strings initializer!");
1826 /// getValueAsDef - This method looks up the specified field and returns its
1827 /// value as a Record, aborting if the field does not exist or if the value
1828 /// is not the right type.
1830 Record *Record::getValueAsDef(StringRef FieldName) const {
1831 const RecordVal *R = getValue(FieldName);
1832 if (!R || !R->getValue())
1833 PrintFatalError(getLoc(), "Record `" + getName() +
1834 "' does not have a field named `" + FieldName + "'!\n");
1836 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1837 return DI->getDef();
1838 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1839 FieldName + "' does not have a def initializer!");
1842 /// getValueAsBit - This method looks up the specified field and returns its
1843 /// value as a bit, aborting if the field does not exist or if the value is
1844 /// not the right type.
1846 bool Record::getValueAsBit(StringRef FieldName) const {
1847 const RecordVal *R = getValue(FieldName);
1848 if (!R || !R->getValue())
1849 PrintFatalError(getLoc(), "Record `" + getName() +
1850 "' does not have a field named `" + FieldName + "'!\n");
1852 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1853 return BI->getValue();
1854 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1855 FieldName + "' does not have a bit initializer!");
1858 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1859 const RecordVal *R = getValue(FieldName);
1860 if (!R || !R->getValue())
1861 PrintFatalError(getLoc(), "Record `" + getName() +
1862 "' does not have a field named `" + FieldName.str() + "'!\n");
1864 if (isa<UnsetInit>(R->getValue())) {
1869 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1870 return BI->getValue();
1871 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1872 FieldName + "' does not have a bit initializer!");
1875 /// getValueAsDag - This method looks up the specified field and returns its
1876 /// value as an Dag, aborting if the field does not exist or if the value is
1877 /// not the right type.
1879 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1880 const RecordVal *R = getValue(FieldName);
1881 if (!R || !R->getValue())
1882 PrintFatalError(getLoc(), "Record `" + getName() +
1883 "' does not have a field named `" + FieldName + "'!\n");
1885 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1887 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1888 FieldName + "' does not have a dag initializer!");
1892 void MultiClass::dump() const {
1893 errs() << "Record:\n";
1896 errs() << "Defs:\n";
1897 for (const auto &Proto : DefPrototypes)
1902 void RecordKeeper::dump() const { errs() << *this; }
1904 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1905 OS << "------------- Classes -----------------\n";
1906 const auto &Classes = RK.getClasses();
1907 for (const auto &C : Classes)
1908 OS << "class " << *C.second;
1910 OS << "------------- Defs -----------------\n";
1911 const auto &Defs = RK.getDefs();
1912 for (const auto &D : Defs)
1913 OS << "def " << *D.second;
1918 /// getAllDerivedDefinitions - This method returns all concrete definitions
1919 /// that derive from the specified class name. If a class with the specified
1920 /// name does not exist, an error is printed and true is returned.
1921 std::vector<Record*>
1922 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1923 Record *Class = getClass(ClassName);
1925 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1927 std::vector<Record*> Defs;
1928 for (const auto &D : getDefs())
1929 if (D.second->isSubClassOf(Class))
1930 Defs.push_back(D.second.get());
1935 /// QualifyName - Return an Init with a qualifier prefix referring
1936 /// to CurRec's name.
1937 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1938 Init *Name, const std::string &Scoper) {
1939 RecTy *Type = cast<TypedInit>(Name)->getType();
1941 BinOpInit *NewName =
1942 BinOpInit::get(BinOpInit::STRCONCAT,
1943 BinOpInit::get(BinOpInit::STRCONCAT,
1944 CurRec.getNameInit(),
1945 StringInit::get(Scoper),
1946 Type)->Fold(&CurRec, CurMultiClass),
1950 if (CurMultiClass && Scoper != "::") {
1952 BinOpInit::get(BinOpInit::STRCONCAT,
1953 BinOpInit::get(BinOpInit::STRCONCAT,
1954 CurMultiClass->Rec.getNameInit(),
1955 StringInit::get("::"),
1956 Type)->Fold(&CurRec, CurMultiClass),
1957 NewName->Fold(&CurRec, CurMultiClass),
1961 return NewName->Fold(&CurRec, CurMultiClass);
1964 /// QualifyName - Return an Init with a qualifier prefix referring
1965 /// to CurRec's name.
1966 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1967 const std::string &Name,
1968 const std::string &Scoper) {
1969 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);