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 *TI) {
116 RecTy *Ty = TI->getType();
117 if (isa<BitRecTy>(Ty))
118 return TI; // 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 ? TI : 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>(TI)) {
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 *BI) {
167 if (Size != 1) return nullptr; // Can only convert single bit.
168 return BitsInit::get(BI);
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 *TI) {
204 if (Size == 1 && isa<BitRecTy>(TI->getType()))
205 return BitsInit::get(TI);
207 if (TI->getType()->typeIsConvertibleTo(this)) {
208 SmallVector<Init *, 16> NewBits(Size);
210 for (unsigned i = 0; i != Size; ++i)
211 NewBits[i] = VarBitInit::get(TI, 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 |= static_cast<int64_t>(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;
251 Init *StringRecTy::convertValue(TypedInit *TI) {
252 if (isa<StringRecTy>(TI->getType()))
253 return TI; // Accept variable if already of the right type!
257 std::string ListRecTy::getAsString() const {
258 return "list<" + Ty->getAsString() + ">";
261 Init *ListRecTy::convertValue(ListInit *LI) {
262 std::vector<Init*> Elements;
264 // Verify that all of the elements of the list are subclasses of the
265 // appropriate class!
266 for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
267 if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
268 Elements.push_back(CI);
272 if (!isa<ListRecTy>(LI->getType()))
275 return ListInit::get(Elements, this);
278 Init *ListRecTy::convertValue(TypedInit *TI) {
279 // Ensure that TI is compatible with our class.
280 if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
281 if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
286 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
287 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
288 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
292 Init *DagRecTy::convertValue(TypedInit *TI) {
293 if (TI->getType()->typeIsConvertibleTo(this))
298 RecordRecTy *RecordRecTy::get(Record *R) {
299 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
302 std::string RecordRecTy::getAsString() const {
303 return Rec->getName();
306 Init *RecordRecTy::convertValue(DefInit *DI) {
307 // Ensure that DI is a subclass of Rec.
308 if (!DI->getDef()->isSubClassOf(Rec))
313 Init *RecordRecTy::convertValue(TypedInit *TI) {
314 // Ensure that TI is compatible with Rec.
315 if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
316 if (RRT->getRecord()->isSubClassOf(getRecord()) ||
317 RRT->getRecord() == getRecord())
322 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
323 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
327 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
330 const std::vector<Record*> &SC = Rec->getSuperClasses();
331 for (unsigned i = 0, e = SC.size(); i != e; ++i)
332 if (RTy->getRecord()->isSubClassOf(SC[i]))
338 /// resolveTypes - Find a common type that T1 and T2 convert to.
339 /// Return null if no such type exists.
341 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
342 if (T1->typeIsConvertibleTo(T2))
344 if (T2->typeIsConvertibleTo(T1))
347 // If one is a Record type, check superclasses
348 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
349 // See if T2 inherits from a type T1 also inherits from
350 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
351 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
352 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
357 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
358 // See if T1 inherits from a type T2 also inherits from
359 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
360 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
361 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
370 //===----------------------------------------------------------------------===//
371 // Initializer implementations
372 //===----------------------------------------------------------------------===//
374 void Init::anchor() { }
375 void Init::dump() const { return print(errs()); }
377 void UnsetInit::anchor() { }
379 UnsetInit *UnsetInit::get() {
380 static UnsetInit TheInit;
384 void BitInit::anchor() { }
386 BitInit *BitInit::get(bool V) {
387 static BitInit True(true);
388 static BitInit False(false);
390 return V ? &True : &False;
394 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
395 ID.AddInteger(Range.size());
397 for (Init *I : Range)
401 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
402 static FoldingSet<BitsInit> ThePool;
403 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
406 ProfileBitsInit(ID, Range);
409 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
412 BitsInit *I = new BitsInit(Range);
413 ThePool.InsertNode(I, IP);
414 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
418 void BitsInit::Profile(FoldingSetNodeID &ID) const {
419 ProfileBitsInit(ID, Bits);
423 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
424 SmallVector<Init *, 16> NewBits(Bits.size());
426 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
427 if (Bits[i] >= getNumBits())
429 NewBits[i] = getBit(Bits[i]);
431 return BitsInit::get(NewBits);
434 std::string BitsInit::getAsString() const {
435 std::string Result = "{ ";
436 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
437 if (i) Result += ", ";
438 if (Init *Bit = getBit(e-i-1))
439 Result += Bit->getAsString();
443 return Result + " }";
446 // Fix bit initializer to preserve the behavior that bit reference from a unset
447 // bits initializer will resolve into VarBitInit to keep the field name and bit
448 // number used in targets with fixed insn length.
449 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
450 if (RV || !isa<UnsetInit>(After))
455 // resolveReferences - If there are any field references that refer to fields
456 // that have been filled in, we can propagate the values now.
458 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
459 bool Changed = false;
460 SmallVector<Init *, 16> NewBits(getNumBits());
462 Init *CachedInit = nullptr;
463 Init *CachedBitVar = nullptr;
464 bool CachedBitVarChanged = false;
466 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
467 Init *CurBit = Bits[i];
468 Init *CurBitVar = CurBit->getBitVar();
472 if (CurBitVar == CachedBitVar) {
473 if (CachedBitVarChanged) {
474 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
475 NewBits[i] = fixBitInit(RV, CurBit, Bit);
479 CachedBitVar = CurBitVar;
480 CachedBitVarChanged = false;
485 CurBitVar = CurBitVar->resolveReferences(R, RV);
486 CachedBitVarChanged |= B != CurBitVar;
487 Changed |= B != CurBitVar;
488 } while (B != CurBitVar);
489 CachedInit = CurBitVar;
491 if (CachedBitVarChanged) {
492 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
493 NewBits[i] = fixBitInit(RV, CurBit, Bit);
498 return BitsInit::get(NewBits);
500 return const_cast<BitsInit *>(this);
503 IntInit *IntInit::get(int64_t V) {
504 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
506 std::unique_ptr<IntInit> &I = ThePool[V];
507 if (!I) I.reset(new IntInit(V));
511 std::string IntInit::getAsString() const {
512 return itostr(Value);
516 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
517 SmallVector<Init *, 16> NewBits(Bits.size());
519 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
523 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
525 return BitsInit::get(NewBits);
528 void StringInit::anchor() { }
530 StringInit *StringInit::get(StringRef V) {
531 static StringMap<std::unique_ptr<StringInit>> ThePool;
533 std::unique_ptr<StringInit> &I = ThePool[V];
534 if (!I) I.reset(new StringInit(V));
538 static void ProfileListInit(FoldingSetNodeID &ID,
539 ArrayRef<Init *> Range,
541 ID.AddInteger(Range.size());
542 ID.AddPointer(EltTy);
544 for (Init *I : Range)
548 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
549 static FoldingSet<ListInit> ThePool;
550 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
553 ProfileListInit(ID, Range, EltTy);
556 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
559 ListInit *I = new ListInit(Range, EltTy);
560 ThePool.InsertNode(I, IP);
561 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
565 void ListInit::Profile(FoldingSetNodeID &ID) const {
566 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
568 ProfileListInit(ID, Values, EltTy);
572 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
573 std::vector<Init*> Vals;
574 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
575 if (Elements[i] >= getSize())
577 Vals.push_back(getElement(Elements[i]));
579 return ListInit::get(Vals, getType());
582 Record *ListInit::getElementAsRecord(unsigned i) const {
583 assert(i < Values.size() && "List element index out of range!");
584 DefInit *DI = dyn_cast<DefInit>(Values[i]);
586 PrintFatalError("Expected record in list!");
590 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
591 std::vector<Init*> Resolved;
592 Resolved.reserve(getSize());
593 bool Changed = false;
595 for (unsigned i = 0, e = getSize(); i != e; ++i) {
597 Init *CurElt = getElement(i);
601 CurElt = CurElt->resolveReferences(R, RV);
602 Changed |= E != CurElt;
603 } while (E != CurElt);
604 Resolved.push_back(E);
608 return ListInit::get(Resolved, getType());
609 return const_cast<ListInit *>(this);
612 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
613 unsigned Elt) const {
614 if (Elt >= getSize())
615 return nullptr; // Out of range reference.
616 Init *E = getElement(Elt);
617 // If the element is set to some value, or if we are resolving a reference
618 // to a specific variable and that variable is explicitly unset, then
619 // replace the VarListElementInit with it.
620 if (IRV || !isa<UnsetInit>(E))
625 std::string ListInit::getAsString() const {
626 std::string Result = "[";
627 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
628 if (i) Result += ", ";
629 Result += Values[i]->getAsString();
634 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
635 unsigned Elt) const {
636 Init *Resolved = resolveReferences(R, IRV);
637 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
639 Resolved = OResolved->Fold(&R, nullptr);
642 if (Resolved != this) {
643 TypedInit *Typed = cast<TypedInit>(Resolved);
644 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
646 return VarListElementInit::get(Typed, Elt);
652 Init *OpInit::getBit(unsigned Bit) const {
653 if (getType() == BitRecTy::get())
654 return const_cast<OpInit*>(this);
655 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
658 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
659 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
660 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
662 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
664 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
665 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
669 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
670 switch (getOpcode()) {
672 if (isa<StringRecTy>(getType())) {
673 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
676 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
677 return StringInit::get(LHSd->getAsString());
679 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
680 return StringInit::get(LHSi->getAsString());
682 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
683 std::string Name = LHSs->getValue();
685 // From TGParser::ParseIDValue
687 if (const RecordVal *RV = CurRec->getValue(Name)) {
688 if (RV->getType() != getType())
689 PrintFatalError("type mismatch in cast");
690 return VarInit::get(Name, RV->getType());
693 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
696 if (CurRec->isTemplateArg(TemplateArgName)) {
697 const RecordVal *RV = CurRec->getValue(TemplateArgName);
698 assert(RV && "Template arg doesn't exist??");
700 if (RV->getType() != getType())
701 PrintFatalError("type mismatch in cast");
703 return VarInit::get(TemplateArgName, RV->getType());
708 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
711 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
712 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
713 assert(RV && "Template arg doesn't exist??");
715 if (RV->getType() != getType())
716 PrintFatalError("type mismatch in cast");
718 return VarInit::get(MCName, RV->getType());
721 assert(CurRec && "NULL pointer");
722 if (Record *D = (CurRec->getRecords()).getDef(Name))
723 return DefInit::get(D);
725 PrintFatalError(CurRec->getLoc(),
726 "Undefined reference:'" + Name + "'\n");
732 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
733 assert(!LHSl->empty() && "Empty list in head");
734 return LHSl->getElement(0);
739 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
740 assert(!LHSl->empty() && "Empty list in tail");
741 // Note the +1. We can't just pass the result of getValues()
743 return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
748 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
749 return IntInit::get(LHSl->empty());
750 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
751 return IntInit::get(LHSs->getValue().empty());
756 return const_cast<UnOpInit *>(this);
759 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
760 Init *lhs = LHS->resolveReferences(R, RV);
763 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
764 return Fold(&R, nullptr);
767 std::string UnOpInit::getAsString() const {
770 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
771 case HEAD: Result = "!head"; break;
772 case TAIL: Result = "!tail"; break;
773 case EMPTY: Result = "!empty"; break;
775 return Result + "(" + LHS->getAsString() + ")";
778 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
779 Init *rhs, RecTy *Type) {
781 std::pair<std::pair<unsigned, Init *>, Init *>,
785 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
787 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
790 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
791 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
795 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
796 switch (getOpcode()) {
798 DagInit *LHSs = dyn_cast<DagInit>(LHS);
799 DagInit *RHSs = dyn_cast<DagInit>(RHS);
801 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
802 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
803 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
804 PrintFatalError("Concated Dag operators do not match!");
805 std::vector<Init*> Args;
806 std::vector<std::string> ArgNames;
807 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
808 Args.push_back(LHSs->getArg(i));
809 ArgNames.push_back(LHSs->getArgName(i));
811 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
812 Args.push_back(RHSs->getArg(i));
813 ArgNames.push_back(RHSs->getArgName(i));
815 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
820 ListInit *LHSs = dyn_cast<ListInit>(LHS);
821 ListInit *RHSs = dyn_cast<ListInit>(RHS);
823 std::vector<Init *> Args;
824 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
825 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
826 return ListInit::get(
827 Args, cast<ListRecTy>(LHSs->getType())->getElementType());
832 StringInit *LHSs = dyn_cast<StringInit>(LHS);
833 StringInit *RHSs = dyn_cast<StringInit>(RHS);
835 return StringInit::get(LHSs->getValue() + RHSs->getValue());
839 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
840 // to string objects.
842 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
844 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
847 return IntInit::get(L->getValue() == R->getValue());
849 StringInit *LHSs = dyn_cast<StringInit>(LHS);
850 StringInit *RHSs = dyn_cast<StringInit>(RHS);
852 // Make sure we've resolved
854 return IntInit::get(LHSs->getValue() == RHSs->getValue());
864 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
866 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
868 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
870 switch (getOpcode()) {
871 default: llvm_unreachable("Bad opcode!");
872 case ADD: Result = LHSv + RHSv; break;
873 case AND: Result = LHSv & RHSv; break;
874 case SHL: Result = LHSv << RHSv; break;
875 case SRA: Result = LHSv >> RHSv; break;
876 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
878 return IntInit::get(Result);
883 return const_cast<BinOpInit *>(this);
886 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
887 Init *lhs = LHS->resolveReferences(R, RV);
888 Init *rhs = RHS->resolveReferences(R, RV);
890 if (LHS != lhs || RHS != rhs)
891 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
892 return Fold(&R, nullptr);
895 std::string BinOpInit::getAsString() const {
898 case CONCAT: Result = "!con"; break;
899 case ADD: Result = "!add"; break;
900 case AND: Result = "!and"; break;
901 case SHL: Result = "!shl"; break;
902 case SRA: Result = "!sra"; break;
903 case SRL: Result = "!srl"; break;
904 case EQ: Result = "!eq"; break;
905 case LISTCONCAT: Result = "!listconcat"; break;
906 case STRCONCAT: Result = "!strconcat"; break;
908 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
911 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
915 std::pair<std::pair<unsigned, RecTy *>, Init *>,
921 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
923 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
929 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
930 if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
934 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
935 Record *CurRec, MultiClass *CurMultiClass);
937 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
938 RecTy *Type, Record *CurRec,
939 MultiClass *CurMultiClass) {
940 // If this is a dag, recurse
941 if (auto *TArg = dyn_cast<TypedInit>(Arg))
942 if (isa<DagRecTy>(TArg->getType()))
943 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
945 std::vector<Init *> NewOperands;
946 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
947 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
948 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
949 Type, CurRec, CurMultiClass))
950 NewOperands.push_back(Result);
952 NewOperands.push_back(Arg);
953 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
954 NewOperands.push_back(Arg);
956 NewOperands.push_back(RHSo->getOperand(i));
960 // Now run the operator and use its result as the new leaf
961 const OpInit *NewOp = RHSo->clone(NewOperands);
962 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
963 return (NewVal != NewOp) ? NewVal : nullptr;
966 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
967 Record *CurRec, MultiClass *CurMultiClass) {
968 DagInit *MHSd = dyn_cast<DagInit>(MHS);
969 ListInit *MHSl = dyn_cast<ListInit>(MHS);
971 OpInit *RHSo = dyn_cast<OpInit>(RHS);
974 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
976 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
979 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
981 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
983 Init *Val = MHSd->getOperator();
984 Init *Result = EvaluateOperation(RHSo, LHS, Val,
985 Type, CurRec, CurMultiClass);
989 std::vector<std::pair<Init *, std::string> > args;
990 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
993 Arg = MHSd->getArg(i);
994 ArgName = MHSd->getArgName(i);
997 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
998 CurRec, CurMultiClass);
1002 // TODO: Process arg names
1003 args.push_back(std::make_pair(Arg, ArgName));
1006 return DagInit::get(Val, "", args);
1009 std::vector<Init *> NewOperands;
1010 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
1012 for (Init *&Item : NewList) {
1013 NewOperands.clear();
1014 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1015 // First, replace the foreach variable with the list item
1016 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
1017 NewOperands.push_back(Item);
1019 NewOperands.push_back(RHSo->getOperand(i));
1022 // Now run the operator and use its result as the new list item
1023 const OpInit *NewOp = RHSo->clone(NewOperands);
1024 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1025 if (NewItem != NewOp)
1028 return ListInit::get(NewList, MHSl->getType());
1034 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1035 switch (getOpcode()) {
1037 DefInit *LHSd = dyn_cast<DefInit>(LHS);
1038 VarInit *LHSv = dyn_cast<VarInit>(LHS);
1039 StringInit *LHSs = dyn_cast<StringInit>(LHS);
1041 DefInit *MHSd = dyn_cast<DefInit>(MHS);
1042 VarInit *MHSv = dyn_cast<VarInit>(MHS);
1043 StringInit *MHSs = dyn_cast<StringInit>(MHS);
1045 DefInit *RHSd = dyn_cast<DefInit>(RHS);
1046 VarInit *RHSv = dyn_cast<VarInit>(RHS);
1047 StringInit *RHSs = dyn_cast<StringInit>(RHS);
1049 if (LHSd && MHSd && RHSd) {
1050 Record *Val = RHSd->getDef();
1051 if (LHSd->getAsString() == RHSd->getAsString())
1052 Val = MHSd->getDef();
1053 return DefInit::get(Val);
1055 if (LHSv && MHSv && RHSv) {
1056 std::string Val = RHSv->getName();
1057 if (LHSv->getAsString() == RHSv->getAsString())
1058 Val = MHSv->getName();
1059 return VarInit::get(Val, getType());
1061 if (LHSs && MHSs && RHSs) {
1062 std::string Val = RHSs->getValue();
1064 std::string::size_type found;
1065 std::string::size_type idx = 0;
1067 found = Val.find(LHSs->getValue(), idx);
1068 if (found == std::string::npos)
1070 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1071 idx = found + MHSs->getValue().size();
1074 return StringInit::get(Val);
1080 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1081 CurRec, CurMultiClass))
1087 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1088 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1089 LHSi = dyn_cast<IntInit>(I);
1091 if (LHSi->getValue())
1099 return const_cast<TernOpInit *>(this);
1102 Init *TernOpInit::resolveReferences(Record &R,
1103 const RecordVal *RV) const {
1104 Init *lhs = LHS->resolveReferences(R, RV);
1106 if (Opc == IF && lhs != LHS) {
1107 IntInit *Value = dyn_cast<IntInit>(lhs);
1108 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1109 Value = dyn_cast<IntInit>(I);
1112 if (Value->getValue()) {
1113 Init *mhs = MHS->resolveReferences(R, RV);
1114 return (TernOpInit::get(getOpcode(), lhs, mhs,
1115 RHS, getType()))->Fold(&R, nullptr);
1117 Init *rhs = RHS->resolveReferences(R, RV);
1118 return (TernOpInit::get(getOpcode(), lhs, MHS,
1119 rhs, getType()))->Fold(&R, nullptr);
1123 Init *mhs = MHS->resolveReferences(R, RV);
1124 Init *rhs = RHS->resolveReferences(R, RV);
1126 if (LHS != lhs || MHS != mhs || RHS != rhs)
1127 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1128 getType()))->Fold(&R, nullptr);
1129 return Fold(&R, nullptr);
1132 std::string TernOpInit::getAsString() const {
1135 case SUBST: Result = "!subst"; break;
1136 case FOREACH: Result = "!foreach"; break;
1137 case IF: Result = "!if"; break;
1139 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1140 RHS->getAsString() + ")";
1143 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1144 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1145 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1146 return Field->getType();
1151 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1152 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1153 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1154 unsigned NumBits = T->getNumBits();
1156 SmallVector<Init *, 16> NewBits(Bits.size());
1157 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1158 if (Bits[i] >= NumBits)
1161 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1163 return BitsInit::get(NewBits);
1167 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1168 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1169 if (!T) return nullptr; // Cannot subscript a non-list variable.
1171 if (Elements.size() == 1)
1172 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1174 std::vector<Init*> ListInits;
1175 ListInits.reserve(Elements.size());
1176 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1177 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1179 return ListInit::get(ListInits, T);
1183 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1184 Init *Value = StringInit::get(VN);
1185 return VarInit::get(Value, T);
1188 VarInit *VarInit::get(Init *VN, RecTy *T) {
1189 typedef std::pair<RecTy *, Init *> Key;
1190 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1192 Key TheKey(std::make_pair(T, VN));
1194 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1195 if (!I) I.reset(new VarInit(VN, T));
1199 const std::string &VarInit::getName() const {
1200 StringInit *NameString = cast<StringInit>(getNameInit());
1201 return NameString->getValue();
1204 Init *VarInit::getBit(unsigned Bit) const {
1205 if (getType() == BitRecTy::get())
1206 return const_cast<VarInit*>(this);
1207 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1210 Init *VarInit::resolveListElementReference(Record &R,
1211 const RecordVal *IRV,
1212 unsigned Elt) const {
1213 if (R.isTemplateArg(getNameInit())) return nullptr;
1214 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1216 RecordVal *RV = R.getValue(getNameInit());
1217 assert(RV && "Reference to a non-existent variable?");
1218 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1220 return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
1222 if (Elt >= LI->getSize())
1223 return nullptr; // Out of range reference.
1224 Init *E = LI->getElement(Elt);
1225 // If the element is set to some value, or if we are resolving a reference
1226 // to a specific variable and that variable is explicitly unset, then
1227 // replace the VarListElementInit with it.
1228 if (IRV || !isa<UnsetInit>(E))
1234 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1235 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1236 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1237 return RV->getType();
1241 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1242 const std::string &FieldName) const {
1243 if (isa<RecordRecTy>(getType()))
1244 if (const RecordVal *Val = R.getValue(VarName)) {
1245 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1247 Init *TheInit = Val->getValue();
1248 assert(TheInit != this && "Infinite loop detected!");
1249 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1256 /// resolveReferences - This method is used by classes that refer to other
1257 /// variables which may not be defined at the time the expression is formed.
1258 /// If a value is set for the variable later, this method will be called on
1259 /// users of the value to allow the value to propagate out.
1261 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1262 if (RecordVal *Val = R.getValue(VarName))
1263 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1264 return Val->getValue();
1265 return const_cast<VarInit *>(this);
1268 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1269 typedef std::pair<TypedInit *, unsigned> Key;
1270 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1272 Key TheKey(std::make_pair(T, B));
1274 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1275 if (!I) I.reset(new VarBitInit(T, B));
1279 std::string VarBitInit::getAsString() const {
1280 return TI->getAsString() + "{" + utostr(Bit) + "}";
1283 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1284 Init *I = TI->resolveReferences(R, RV);
1286 return I->getBit(getBitNum());
1288 return const_cast<VarBitInit*>(this);
1291 VarListElementInit *VarListElementInit::get(TypedInit *T,
1293 typedef std::pair<TypedInit *, unsigned> Key;
1294 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1296 Key TheKey(std::make_pair(T, E));
1298 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1299 if (!I) I.reset(new VarListElementInit(T, E));
1303 std::string VarListElementInit::getAsString() const {
1304 return TI->getAsString() + "[" + utostr(Element) + "]";
1308 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1309 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1312 return const_cast<VarListElementInit *>(this);
1315 Init *VarListElementInit::getBit(unsigned Bit) const {
1316 if (getType() == BitRecTy::get())
1317 return const_cast<VarListElementInit*>(this);
1318 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1321 Init *VarListElementInit:: resolveListElementReference(Record &R,
1322 const RecordVal *RV,
1323 unsigned Elt) const {
1324 if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
1325 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1326 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1327 if (Result2) return Result2;
1328 return VarListElementInit::get(TInit, Elt);
1336 DefInit *DefInit::get(Record *R) {
1337 return R->getDefInit();
1340 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1341 if (const RecordVal *RV = Def->getValue(FieldName))
1342 return RV->getType();
1346 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1347 const std::string &FieldName) const {
1348 return Def->getValue(FieldName)->getValue();
1352 std::string DefInit::getAsString() const {
1353 return Def->getName();
1356 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1357 typedef std::pair<Init *, TableGenStringKey> Key;
1358 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1360 Key TheKey(std::make_pair(R, FN));
1362 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1363 if (!I) I.reset(new FieldInit(R, FN));
1367 Init *FieldInit::getBit(unsigned Bit) const {
1368 if (getType() == BitRecTy::get())
1369 return const_cast<FieldInit*>(this);
1370 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1373 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1374 unsigned Elt) const {
1375 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1376 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1377 if (Elt >= LI->getSize()) return nullptr;
1378 Init *E = LI->getElement(Elt);
1380 // If the element is set to some value, or if we are resolving a
1381 // reference to a specific variable and that variable is explicitly
1382 // unset, then replace the VarListElementInit with it.
1383 if (RV || !isa<UnsetInit>(E))
1389 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1390 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1392 if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
1393 Init *BVR = BitsVal->resolveReferences(R, RV);
1394 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1398 return FieldInit::get(NewRec, FieldName);
1399 return const_cast<FieldInit *>(this);
1402 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1403 ArrayRef<Init *> ArgRange,
1404 ArrayRef<std::string> NameRange) {
1408 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1409 ArrayRef<std::string>::iterator Name = NameRange.begin();
1410 while (Arg != ArgRange.end()) {
1411 assert(Name != NameRange.end() && "Arg name underflow!");
1412 ID.AddPointer(*Arg++);
1413 ID.AddString(*Name++);
1415 assert(Name == NameRange.end() && "Arg name overflow!");
1419 DagInit::get(Init *V, const std::string &VN,
1420 ArrayRef<Init *> ArgRange,
1421 ArrayRef<std::string> NameRange) {
1422 static FoldingSet<DagInit> ThePool;
1423 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1425 FoldingSetNodeID ID;
1426 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1429 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1432 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1433 ThePool.InsertNode(I, IP);
1434 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1439 DagInit::get(Init *V, const std::string &VN,
1440 const std::vector<std::pair<Init*, std::string> > &args) {
1441 std::vector<Init *> Args;
1442 std::vector<std::string> Names;
1444 for (const auto &Arg : args) {
1445 Args.push_back(Arg.first);
1446 Names.push_back(Arg.second);
1449 return DagInit::get(V, VN, Args, Names);
1452 void DagInit::Profile(FoldingSetNodeID &ID) const {
1453 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1456 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1457 std::vector<Init*> NewArgs;
1458 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1459 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1461 Init *Op = Val->resolveReferences(R, RV);
1463 if (Args != NewArgs || Op != Val)
1464 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1466 return const_cast<DagInit *>(this);
1470 std::string DagInit::getAsString() const {
1471 std::string Result = "(" + Val->getAsString();
1472 if (!ValName.empty())
1473 Result += ":" + ValName;
1474 if (!Args.empty()) {
1475 Result += " " + Args[0]->getAsString();
1476 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1477 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1478 Result += ", " + Args[i]->getAsString();
1479 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1482 return Result + ")";
1486 //===----------------------------------------------------------------------===//
1487 // Other implementations
1488 //===----------------------------------------------------------------------===//
1490 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1491 : Name(N), Ty(T), Prefix(P) {
1492 Value = Ty->convertValue(UnsetInit::get());
1493 assert(Value && "Cannot create unset value for current type!");
1496 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1497 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1498 Value = Ty->convertValue(UnsetInit::get());
1499 assert(Value && "Cannot create unset value for current type!");
1502 const std::string &RecordVal::getName() const {
1503 return cast<StringInit>(Name)->getValue();
1506 void RecordVal::dump() const { errs() << *this; }
1508 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1509 if (getPrefix()) OS << "field ";
1510 OS << *getType() << " " << getNameInitAsString();
1513 OS << " = " << *getValue();
1515 if (PrintSem) OS << ";\n";
1518 unsigned Record::LastID = 0;
1520 void Record::init() {
1523 // Every record potentially has a def at the top. This value is
1524 // replaced with the top-level def name at instantiation time.
1525 RecordVal DN("NAME", StringRecTy::get(), 0);
1529 void Record::checkName() {
1530 // Ensure the record name has string type.
1531 const TypedInit *TypedName = cast<const TypedInit>(Name);
1532 RecTy *Type = TypedName->getType();
1533 if (!isa<StringRecTy>(Type))
1534 PrintFatalError(getLoc(), "Record name is not a string!");
1537 DefInit *Record::getDefInit() {
1538 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1542 std::unique_ptr<DefInit> &I = ThePool[this];
1543 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1547 const std::string &Record::getName() const {
1548 return cast<StringInit>(Name)->getValue();
1551 void Record::setName(Init *NewName) {
1554 // DO NOT resolve record values to the name at this point because
1555 // there might be default values for arguments of this def. Those
1556 // arguments might not have been resolved yet so we don't want to
1557 // prematurely assume values for those arguments were not passed to
1560 // Nonetheless, it may be that some of this Record's values
1561 // reference the record name. Indeed, the reason for having the
1562 // record name be an Init is to provide this flexibility. The extra
1563 // resolve steps after completely instantiating defs takes care of
1564 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1567 void Record::setName(const std::string &Name) {
1568 setName(StringInit::get(Name));
1571 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1572 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1574 void Record::resolveReferencesTo(const RecordVal *RV) {
1575 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1576 if (RV == &Values[i]) // Skip resolve the same field as the given one
1578 if (Init *V = Values[i].getValue())
1579 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1580 PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1581 Values[i].getNameInitAsString() +
1582 "' after resolving references" +
1583 (RV ? " against '" + RV->getNameInitAsString() +
1584 "' of (" + RV->getValue()->getAsUnquotedString() +
1588 Init *OldName = getNameInit();
1589 Init *NewName = Name->resolveReferences(*this, RV);
1590 if (NewName != OldName) {
1591 // Re-register with RecordKeeper.
1596 void Record::dump() const { errs() << *this; }
1598 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1599 OS << R.getNameInitAsString();
1601 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1602 if (!TArgs.empty()) {
1604 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1606 const RecordVal *RV = R.getValue(TArgs[i]);
1607 assert(RV && "Template argument record not found??");
1608 RV->print(OS, false);
1614 const std::vector<Record*> &SC = R.getSuperClasses();
1617 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1618 OS << " " << SC[i]->getNameInitAsString();
1622 const std::vector<RecordVal> &Vals = R.getValues();
1623 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1624 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1626 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1627 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1633 /// getValueInit - Return the initializer for a value with the specified name,
1634 /// or abort if the field does not exist.
1636 Init *Record::getValueInit(StringRef FieldName) const {
1637 const RecordVal *R = getValue(FieldName);
1638 if (!R || !R->getValue())
1639 PrintFatalError(getLoc(), "Record `" + getName() +
1640 "' does not have a field named `" + FieldName + "'!\n");
1641 return R->getValue();
1645 /// getValueAsString - This method looks up the specified field and returns its
1646 /// value as a string, aborts if the field does not exist or if
1647 /// the value is not a string.
1649 std::string Record::getValueAsString(StringRef FieldName) const {
1650 const RecordVal *R = getValue(FieldName);
1651 if (!R || !R->getValue())
1652 PrintFatalError(getLoc(), "Record `" + getName() +
1653 "' does not have a field named `" + FieldName + "'!\n");
1655 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1656 return SI->getValue();
1657 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1658 FieldName + "' does not have a string initializer!");
1661 /// getValueAsBitsInit - This method looks up the specified field and returns
1662 /// its value as a BitsInit, aborts if the field does not exist or if
1663 /// the value is not the right type.
1665 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1666 const RecordVal *R = getValue(FieldName);
1667 if (!R || !R->getValue())
1668 PrintFatalError(getLoc(), "Record `" + getName() +
1669 "' does not have a field named `" + FieldName + "'!\n");
1671 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1673 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1674 FieldName + "' does not have a BitsInit initializer!");
1677 /// getValueAsListInit - This method looks up the specified field and returns
1678 /// its value as a ListInit, aborting if the field does not exist or if
1679 /// the value is not the right type.
1681 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1682 const RecordVal *R = getValue(FieldName);
1683 if (!R || !R->getValue())
1684 PrintFatalError(getLoc(), "Record `" + getName() +
1685 "' does not have a field named `" + FieldName + "'!\n");
1687 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1689 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1690 FieldName + "' does not have a list initializer!");
1693 /// getValueAsListOfDefs - This method looks up the specified field and returns
1694 /// its value as a vector of records, aborting if the field does not exist
1695 /// or if the value is not the right type.
1697 std::vector<Record*>
1698 Record::getValueAsListOfDefs(StringRef FieldName) const {
1699 ListInit *List = getValueAsListInit(FieldName);
1700 std::vector<Record*> Defs;
1701 for (unsigned i = 0; i < List->getSize(); i++) {
1702 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i)))
1703 Defs.push_back(DI->getDef());
1705 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1706 FieldName + "' list is not entirely DefInit!");
1711 /// getValueAsInt - This method looks up the specified field and returns its
1712 /// value as an int64_t, aborting if the field does not exist or if the value
1713 /// is not the right type.
1715 int64_t Record::getValueAsInt(StringRef FieldName) const {
1716 const RecordVal *R = getValue(FieldName);
1717 if (!R || !R->getValue())
1718 PrintFatalError(getLoc(), "Record `" + getName() +
1719 "' does not have a field named `" + FieldName + "'!\n");
1721 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1722 return II->getValue();
1723 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1724 FieldName + "' does not have an int initializer!");
1727 /// getValueAsListOfInts - This method looks up the specified field and returns
1728 /// its value as a vector of integers, aborting if the field does not exist or
1729 /// if the value is not the right type.
1731 std::vector<int64_t>
1732 Record::getValueAsListOfInts(StringRef FieldName) const {
1733 ListInit *List = getValueAsListInit(FieldName);
1734 std::vector<int64_t> Ints;
1735 for (unsigned i = 0; i < List->getSize(); i++) {
1736 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i)))
1737 Ints.push_back(II->getValue());
1739 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1740 FieldName + "' does not have a list of ints initializer!");
1745 /// getValueAsListOfStrings - This method looks up the specified field and
1746 /// returns its value as a vector of strings, aborting if the field does not
1747 /// exist or if the value is not the right type.
1749 std::vector<std::string>
1750 Record::getValueAsListOfStrings(StringRef FieldName) const {
1751 ListInit *List = getValueAsListInit(FieldName);
1752 std::vector<std::string> Strings;
1753 for (unsigned i = 0; i < List->getSize(); i++) {
1754 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i)))
1755 Strings.push_back(II->getValue());
1757 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1758 FieldName + "' does not have a list of strings initializer!");
1763 /// getValueAsDef - This method looks up the specified field and returns its
1764 /// value as a Record, aborting if the field does not exist or if the value
1765 /// is not the right type.
1767 Record *Record::getValueAsDef(StringRef FieldName) const {
1768 const RecordVal *R = getValue(FieldName);
1769 if (!R || !R->getValue())
1770 PrintFatalError(getLoc(), "Record `" + getName() +
1771 "' does not have a field named `" + FieldName + "'!\n");
1773 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1774 return DI->getDef();
1775 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1776 FieldName + "' does not have a def initializer!");
1779 /// getValueAsBit - This method looks up the specified field and returns its
1780 /// value as a bit, aborting if the field does not exist or if the value is
1781 /// not the right type.
1783 bool Record::getValueAsBit(StringRef FieldName) const {
1784 const RecordVal *R = getValue(FieldName);
1785 if (!R || !R->getValue())
1786 PrintFatalError(getLoc(), "Record `" + getName() +
1787 "' does not have a field named `" + FieldName + "'!\n");
1789 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1790 return BI->getValue();
1791 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1792 FieldName + "' does not have a bit initializer!");
1795 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1796 const RecordVal *R = getValue(FieldName);
1797 if (!R || !R->getValue())
1798 PrintFatalError(getLoc(), "Record `" + getName() +
1799 "' does not have a field named `" + FieldName.str() + "'!\n");
1801 if (isa<UnsetInit>(R->getValue())) {
1806 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1807 return BI->getValue();
1808 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1809 FieldName + "' does not have a bit initializer!");
1812 /// getValueAsDag - This method looks up the specified field and returns its
1813 /// value as an Dag, aborting if the field does not exist or if the value is
1814 /// not the right type.
1816 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1817 const RecordVal *R = getValue(FieldName);
1818 if (!R || !R->getValue())
1819 PrintFatalError(getLoc(), "Record `" + getName() +
1820 "' does not have a field named `" + FieldName + "'!\n");
1822 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1824 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1825 FieldName + "' does not have a dag initializer!");
1829 void MultiClass::dump() const {
1830 errs() << "Record:\n";
1833 errs() << "Defs:\n";
1834 for (const auto &Proto : DefPrototypes)
1839 void RecordKeeper::dump() const { errs() << *this; }
1841 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1842 OS << "------------- Classes -----------------\n";
1843 for (const auto &C : RK.getClasses())
1844 OS << "class " << *C.second;
1846 OS << "------------- Defs -----------------\n";
1847 for (const auto &D : RK.getDefs())
1848 OS << "def " << *D.second;
1853 /// getAllDerivedDefinitions - This method returns all concrete definitions
1854 /// that derive from the specified class name. If a class with the specified
1855 /// name does not exist, an error is printed and true is returned.
1856 std::vector<Record*>
1857 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1858 Record *Class = getClass(ClassName);
1860 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1862 std::vector<Record*> Defs;
1863 for (const auto &D : getDefs())
1864 if (D.second->isSubClassOf(Class))
1865 Defs.push_back(D.second.get());
1870 /// QualifyName - Return an Init with a qualifier prefix referring
1871 /// to CurRec's name.
1872 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1873 Init *Name, const std::string &Scoper) {
1874 RecTy *Type = cast<TypedInit>(Name)->getType();
1876 BinOpInit *NewName =
1877 BinOpInit::get(BinOpInit::STRCONCAT,
1878 BinOpInit::get(BinOpInit::STRCONCAT,
1879 CurRec.getNameInit(),
1880 StringInit::get(Scoper),
1881 Type)->Fold(&CurRec, CurMultiClass),
1885 if (CurMultiClass && Scoper != "::") {
1887 BinOpInit::get(BinOpInit::STRCONCAT,
1888 BinOpInit::get(BinOpInit::STRCONCAT,
1889 CurMultiClass->Rec.getNameInit(),
1890 StringInit::get("::"),
1891 Type)->Fold(&CurRec, CurMultiClass),
1892 NewName->Fold(&CurRec, CurMultiClass),
1896 return NewName->Fold(&CurRec, CurMultiClass);
1899 /// QualifyName - Return an Init with a qualifier prefix referring
1900 /// to CurRec's name.
1901 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1902 const std::string &Name,
1903 const std::string &Scoper) {
1904 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);