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 void StringRecTy::anchor() { }
93 void DagRecTy::anchor() { }
95 ListRecTy *RecTy::getListTy() {
97 ListTy.reset(new ListRecTy(this));
101 bool RecTy::baseClassOf(const RecTy *RHS) const {
102 assert (RHS && "NULL pointer");
103 return Kind == RHS->getRecTyKind();
106 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
107 if(RecTy::baseClassOf(RHS) || RHS->getRecTyKind() == IntRecTyKind)
109 if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
110 return BitsTy->getNumBits() == 1;
114 BitsRecTy *BitsRecTy::get(unsigned Sz) {
115 static std::vector<std::unique_ptr<BitsRecTy>> Shared;
116 if (Sz >= Shared.size())
117 Shared.resize(Sz + 1);
118 std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
120 Ty.reset(new BitsRecTy(Sz));
124 std::string BitsRecTy::getAsString() const {
125 return "bits<" + utostr(Size) + ">";
128 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
129 if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
130 return cast<BitsRecTy>(RHS)->Size == Size;
131 RecTyKind kind = RHS->getRecTyKind();
132 return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
135 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
136 RecTyKind kind = RHS->getRecTyKind();
137 return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
141 std::string ListRecTy::getAsString() const {
142 return "list<" + Ty->getAsString() + ">";
145 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
146 if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
147 return ListTy->getElementType()->typeIsConvertibleTo(Ty);
151 RecordRecTy *RecordRecTy::get(Record *R) {
152 return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
155 std::string RecordRecTy::getAsString() const {
156 return Rec->getName();
159 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
160 const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
164 if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
167 const std::vector<Record*> &SC = Rec->getSuperClasses();
168 for (unsigned i = 0, e = SC.size(); i != e; ++i)
169 if (RTy->getRecord()->isSubClassOf(SC[i]))
175 /// resolveTypes - Find a common type that T1 and T2 convert to.
176 /// Return null if no such type exists.
178 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
179 if (T1->typeIsConvertibleTo(T2))
181 if (T2->typeIsConvertibleTo(T1))
184 // If one is a Record type, check superclasses
185 if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
186 // See if T2 inherits from a type T1 also inherits from
187 for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
188 RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
189 RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
194 if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
195 // See if T1 inherits from a type T2 also inherits from
196 for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
197 RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
198 RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
207 //===----------------------------------------------------------------------===//
208 // Initializer implementations
209 //===----------------------------------------------------------------------===//
211 void Init::anchor() { }
212 void Init::dump() const { return print(errs()); }
214 UnsetInit *UnsetInit::get() {
215 static UnsetInit TheInit;
219 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
220 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
221 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
223 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
224 NewBits[i] = UnsetInit::get();
226 return BitsInit::get(NewBits);
229 // All other types can just be returned.
230 return const_cast<UnsetInit *>(this);
233 BitInit *BitInit::get(bool V) {
234 static BitInit True(true);
235 static BitInit False(false);
237 return V ? &True : &False;
240 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
241 if (isa<BitRecTy>(Ty))
242 return const_cast<BitInit *>(this);
244 if (isa<IntRecTy>(Ty))
245 return IntInit::get(getValue());
247 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
248 // Can only convert single bit.
249 if (BRT->getNumBits() == 1)
250 return BitsInit::get(const_cast<BitInit *>(this));
257 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
258 ID.AddInteger(Range.size());
260 for (Init *I : Range)
264 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
265 static FoldingSet<BitsInit> ThePool;
266 static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
269 ProfileBitsInit(ID, Range);
272 if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
275 BitsInit *I = new BitsInit(Range);
276 ThePool.InsertNode(I, IP);
277 TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
281 void BitsInit::Profile(FoldingSetNodeID &ID) const {
282 ProfileBitsInit(ID, Bits);
285 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
286 if (isa<BitRecTy>(Ty)) {
287 if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
291 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
292 // If the number of bits is right, return it. Otherwise we need to expand
294 if (getNumBits() != BRT->getNumBits()) return nullptr;
295 return const_cast<BitsInit *>(this);
298 if (isa<IntRecTy>(Ty)) {
300 for (unsigned i = 0, e = getNumBits(); i != e; ++i)
301 if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
302 Result |= static_cast<int64_t>(Bit->getValue()) << i;
305 return IntInit::get(Result);
312 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
313 SmallVector<Init *, 16> NewBits(Bits.size());
315 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
316 if (Bits[i] >= getNumBits())
318 NewBits[i] = getBit(Bits[i]);
320 return BitsInit::get(NewBits);
323 std::string BitsInit::getAsString() const {
324 std::string Result = "{ ";
325 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
326 if (i) Result += ", ";
327 if (Init *Bit = getBit(e-i-1))
328 Result += Bit->getAsString();
332 return Result + " }";
335 // Fix bit initializer to preserve the behavior that bit reference from a unset
336 // bits initializer will resolve into VarBitInit to keep the field name and bit
337 // number used in targets with fixed insn length.
338 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
339 if (RV || !isa<UnsetInit>(After))
344 // resolveReferences - If there are any field references that refer to fields
345 // that have been filled in, we can propagate the values now.
347 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
348 bool Changed = false;
349 SmallVector<Init *, 16> NewBits(getNumBits());
351 Init *CachedInit = nullptr;
352 Init *CachedBitVar = nullptr;
353 bool CachedBitVarChanged = false;
355 for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
356 Init *CurBit = Bits[i];
357 Init *CurBitVar = CurBit->getBitVar();
361 if (CurBitVar == CachedBitVar) {
362 if (CachedBitVarChanged) {
363 Init *Bit = CachedInit->getBit(CurBit->getBitNum());
364 NewBits[i] = fixBitInit(RV, CurBit, Bit);
368 CachedBitVar = CurBitVar;
369 CachedBitVarChanged = false;
374 CurBitVar = CurBitVar->resolveReferences(R, RV);
375 CachedBitVarChanged |= B != CurBitVar;
376 Changed |= B != CurBitVar;
377 } while (B != CurBitVar);
378 CachedInit = CurBitVar;
380 if (CachedBitVarChanged) {
381 Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
382 NewBits[i] = fixBitInit(RV, CurBit, Bit);
387 return BitsInit::get(NewBits);
389 return const_cast<BitsInit *>(this);
392 IntInit *IntInit::get(int64_t V) {
393 static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
395 std::unique_ptr<IntInit> &I = ThePool[V];
396 if (!I) I.reset(new IntInit(V));
400 std::string IntInit::getAsString() const {
401 return itostr(Value);
404 /// canFitInBitfield - Return true if the number of bits is large enough to hold
405 /// the integer value.
406 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
407 // For example, with NumBits == 4, we permit Values from [-7 .. 15].
408 return (NumBits >= sizeof(Value) * 8) ||
409 (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
412 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
413 if (isa<IntRecTy>(Ty))
414 return const_cast<IntInit *>(this);
416 if (isa<BitRecTy>(Ty)) {
417 int64_t Val = getValue();
418 if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
419 return BitInit::get(Val != 0);
422 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
423 int64_t Value = getValue();
424 // Make sure this bitfield is large enough to hold the integer value.
425 if (!canFitInBitfield(Value, BRT->getNumBits()))
428 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
429 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
430 NewBits[i] = BitInit::get(Value & (1LL << i));
432 return BitsInit::get(NewBits);
439 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
440 SmallVector<Init *, 16> NewBits(Bits.size());
442 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
446 NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
448 return BitsInit::get(NewBits);
451 StringInit *StringInit::get(StringRef V) {
452 static StringMap<std::unique_ptr<StringInit>> ThePool;
454 std::unique_ptr<StringInit> &I = ThePool[V];
455 if (!I) I.reset(new StringInit(V));
459 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
460 if (isa<StringRecTy>(Ty))
461 return const_cast<StringInit *>(this);
466 static void ProfileListInit(FoldingSetNodeID &ID,
467 ArrayRef<Init *> Range,
469 ID.AddInteger(Range.size());
470 ID.AddPointer(EltTy);
472 for (Init *I : Range)
476 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
477 static FoldingSet<ListInit> ThePool;
478 static std::vector<std::unique_ptr<ListInit>> TheActualPool;
481 ProfileListInit(ID, Range, EltTy);
484 if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
487 ListInit *I = new ListInit(Range, EltTy);
488 ThePool.InsertNode(I, IP);
489 TheActualPool.push_back(std::unique_ptr<ListInit>(I));
493 void ListInit::Profile(FoldingSetNodeID &ID) const {
494 RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
496 ProfileListInit(ID, Values, EltTy);
499 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
500 if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
501 std::vector<Init*> Elements;
503 // Verify that all of the elements of the list are subclasses of the
504 // appropriate class!
505 for (unsigned i = 0, e = getSize(); i != e; ++i)
506 if (Init *CI = getElement(i)->convertInitializerTo(LRT->getElementType()))
507 Elements.push_back(CI);
511 if (isa<ListRecTy>(getType()))
512 return ListInit::get(Elements, Ty);
519 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
520 std::vector<Init*> Vals;
521 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
522 if (Elements[i] >= getSize())
524 Vals.push_back(getElement(Elements[i]));
526 return ListInit::get(Vals, getType());
529 Record *ListInit::getElementAsRecord(unsigned i) const {
530 assert(i < Values.size() && "List element index out of range!");
531 DefInit *DI = dyn_cast<DefInit>(Values[i]);
533 PrintFatalError("Expected record in list!");
537 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
538 std::vector<Init*> Resolved;
539 Resolved.reserve(getSize());
540 bool Changed = false;
542 for (unsigned i = 0, e = getSize(); i != e; ++i) {
544 Init *CurElt = getElement(i);
548 CurElt = CurElt->resolveReferences(R, RV);
549 Changed |= E != CurElt;
550 } while (E != CurElt);
551 Resolved.push_back(E);
555 return ListInit::get(Resolved, getType());
556 return const_cast<ListInit *>(this);
559 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
560 unsigned Elt) const {
561 if (Elt >= getSize())
562 return nullptr; // Out of range reference.
563 Init *E = getElement(Elt);
564 // If the element is set to some value, or if we are resolving a reference
565 // to a specific variable and that variable is explicitly unset, then
566 // replace the VarListElementInit with it.
567 if (IRV || !isa<UnsetInit>(E))
572 std::string ListInit::getAsString() const {
573 std::string Result = "[";
574 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
575 if (i) Result += ", ";
576 Result += Values[i]->getAsString();
581 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
582 unsigned Elt) const {
583 Init *Resolved = resolveReferences(R, IRV);
584 OpInit *OResolved = dyn_cast<OpInit>(Resolved);
586 Resolved = OResolved->Fold(&R, nullptr);
589 if (Resolved != this) {
590 TypedInit *Typed = cast<TypedInit>(Resolved);
591 if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
593 return VarListElementInit::get(Typed, Elt);
599 Init *OpInit::getBit(unsigned Bit) const {
600 if (getType() == BitRecTy::get())
601 return const_cast<OpInit*>(this);
602 return VarBitInit::get(const_cast<OpInit*>(this), Bit);
605 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
606 typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
607 static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
609 Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
611 std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
612 if (!I) I.reset(new UnOpInit(opc, lhs, Type));
616 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
617 switch (getOpcode()) {
619 if (isa<StringRecTy>(getType())) {
620 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
623 if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
624 return StringInit::get(LHSd->getAsString());
626 if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
627 return StringInit::get(LHSi->getAsString());
629 if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
630 std::string Name = LHSs->getValue();
632 // From TGParser::ParseIDValue
634 if (const RecordVal *RV = CurRec->getValue(Name)) {
635 if (RV->getType() != getType())
636 PrintFatalError("type mismatch in cast");
637 return VarInit::get(Name, RV->getType());
640 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
643 if (CurRec->isTemplateArg(TemplateArgName)) {
644 const RecordVal *RV = CurRec->getValue(TemplateArgName);
645 assert(RV && "Template arg doesn't exist??");
647 if (RV->getType() != getType())
648 PrintFatalError("type mismatch in cast");
650 return VarInit::get(TemplateArgName, RV->getType());
655 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
658 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
659 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
660 assert(RV && "Template arg doesn't exist??");
662 if (RV->getType() != getType())
663 PrintFatalError("type mismatch in cast");
665 return VarInit::get(MCName, RV->getType());
668 assert(CurRec && "NULL pointer");
669 if (Record *D = (CurRec->getRecords()).getDef(Name))
670 return DefInit::get(D);
672 PrintFatalError(CurRec->getLoc(),
673 "Undefined reference:'" + Name + "'\n");
679 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
680 assert(!LHSl->empty() && "Empty list in head");
681 return LHSl->getElement(0);
686 if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
687 assert(!LHSl->empty() && "Empty list in tail");
688 // Note the +1. We can't just pass the result of getValues()
690 return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
695 if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
696 return IntInit::get(LHSl->empty());
697 if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
698 return IntInit::get(LHSs->getValue().empty());
703 return const_cast<UnOpInit *>(this);
706 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
707 Init *lhs = LHS->resolveReferences(R, RV);
710 return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
711 return Fold(&R, nullptr);
714 std::string UnOpInit::getAsString() const {
717 case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
718 case HEAD: Result = "!head"; break;
719 case TAIL: Result = "!tail"; break;
720 case EMPTY: Result = "!empty"; break;
722 return Result + "(" + LHS->getAsString() + ")";
725 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
726 Init *rhs, RecTy *Type) {
728 std::pair<std::pair<unsigned, Init *>, Init *>,
732 static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
734 Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
737 std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
738 if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
742 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
743 switch (getOpcode()) {
745 DagInit *LHSs = dyn_cast<DagInit>(LHS);
746 DagInit *RHSs = dyn_cast<DagInit>(RHS);
748 DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
749 DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
750 if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
751 PrintFatalError("Concated Dag operators do not match!");
752 std::vector<Init*> Args;
753 std::vector<std::string> ArgNames;
754 for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
755 Args.push_back(LHSs->getArg(i));
756 ArgNames.push_back(LHSs->getArgName(i));
758 for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
759 Args.push_back(RHSs->getArg(i));
760 ArgNames.push_back(RHSs->getArgName(i));
762 return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
767 ListInit *LHSs = dyn_cast<ListInit>(LHS);
768 ListInit *RHSs = dyn_cast<ListInit>(RHS);
770 std::vector<Init *> Args;
771 Args.insert(Args.end(), LHSs->begin(), LHSs->end());
772 Args.insert(Args.end(), RHSs->begin(), RHSs->end());
773 return ListInit::get(
774 Args, cast<ListRecTy>(LHSs->getType())->getElementType());
779 StringInit *LHSs = dyn_cast<StringInit>(LHS);
780 StringInit *RHSs = dyn_cast<StringInit>(RHS);
782 return StringInit::get(LHSs->getValue() + RHSs->getValue());
786 // try to fold eq comparison for 'bit' and 'int', otherwise fallback
787 // to string objects.
789 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
791 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
794 return IntInit::get(L->getValue() == R->getValue());
796 StringInit *LHSs = dyn_cast<StringInit>(LHS);
797 StringInit *RHSs = dyn_cast<StringInit>(RHS);
799 // Make sure we've resolved
801 return IntInit::get(LHSs->getValue() == RHSs->getValue());
811 dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
813 dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
815 int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
817 switch (getOpcode()) {
818 default: llvm_unreachable("Bad opcode!");
819 case ADD: Result = LHSv + RHSv; break;
820 case AND: Result = LHSv & RHSv; break;
821 case SHL: Result = LHSv << RHSv; break;
822 case SRA: Result = LHSv >> RHSv; break;
823 case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
825 return IntInit::get(Result);
830 return const_cast<BinOpInit *>(this);
833 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
834 Init *lhs = LHS->resolveReferences(R, RV);
835 Init *rhs = RHS->resolveReferences(R, RV);
837 if (LHS != lhs || RHS != rhs)
838 return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
839 return Fold(&R, nullptr);
842 std::string BinOpInit::getAsString() const {
845 case CONCAT: Result = "!con"; break;
846 case ADD: Result = "!add"; break;
847 case AND: Result = "!and"; break;
848 case SHL: Result = "!shl"; break;
849 case SRA: Result = "!sra"; break;
850 case SRL: Result = "!srl"; break;
851 case EQ: Result = "!eq"; break;
852 case LISTCONCAT: Result = "!listconcat"; break;
853 case STRCONCAT: Result = "!strconcat"; break;
855 return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
858 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
862 std::pair<std::pair<unsigned, RecTy *>, Init *>,
868 static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
870 Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
876 std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
877 if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
881 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
882 Record *CurRec, MultiClass *CurMultiClass);
884 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
885 RecTy *Type, Record *CurRec,
886 MultiClass *CurMultiClass) {
887 // If this is a dag, recurse
888 if (auto *TArg = dyn_cast<TypedInit>(Arg))
889 if (isa<DagRecTy>(TArg->getType()))
890 return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
892 std::vector<Init *> NewOperands;
893 for (int i = 0; i < RHSo->getNumOperands(); ++i) {
894 if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
895 if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
896 Type, CurRec, CurMultiClass))
897 NewOperands.push_back(Result);
899 NewOperands.push_back(Arg);
900 } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
901 NewOperands.push_back(Arg);
903 NewOperands.push_back(RHSo->getOperand(i));
907 // Now run the operator and use its result as the new leaf
908 const OpInit *NewOp = RHSo->clone(NewOperands);
909 Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
910 return (NewVal != NewOp) ? NewVal : nullptr;
913 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
914 Record *CurRec, MultiClass *CurMultiClass) {
915 DagInit *MHSd = dyn_cast<DagInit>(MHS);
916 ListInit *MHSl = dyn_cast<ListInit>(MHS);
918 OpInit *RHSo = dyn_cast<OpInit>(RHS);
921 PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
923 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
926 PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
928 if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
930 Init *Val = MHSd->getOperator();
931 Init *Result = EvaluateOperation(RHSo, LHS, Val,
932 Type, CurRec, CurMultiClass);
936 std::vector<std::pair<Init *, std::string> > args;
937 for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
940 Arg = MHSd->getArg(i);
941 ArgName = MHSd->getArgName(i);
944 Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
945 CurRec, CurMultiClass);
949 // TODO: Process arg names
950 args.push_back(std::make_pair(Arg, ArgName));
953 return DagInit::get(Val, "", args);
956 std::vector<Init *> NewOperands;
957 std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
959 for (Init *&Item : NewList) {
961 for(int i = 0; i < RHSo->getNumOperands(); ++i) {
962 // First, replace the foreach variable with the list item
963 if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
964 NewOperands.push_back(Item);
966 NewOperands.push_back(RHSo->getOperand(i));
969 // Now run the operator and use its result as the new list item
970 const OpInit *NewOp = RHSo->clone(NewOperands);
971 Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
972 if (NewItem != NewOp)
975 return ListInit::get(NewList, MHSl->getType());
981 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
982 switch (getOpcode()) {
984 DefInit *LHSd = dyn_cast<DefInit>(LHS);
985 VarInit *LHSv = dyn_cast<VarInit>(LHS);
986 StringInit *LHSs = dyn_cast<StringInit>(LHS);
988 DefInit *MHSd = dyn_cast<DefInit>(MHS);
989 VarInit *MHSv = dyn_cast<VarInit>(MHS);
990 StringInit *MHSs = dyn_cast<StringInit>(MHS);
992 DefInit *RHSd = dyn_cast<DefInit>(RHS);
993 VarInit *RHSv = dyn_cast<VarInit>(RHS);
994 StringInit *RHSs = dyn_cast<StringInit>(RHS);
996 if (LHSd && MHSd && RHSd) {
997 Record *Val = RHSd->getDef();
998 if (LHSd->getAsString() == RHSd->getAsString())
999 Val = MHSd->getDef();
1000 return DefInit::get(Val);
1002 if (LHSv && MHSv && RHSv) {
1003 std::string Val = RHSv->getName();
1004 if (LHSv->getAsString() == RHSv->getAsString())
1005 Val = MHSv->getName();
1006 return VarInit::get(Val, getType());
1008 if (LHSs && MHSs && RHSs) {
1009 std::string Val = RHSs->getValue();
1011 std::string::size_type found;
1012 std::string::size_type idx = 0;
1014 found = Val.find(LHSs->getValue(), idx);
1015 if (found == std::string::npos)
1017 Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1018 idx = found + MHSs->getValue().size();
1021 return StringInit::get(Val);
1027 if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1028 CurRec, CurMultiClass))
1034 IntInit *LHSi = dyn_cast<IntInit>(LHS);
1035 if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1036 LHSi = dyn_cast<IntInit>(I);
1038 if (LHSi->getValue())
1046 return const_cast<TernOpInit *>(this);
1049 Init *TernOpInit::resolveReferences(Record &R,
1050 const RecordVal *RV) const {
1051 Init *lhs = LHS->resolveReferences(R, RV);
1053 if (Opc == IF && lhs != LHS) {
1054 IntInit *Value = dyn_cast<IntInit>(lhs);
1055 if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1056 Value = dyn_cast<IntInit>(I);
1059 if (Value->getValue()) {
1060 Init *mhs = MHS->resolveReferences(R, RV);
1061 return (TernOpInit::get(getOpcode(), lhs, mhs,
1062 RHS, getType()))->Fold(&R, nullptr);
1064 Init *rhs = RHS->resolveReferences(R, RV);
1065 return (TernOpInit::get(getOpcode(), lhs, MHS,
1066 rhs, getType()))->Fold(&R, nullptr);
1070 Init *mhs = MHS->resolveReferences(R, RV);
1071 Init *rhs = RHS->resolveReferences(R, RV);
1073 if (LHS != lhs || MHS != mhs || RHS != rhs)
1074 return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1075 getType()))->Fold(&R, nullptr);
1076 return Fold(&R, nullptr);
1079 std::string TernOpInit::getAsString() const {
1082 case SUBST: Result = "!subst"; break;
1083 case FOREACH: Result = "!foreach"; break;
1084 case IF: Result = "!if"; break;
1086 return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
1087 RHS->getAsString() + ")";
1090 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1091 if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
1092 if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
1093 return Field->getType();
1098 TypedInit::convertInitializerTo(RecTy *Ty) const {
1099 if (isa<IntRecTy>(Ty)) {
1100 if (getType()->typeIsConvertibleTo(Ty))
1101 return const_cast<TypedInit *>(this);
1105 if (isa<StringRecTy>(Ty)) {
1106 if (isa<StringRecTy>(getType()))
1107 return const_cast<TypedInit *>(this);
1111 if (isa<BitRecTy>(Ty)) {
1112 // Accept variable if it is already of bit type!
1113 if (isa<BitRecTy>(getType()))
1114 return const_cast<TypedInit *>(this);
1115 if (auto *BitsTy = dyn_cast<BitsRecTy>(getType())) {
1116 // Accept only bits<1> expression.
1117 if (BitsTy->getNumBits() == 1)
1118 return const_cast<TypedInit *>(this);
1121 // Ternary !if can be converted to bit, but only if both sides are
1122 // convertible to a bit.
1123 if (const auto *TOI = dyn_cast<TernOpInit>(this)) {
1124 if (TOI->getOpcode() == TernOpInit::TernaryOp::IF &&
1125 TOI->getMHS()->convertInitializerTo(BitRecTy::get()) &&
1126 TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
1127 return const_cast<TypedInit *>(this);
1133 if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
1134 if (BRT->getNumBits() == 1 && isa<BitRecTy>(getType()))
1135 return BitsInit::get(const_cast<TypedInit *>(this));
1137 if (getType()->typeIsConvertibleTo(BRT)) {
1138 SmallVector<Init *, 16> NewBits(BRT->getNumBits());
1140 for (unsigned i = 0; i != BRT->getNumBits(); ++i)
1141 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), i);
1142 return BitsInit::get(NewBits);
1148 if (auto *DLRT = dyn_cast<ListRecTy>(Ty)) {
1149 if (auto *SLRT = dyn_cast<ListRecTy>(getType()))
1150 if (SLRT->getElementType()->typeIsConvertibleTo(DLRT->getElementType()))
1151 return const_cast<TypedInit *>(this);
1155 if (auto *DRT = dyn_cast<DagRecTy>(Ty)) {
1156 if (getType()->typeIsConvertibleTo(DRT))
1157 return const_cast<TypedInit *>(this);
1161 if (auto *SRRT = dyn_cast<RecordRecTy>(Ty)) {
1162 // Ensure that this is compatible with Rec.
1163 if (RecordRecTy *DRRT = dyn_cast<RecordRecTy>(getType()))
1164 if (DRRT->getRecord()->isSubClassOf(SRRT->getRecord()) ||
1165 DRRT->getRecord() == SRRT->getRecord())
1166 return const_cast<TypedInit *>(this);
1174 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1175 BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
1176 if (!T) return nullptr; // Cannot subscript a non-bits variable.
1177 unsigned NumBits = T->getNumBits();
1179 SmallVector<Init *, 16> NewBits(Bits.size());
1180 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1181 if (Bits[i] >= NumBits)
1184 NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
1186 return BitsInit::get(NewBits);
1190 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1191 ListRecTy *T = dyn_cast<ListRecTy>(getType());
1192 if (!T) return nullptr; // Cannot subscript a non-list variable.
1194 if (Elements.size() == 1)
1195 return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
1197 std::vector<Init*> ListInits;
1198 ListInits.reserve(Elements.size());
1199 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1200 ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
1202 return ListInit::get(ListInits, T);
1206 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1207 Init *Value = StringInit::get(VN);
1208 return VarInit::get(Value, T);
1211 VarInit *VarInit::get(Init *VN, RecTy *T) {
1212 typedef std::pair<RecTy *, Init *> Key;
1213 static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
1215 Key TheKey(std::make_pair(T, VN));
1217 std::unique_ptr<VarInit> &I = ThePool[TheKey];
1218 if (!I) I.reset(new VarInit(VN, T));
1222 const std::string &VarInit::getName() const {
1223 StringInit *NameString = cast<StringInit>(getNameInit());
1224 return NameString->getValue();
1227 Init *VarInit::getBit(unsigned Bit) const {
1228 if (getType() == BitRecTy::get())
1229 return const_cast<VarInit*>(this);
1230 return VarBitInit::get(const_cast<VarInit*>(this), Bit);
1233 Init *VarInit::resolveListElementReference(Record &R,
1234 const RecordVal *IRV,
1235 unsigned Elt) const {
1236 if (R.isTemplateArg(getNameInit())) return nullptr;
1237 if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
1239 RecordVal *RV = R.getValue(getNameInit());
1240 assert(RV && "Reference to a non-existent variable?");
1241 ListInit *LI = dyn_cast<ListInit>(RV->getValue());
1243 return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
1245 if (Elt >= LI->getSize())
1246 return nullptr; // Out of range reference.
1247 Init *E = LI->getElement(Elt);
1248 // If the element is set to some value, or if we are resolving a reference
1249 // to a specific variable and that variable is explicitly unset, then
1250 // replace the VarListElementInit with it.
1251 if (IRV || !isa<UnsetInit>(E))
1257 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1258 if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
1259 if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1260 return RV->getType();
1264 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1265 const std::string &FieldName) const {
1266 if (isa<RecordRecTy>(getType()))
1267 if (const RecordVal *Val = R.getValue(VarName)) {
1268 if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
1270 Init *TheInit = Val->getValue();
1271 assert(TheInit != this && "Infinite loop detected!");
1272 if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
1279 /// resolveReferences - This method is used by classes that refer to other
1280 /// variables which may not be defined at the time the expression is formed.
1281 /// If a value is set for the variable later, this method will be called on
1282 /// users of the value to allow the value to propagate out.
1284 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1285 if (RecordVal *Val = R.getValue(VarName))
1286 if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
1287 return Val->getValue();
1288 return const_cast<VarInit *>(this);
1291 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
1292 typedef std::pair<TypedInit *, unsigned> Key;
1293 static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
1295 Key TheKey(std::make_pair(T, B));
1297 std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
1298 if (!I) I.reset(new VarBitInit(T, B));
1302 Init *VarBitInit::convertInitializerTo(RecTy *Ty) const {
1303 if (isa<BitRecTy>(Ty))
1304 return const_cast<VarBitInit *>(this);
1309 std::string VarBitInit::getAsString() const {
1310 return TI->getAsString() + "{" + utostr(Bit) + "}";
1313 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
1314 Init *I = TI->resolveReferences(R, RV);
1316 return I->getBit(getBitNum());
1318 return const_cast<VarBitInit*>(this);
1321 VarListElementInit *VarListElementInit::get(TypedInit *T,
1323 typedef std::pair<TypedInit *, unsigned> Key;
1324 static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
1326 Key TheKey(std::make_pair(T, E));
1328 std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
1329 if (!I) I.reset(new VarListElementInit(T, E));
1333 std::string VarListElementInit::getAsString() const {
1334 return TI->getAsString() + "[" + utostr(Element) + "]";
1338 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
1339 if (Init *I = getVariable()->resolveListElementReference(R, RV,
1342 return const_cast<VarListElementInit *>(this);
1345 Init *VarListElementInit::getBit(unsigned Bit) const {
1346 if (getType() == BitRecTy::get())
1347 return const_cast<VarListElementInit*>(this);
1348 return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
1351 Init *VarListElementInit:: resolveListElementReference(Record &R,
1352 const RecordVal *RV,
1353 unsigned Elt) const {
1354 if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
1355 if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
1356 Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
1357 if (Result2) return Result2;
1358 return VarListElementInit::get(TInit, Elt);
1366 DefInit *DefInit::get(Record *R) {
1367 return R->getDefInit();
1370 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
1371 if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
1372 if (getDef()->isSubClassOf(RRT->getRecord()))
1373 return const_cast<DefInit *>(this);
1377 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1378 if (const RecordVal *RV = Def->getValue(FieldName))
1379 return RV->getType();
1383 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1384 const std::string &FieldName) const {
1385 return Def->getValue(FieldName)->getValue();
1389 std::string DefInit::getAsString() const {
1390 return Def->getName();
1393 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
1394 typedef std::pair<Init *, TableGenStringKey> Key;
1395 static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
1397 Key TheKey(std::make_pair(R, FN));
1399 std::unique_ptr<FieldInit> &I = ThePool[TheKey];
1400 if (!I) I.reset(new FieldInit(R, FN));
1404 Init *FieldInit::getBit(unsigned Bit) const {
1405 if (getType() == BitRecTy::get())
1406 return const_cast<FieldInit*>(this);
1407 return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
1410 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1411 unsigned Elt) const {
1412 if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1413 if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
1414 if (Elt >= LI->getSize()) return nullptr;
1415 Init *E = LI->getElement(Elt);
1417 // If the element is set to some value, or if we are resolving a
1418 // reference to a specific variable and that variable is explicitly
1419 // unset, then replace the VarListElementInit with it.
1420 if (RV || !isa<UnsetInit>(E))
1426 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1427 Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1429 if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
1430 Init *BVR = BitsVal->resolveReferences(R, RV);
1431 return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
1435 return FieldInit::get(NewRec, FieldName);
1436 return const_cast<FieldInit *>(this);
1439 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
1440 ArrayRef<Init *> ArgRange,
1441 ArrayRef<std::string> NameRange) {
1445 ArrayRef<Init *>::iterator Arg = ArgRange.begin();
1446 ArrayRef<std::string>::iterator Name = NameRange.begin();
1447 while (Arg != ArgRange.end()) {
1448 assert(Name != NameRange.end() && "Arg name underflow!");
1449 ID.AddPointer(*Arg++);
1450 ID.AddString(*Name++);
1452 assert(Name == NameRange.end() && "Arg name overflow!");
1456 DagInit::get(Init *V, const std::string &VN,
1457 ArrayRef<Init *> ArgRange,
1458 ArrayRef<std::string> NameRange) {
1459 static FoldingSet<DagInit> ThePool;
1460 static std::vector<std::unique_ptr<DagInit>> TheActualPool;
1462 FoldingSetNodeID ID;
1463 ProfileDagInit(ID, V, VN, ArgRange, NameRange);
1466 if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
1469 DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
1470 ThePool.InsertNode(I, IP);
1471 TheActualPool.push_back(std::unique_ptr<DagInit>(I));
1476 DagInit::get(Init *V, const std::string &VN,
1477 const std::vector<std::pair<Init*, std::string> > &args) {
1478 std::vector<Init *> Args;
1479 std::vector<std::string> Names;
1481 for (const auto &Arg : args) {
1482 Args.push_back(Arg.first);
1483 Names.push_back(Arg.second);
1486 return DagInit::get(V, VN, Args, Names);
1489 void DagInit::Profile(FoldingSetNodeID &ID) const {
1490 ProfileDagInit(ID, Val, ValName, Args, ArgNames);
1493 Init *DagInit::convertInitializerTo(RecTy *Ty) const {
1494 if (isa<DagRecTy>(Ty))
1495 return const_cast<DagInit *>(this);
1500 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1501 std::vector<Init*> NewArgs;
1502 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1503 NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1505 Init *Op = Val->resolveReferences(R, RV);
1507 if (Args != NewArgs || Op != Val)
1508 return DagInit::get(Op, ValName, NewArgs, ArgNames);
1510 return const_cast<DagInit *>(this);
1514 std::string DagInit::getAsString() const {
1515 std::string Result = "(" + Val->getAsString();
1516 if (!ValName.empty())
1517 Result += ":" + ValName;
1518 if (!Args.empty()) {
1519 Result += " " + Args[0]->getAsString();
1520 if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1521 for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1522 Result += ", " + Args[i]->getAsString();
1523 if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1526 return Result + ")";
1530 //===----------------------------------------------------------------------===//
1531 // Other implementations
1532 //===----------------------------------------------------------------------===//
1534 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
1535 : Name(N), Ty(T), Prefix(P) {
1536 Value = UnsetInit::get()->convertInitializerTo(Ty);
1537 assert(Value && "Cannot create unset value for current type!");
1540 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1541 : Name(StringInit::get(N)), Ty(T), Prefix(P) {
1542 Value = UnsetInit::get()->convertInitializerTo(Ty);
1543 assert(Value && "Cannot create unset value for current type!");
1546 const std::string &RecordVal::getName() const {
1547 return cast<StringInit>(Name)->getValue();
1550 void RecordVal::dump() const { errs() << *this; }
1552 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1553 if (getPrefix()) OS << "field ";
1554 OS << *getType() << " " << getNameInitAsString();
1557 OS << " = " << *getValue();
1559 if (PrintSem) OS << ";\n";
1562 unsigned Record::LastID = 0;
1564 void Record::init() {
1567 // Every record potentially has a def at the top. This value is
1568 // replaced with the top-level def name at instantiation time.
1569 RecordVal DN("NAME", StringRecTy::get(), 0);
1573 void Record::checkName() {
1574 // Ensure the record name has string type.
1575 const TypedInit *TypedName = cast<const TypedInit>(Name);
1576 RecTy *Type = TypedName->getType();
1577 if (!isa<StringRecTy>(Type))
1578 PrintFatalError(getLoc(), "Record name is not a string!");
1581 DefInit *Record::getDefInit() {
1582 static DenseMap<Record *, std::unique_ptr<DefInit>> ThePool;
1586 std::unique_ptr<DefInit> &I = ThePool[this];
1587 if (!I) I.reset(new DefInit(this, new RecordRecTy(this)));
1591 const std::string &Record::getName() const {
1592 return cast<StringInit>(Name)->getValue();
1595 void Record::setName(Init *NewName) {
1598 // DO NOT resolve record values to the name at this point because
1599 // there might be default values for arguments of this def. Those
1600 // arguments might not have been resolved yet so we don't want to
1601 // prematurely assume values for those arguments were not passed to
1604 // Nonetheless, it may be that some of this Record's values
1605 // reference the record name. Indeed, the reason for having the
1606 // record name be an Init is to provide this flexibility. The extra
1607 // resolve steps after completely instantiating defs takes care of
1608 // this. See TGParser::ParseDef and TGParser::ParseDefm.
1611 void Record::setName(const std::string &Name) {
1612 setName(StringInit::get(Name));
1615 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1616 /// reference to RV with the RHS of RV. If RV is null, we resolve all possible
1618 void Record::resolveReferencesTo(const RecordVal *RV) {
1619 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1620 if (RV == &Values[i]) // Skip resolve the same field as the given one
1622 if (Init *V = Values[i].getValue())
1623 if (Values[i].setValue(V->resolveReferences(*this, RV)))
1624 PrintFatalError(getLoc(), "Invalid value is found when setting '" +
1625 Values[i].getNameInitAsString() +
1626 "' after resolving references" +
1627 (RV ? " against '" + RV->getNameInitAsString() +
1628 "' of (" + RV->getValue()->getAsUnquotedString() +
1632 Init *OldName = getNameInit();
1633 Init *NewName = Name->resolveReferences(*this, RV);
1634 if (NewName != OldName) {
1635 // Re-register with RecordKeeper.
1640 void Record::dump() const { errs() << *this; }
1642 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1643 OS << R.getNameInitAsString();
1645 const std::vector<Init *> &TArgs = R.getTemplateArgs();
1646 if (!TArgs.empty()) {
1648 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1650 const RecordVal *RV = R.getValue(TArgs[i]);
1651 assert(RV && "Template argument record not found??");
1652 RV->print(OS, false);
1658 const std::vector<Record*> &SC = R.getSuperClasses();
1661 for (unsigned i = 0, e = SC.size(); i != e; ++i)
1662 OS << " " << SC[i]->getNameInitAsString();
1666 const std::vector<RecordVal> &Vals = R.getValues();
1667 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1668 if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1670 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1671 if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1677 /// getValueInit - Return the initializer for a value with the specified name,
1678 /// or abort if the field does not exist.
1680 Init *Record::getValueInit(StringRef FieldName) const {
1681 const RecordVal *R = getValue(FieldName);
1682 if (!R || !R->getValue())
1683 PrintFatalError(getLoc(), "Record `" + getName() +
1684 "' does not have a field named `" + FieldName + "'!\n");
1685 return R->getValue();
1689 /// getValueAsString - This method looks up the specified field and returns its
1690 /// value as a string, aborts if the field does not exist or if
1691 /// the value is not a string.
1693 std::string Record::getValueAsString(StringRef FieldName) const {
1694 const RecordVal *R = getValue(FieldName);
1695 if (!R || !R->getValue())
1696 PrintFatalError(getLoc(), "Record `" + getName() +
1697 "' does not have a field named `" + FieldName + "'!\n");
1699 if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
1700 return SI->getValue();
1701 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1702 FieldName + "' does not have a string initializer!");
1705 /// getValueAsBitsInit - This method looks up the specified field and returns
1706 /// its value as a BitsInit, aborts if the field does not exist or if
1707 /// the value is not the right type.
1709 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1710 const RecordVal *R = getValue(FieldName);
1711 if (!R || !R->getValue())
1712 PrintFatalError(getLoc(), "Record `" + getName() +
1713 "' does not have a field named `" + FieldName + "'!\n");
1715 if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
1717 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1718 FieldName + "' does not have a BitsInit initializer!");
1721 /// getValueAsListInit - This method looks up the specified field and returns
1722 /// its value as a ListInit, aborting if the field does not exist or if
1723 /// the value is not the right type.
1725 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1726 const RecordVal *R = getValue(FieldName);
1727 if (!R || !R->getValue())
1728 PrintFatalError(getLoc(), "Record `" + getName() +
1729 "' does not have a field named `" + FieldName + "'!\n");
1731 if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
1733 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1734 FieldName + "' does not have a list initializer!");
1737 /// getValueAsListOfDefs - This method looks up the specified field and returns
1738 /// its value as a vector of records, aborting if the field does not exist
1739 /// or if the value is not the right type.
1741 std::vector<Record*>
1742 Record::getValueAsListOfDefs(StringRef FieldName) const {
1743 ListInit *List = getValueAsListInit(FieldName);
1744 std::vector<Record*> Defs;
1745 for (unsigned i = 0; i < List->getSize(); i++) {
1746 if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i)))
1747 Defs.push_back(DI->getDef());
1749 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1750 FieldName + "' list is not entirely DefInit!");
1755 /// getValueAsInt - This method looks up the specified field and returns its
1756 /// value as an int64_t, aborting if the field does not exist or if the value
1757 /// is not the right type.
1759 int64_t Record::getValueAsInt(StringRef FieldName) const {
1760 const RecordVal *R = getValue(FieldName);
1761 if (!R || !R->getValue())
1762 PrintFatalError(getLoc(), "Record `" + getName() +
1763 "' does not have a field named `" + FieldName + "'!\n");
1765 if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
1766 return II->getValue();
1767 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1768 FieldName + "' does not have an int initializer!");
1771 /// getValueAsListOfInts - This method looks up the specified field and returns
1772 /// its value as a vector of integers, aborting if the field does not exist or
1773 /// if the value is not the right type.
1775 std::vector<int64_t>
1776 Record::getValueAsListOfInts(StringRef FieldName) const {
1777 ListInit *List = getValueAsListInit(FieldName);
1778 std::vector<int64_t> Ints;
1779 for (unsigned i = 0; i < List->getSize(); i++) {
1780 if (IntInit *II = dyn_cast<IntInit>(List->getElement(i)))
1781 Ints.push_back(II->getValue());
1783 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1784 FieldName + "' does not have a list of ints initializer!");
1789 /// getValueAsListOfStrings - This method looks up the specified field and
1790 /// returns its value as a vector of strings, aborting if the field does not
1791 /// exist or if the value is not the right type.
1793 std::vector<std::string>
1794 Record::getValueAsListOfStrings(StringRef FieldName) const {
1795 ListInit *List = getValueAsListInit(FieldName);
1796 std::vector<std::string> Strings;
1797 for (unsigned i = 0; i < List->getSize(); i++) {
1798 if (StringInit *II = dyn_cast<StringInit>(List->getElement(i)))
1799 Strings.push_back(II->getValue());
1801 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1802 FieldName + "' does not have a list of strings initializer!");
1807 /// getValueAsDef - This method looks up the specified field and returns its
1808 /// value as a Record, aborting if the field does not exist or if the value
1809 /// is not the right type.
1811 Record *Record::getValueAsDef(StringRef FieldName) const {
1812 const RecordVal *R = getValue(FieldName);
1813 if (!R || !R->getValue())
1814 PrintFatalError(getLoc(), "Record `" + getName() +
1815 "' does not have a field named `" + FieldName + "'!\n");
1817 if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
1818 return DI->getDef();
1819 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1820 FieldName + "' does not have a def initializer!");
1823 /// getValueAsBit - This method looks up the specified field and returns its
1824 /// value as a bit, aborting if the field does not exist or if the value is
1825 /// not the right type.
1827 bool Record::getValueAsBit(StringRef FieldName) const {
1828 const RecordVal *R = getValue(FieldName);
1829 if (!R || !R->getValue())
1830 PrintFatalError(getLoc(), "Record `" + getName() +
1831 "' does not have a field named `" + FieldName + "'!\n");
1833 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1834 return BI->getValue();
1835 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1836 FieldName + "' does not have a bit initializer!");
1839 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
1840 const RecordVal *R = getValue(FieldName);
1841 if (!R || !R->getValue())
1842 PrintFatalError(getLoc(), "Record `" + getName() +
1843 "' does not have a field named `" + FieldName.str() + "'!\n");
1845 if (isa<UnsetInit>(R->getValue())) {
1850 if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
1851 return BI->getValue();
1852 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1853 FieldName + "' does not have a bit initializer!");
1856 /// getValueAsDag - This method looks up the specified field and returns its
1857 /// value as an Dag, aborting if the field does not exist or if the value is
1858 /// not the right type.
1860 DagInit *Record::getValueAsDag(StringRef FieldName) const {
1861 const RecordVal *R = getValue(FieldName);
1862 if (!R || !R->getValue())
1863 PrintFatalError(getLoc(), "Record `" + getName() +
1864 "' does not have a field named `" + FieldName + "'!\n");
1866 if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
1868 PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
1869 FieldName + "' does not have a dag initializer!");
1873 void MultiClass::dump() const {
1874 errs() << "Record:\n";
1877 errs() << "Defs:\n";
1878 for (const auto &Proto : DefPrototypes)
1883 void RecordKeeper::dump() const { errs() << *this; }
1885 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1886 OS << "------------- Classes -----------------\n";
1887 for (const auto &C : RK.getClasses())
1888 OS << "class " << *C.second;
1890 OS << "------------- Defs -----------------\n";
1891 for (const auto &D : RK.getDefs())
1892 OS << "def " << *D.second;
1897 /// getAllDerivedDefinitions - This method returns all concrete definitions
1898 /// that derive from the specified class name. If a class with the specified
1899 /// name does not exist, an error is printed and true is returned.
1900 std::vector<Record*>
1901 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1902 Record *Class = getClass(ClassName);
1904 PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
1906 std::vector<Record*> Defs;
1907 for (const auto &D : getDefs())
1908 if (D.second->isSubClassOf(Class))
1909 Defs.push_back(D.second.get());
1914 /// QualifyName - Return an Init with a qualifier prefix referring
1915 /// to CurRec's name.
1916 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1917 Init *Name, const std::string &Scoper) {
1918 RecTy *Type = cast<TypedInit>(Name)->getType();
1920 BinOpInit *NewName =
1921 BinOpInit::get(BinOpInit::STRCONCAT,
1922 BinOpInit::get(BinOpInit::STRCONCAT,
1923 CurRec.getNameInit(),
1924 StringInit::get(Scoper),
1925 Type)->Fold(&CurRec, CurMultiClass),
1929 if (CurMultiClass && Scoper != "::") {
1931 BinOpInit::get(BinOpInit::STRCONCAT,
1932 BinOpInit::get(BinOpInit::STRCONCAT,
1933 CurMultiClass->Rec.getNameInit(),
1934 StringInit::get("::"),
1935 Type)->Fold(&CurRec, CurMultiClass),
1936 NewName->Fold(&CurRec, CurMultiClass),
1940 return NewName->Fold(&CurRec, CurMultiClass);
1943 /// QualifyName - Return an Init with a qualifier prefix referring
1944 /// to CurRec's name.
1945 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
1946 const std::string &Name,
1947 const std::string &Scoper) {
1948 return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);