Home | History | Annotate | Download | only in TableGen
      1 //===- Record.cpp - Record implementation ---------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // Implement the tablegen record classes.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     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"
     26 
     27 using namespace llvm;
     28 
     29 //===----------------------------------------------------------------------===//
     30 //    std::string wrapper for DenseMap purposes
     31 //===----------------------------------------------------------------------===//
     32 
     33 namespace llvm {
     34 
     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.
     42 
     43 class TableGenStringKey {
     44 public:
     45   TableGenStringKey(const std::string &str) : data(str) {}
     46   TableGenStringKey(const char *str) : data(str) {}
     47 
     48   const std::string &str() const { return data; }
     49 
     50   friend hash_code hash_value(const TableGenStringKey &Value) {
     51     using llvm::hash_value;
     52     return hash_value(Value.str());
     53   }
     54 private:
     55   std::string data;
     56 };
     57 
     58 /// Specialize DenseMapInfo for TableGenStringKey.
     59 template<> struct DenseMapInfo<TableGenStringKey> {
     60   static inline TableGenStringKey getEmptyKey() {
     61     TableGenStringKey Empty("<<<EMPTY KEY>>>");
     62     return Empty;
     63   }
     64   static inline TableGenStringKey getTombstoneKey() {
     65     TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
     66     return Tombstone;
     67   }
     68   static unsigned getHashValue(const TableGenStringKey& Val) {
     69     using llvm::hash_value;
     70     return hash_value(Val);
     71   }
     72   static bool isEqual(const TableGenStringKey& LHS,
     73                       const TableGenStringKey& RHS) {
     74     return LHS.str() == RHS.str();
     75   }
     76 };
     77 
     78 } // namespace llvm
     79 
     80 //===----------------------------------------------------------------------===//
     81 //    Type implementations
     82 //===----------------------------------------------------------------------===//
     83 
     84 BitRecTy BitRecTy::Shared;
     85 IntRecTy IntRecTy::Shared;
     86 StringRecTy StringRecTy::Shared;
     87 DagRecTy DagRecTy::Shared;
     88 
     89 void RecTy::dump() const { print(errs()); }
     90 
     91 ListRecTy *RecTy::getListTy() {
     92   if (!ListTy)
     93     ListTy.reset(new ListRecTy(this));
     94   return ListTy.get();
     95 }
     96 
     97 bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
     98   assert(RHS && "NULL pointer");
     99   return Kind == RHS->getRecTyKind();
    100 }
    101 
    102 bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
    103   if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
    104     return true;
    105   if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
    106     return BitsTy->getNumBits() == 1;
    107   return false;
    108 }
    109 
    110 BitsRecTy *BitsRecTy::get(unsigned Sz) {
    111   static std::vector<std::unique_ptr<BitsRecTy>> Shared;
    112   if (Sz >= Shared.size())
    113     Shared.resize(Sz + 1);
    114   std::unique_ptr<BitsRecTy> &Ty = Shared[Sz];
    115   if (!Ty)
    116     Ty.reset(new BitsRecTy(Sz));
    117   return Ty.get();
    118 }
    119 
    120 std::string BitsRecTy::getAsString() const {
    121   return "bits<" + utostr(Size) + ">";
    122 }
    123 
    124 bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
    125   if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
    126     return cast<BitsRecTy>(RHS)->Size == Size;
    127   RecTyKind kind = RHS->getRecTyKind();
    128   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
    129 }
    130 
    131 bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
    132   RecTyKind kind = RHS->getRecTyKind();
    133   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
    134 }
    135 
    136 std::string StringRecTy::getAsString() const {
    137   return "string";
    138 }
    139 
    140 std::string ListRecTy::getAsString() const {
    141   return "list<" + Ty->getAsString() + ">";
    142 }
    143 
    144 bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
    145   if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
    146     return Ty->typeIsConvertibleTo(ListTy->getElementType());
    147   return false;
    148 }
    149 
    150 std::string DagRecTy::getAsString() const {
    151   return "dag";
    152 }
    153 
    154 RecordRecTy *RecordRecTy::get(Record *R) {
    155   return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
    156 }
    157 
    158 std::string RecordRecTy::getAsString() const {
    159   return Rec->getName();
    160 }
    161 
    162 bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
    163   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
    164   if (!RTy)
    165     return false;
    166 
    167   if (RTy->getRecord() == Rec || Rec->isSubClassOf(RTy->getRecord()))
    168     return true;
    169 
    170   for (Record *SC : RTy->getRecord()->getSuperClasses())
    171     if (Rec->isSubClassOf(SC))
    172       return true;
    173 
    174   return false;
    175 }
    176 
    177 /// resolveTypes - Find a common type that T1 and T2 convert to.
    178 /// Return null if no such type exists.
    179 ///
    180 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
    181   if (T1->typeIsConvertibleTo(T2))
    182     return T2;
    183   if (T2->typeIsConvertibleTo(T1))
    184     return T1;
    185 
    186   // If one is a Record type, check superclasses
    187   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
    188     // See if T2 inherits from a type T1 also inherits from
    189     for (Record *SuperRec1 : RecTy1->getRecord()->getSuperClasses()) {
    190       RecordRecTy *SuperRecTy1 = RecordRecTy::get(SuperRec1);
    191       RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
    192       if (NewType1)
    193         return NewType1;
    194     }
    195   }
    196   if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
    197     // See if T1 inherits from a type T2 also inherits from
    198     for (Record *SuperRec2 : RecTy2->getRecord()->getSuperClasses()) {
    199       RecordRecTy *SuperRecTy2 = RecordRecTy::get(SuperRec2);
    200       RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
    201       if (NewType2)
    202         return NewType2;
    203     }
    204   }
    205   return nullptr;
    206 }
    207 
    208 
    209 //===----------------------------------------------------------------------===//
    210 //    Initializer implementations
    211 //===----------------------------------------------------------------------===//
    212 
    213 void Init::anchor() { }
    214 void Init::dump() const { return print(errs()); }
    215 
    216 UnsetInit *UnsetInit::get() {
    217   static UnsetInit TheInit;
    218   return &TheInit;
    219 }
    220 
    221 Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
    222   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
    223     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
    224 
    225     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
    226       NewBits[i] = UnsetInit::get();
    227 
    228     return BitsInit::get(NewBits);
    229   }
    230 
    231   // All other types can just be returned.
    232   return const_cast<UnsetInit *>(this);
    233 }
    234 
    235 BitInit *BitInit::get(bool V) {
    236   static BitInit True(true);
    237   static BitInit False(false);
    238 
    239   return V ? &True : &False;
    240 }
    241 
    242 Init *BitInit::convertInitializerTo(RecTy *Ty) const {
    243   if (isa<BitRecTy>(Ty))
    244     return const_cast<BitInit *>(this);
    245 
    246   if (isa<IntRecTy>(Ty))
    247     return IntInit::get(getValue());
    248 
    249   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
    250     // Can only convert single bit.
    251     if (BRT->getNumBits() == 1)
    252       return BitsInit::get(const_cast<BitInit *>(this));
    253   }
    254 
    255   return nullptr;
    256 }
    257 
    258 static void
    259 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
    260   ID.AddInteger(Range.size());
    261 
    262   for (Init *I : Range)
    263     ID.AddPointer(I);
    264 }
    265 
    266 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
    267   static FoldingSet<BitsInit> ThePool;
    268   static std::vector<std::unique_ptr<BitsInit>> TheActualPool;
    269 
    270   FoldingSetNodeID ID;
    271   ProfileBitsInit(ID, Range);
    272 
    273   void *IP = nullptr;
    274   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
    275     return I;
    276 
    277   BitsInit *I = new BitsInit(Range);
    278   ThePool.InsertNode(I, IP);
    279   TheActualPool.push_back(std::unique_ptr<BitsInit>(I));
    280   return I;
    281 }
    282 
    283 void BitsInit::Profile(FoldingSetNodeID &ID) const {
    284   ProfileBitsInit(ID, Bits);
    285 }
    286 
    287 Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
    288   if (isa<BitRecTy>(Ty)) {
    289     if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
    290     return getBit(0);
    291   }
    292 
    293   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
    294     // If the number of bits is right, return it.  Otherwise we need to expand
    295     // or truncate.
    296     if (getNumBits() != BRT->getNumBits()) return nullptr;
    297     return const_cast<BitsInit *>(this);
    298   }
    299 
    300   if (isa<IntRecTy>(Ty)) {
    301     int64_t Result = 0;
    302     for (unsigned i = 0, e = getNumBits(); i != e; ++i)
    303       if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
    304         Result |= static_cast<int64_t>(Bit->getValue()) << i;
    305       else
    306         return nullptr;
    307     return IntInit::get(Result);
    308   }
    309 
    310   return nullptr;
    311 }
    312 
    313 Init *
    314 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
    315   SmallVector<Init *, 16> NewBits(Bits.size());
    316 
    317   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
    318     if (Bits[i] >= getNumBits())
    319       return nullptr;
    320     NewBits[i] = getBit(Bits[i]);
    321   }
    322   return BitsInit::get(NewBits);
    323 }
    324 
    325 std::string BitsInit::getAsString() const {
    326   std::string Result = "{ ";
    327   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
    328     if (i) Result += ", ";
    329     if (Init *Bit = getBit(e-i-1))
    330       Result += Bit->getAsString();
    331     else
    332       Result += "*";
    333   }
    334   return Result + " }";
    335 }
    336 
    337 // Fix bit initializer to preserve the behavior that bit reference from a unset
    338 // bits initializer will resolve into VarBitInit to keep the field name and bit
    339 // number used in targets with fixed insn length.
    340 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
    341   if (RV || !isa<UnsetInit>(After))
    342     return After;
    343   return Before;
    344 }
    345 
    346 // resolveReferences - If there are any field references that refer to fields
    347 // that have been filled in, we can propagate the values now.
    348 //
    349 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
    350   bool Changed = false;
    351   SmallVector<Init *, 16> NewBits(getNumBits());
    352 
    353   Init *CachedInit = nullptr;
    354   Init *CachedBitVar = nullptr;
    355   bool CachedBitVarChanged = false;
    356 
    357   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
    358     Init *CurBit = Bits[i];
    359     Init *CurBitVar = CurBit->getBitVar();
    360 
    361     NewBits[i] = CurBit;
    362 
    363     if (CurBitVar == CachedBitVar) {
    364       if (CachedBitVarChanged) {
    365         Init *Bit = CachedInit->getBit(CurBit->getBitNum());
    366         NewBits[i] = fixBitInit(RV, CurBit, Bit);
    367       }
    368       continue;
    369     }
    370     CachedBitVar = CurBitVar;
    371     CachedBitVarChanged = false;
    372 
    373     Init *B;
    374     do {
    375       B = CurBitVar;
    376       CurBitVar = CurBitVar->resolveReferences(R, RV);
    377       CachedBitVarChanged |= B != CurBitVar;
    378       Changed |= B != CurBitVar;
    379     } while (B != CurBitVar);
    380     CachedInit = CurBitVar;
    381 
    382     if (CachedBitVarChanged) {
    383       Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
    384       NewBits[i] = fixBitInit(RV, CurBit, Bit);
    385     }
    386   }
    387 
    388   if (Changed)
    389     return BitsInit::get(NewBits);
    390 
    391   return const_cast<BitsInit *>(this);
    392 }
    393 
    394 IntInit *IntInit::get(int64_t V) {
    395   static DenseMap<int64_t, std::unique_ptr<IntInit>> ThePool;
    396 
    397   std::unique_ptr<IntInit> &I = ThePool[V];
    398   if (!I) I.reset(new IntInit(V));
    399   return I.get();
    400 }
    401 
    402 std::string IntInit::getAsString() const {
    403   return itostr(Value);
    404 }
    405 
    406 /// canFitInBitfield - Return true if the number of bits is large enough to hold
    407 /// the integer value.
    408 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
    409   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
    410   return (NumBits >= sizeof(Value) * 8) ||
    411          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
    412 }
    413 
    414 Init *IntInit::convertInitializerTo(RecTy *Ty) const {
    415   if (isa<IntRecTy>(Ty))
    416     return const_cast<IntInit *>(this);
    417 
    418   if (isa<BitRecTy>(Ty)) {
    419     int64_t Val = getValue();
    420     if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
    421     return BitInit::get(Val != 0);
    422   }
    423 
    424   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
    425     int64_t Value = getValue();
    426     // Make sure this bitfield is large enough to hold the integer value.
    427     if (!canFitInBitfield(Value, BRT->getNumBits()))
    428       return nullptr;
    429 
    430     SmallVector<Init *, 16> NewBits(BRT->getNumBits());
    431     for (unsigned i = 0; i != BRT->getNumBits(); ++i)
    432       NewBits[i] = BitInit::get(Value & (1LL << i));
    433 
    434     return BitsInit::get(NewBits);
    435   }
    436 
    437   return nullptr;
    438 }
    439 
    440 Init *
    441 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
    442   SmallVector<Init *, 16> NewBits(Bits.size());
    443 
    444   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
    445     if (Bits[i] >= 64)
    446       return nullptr;
    447 
    448     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
    449   }
    450   return BitsInit::get(NewBits);
    451 }
    452 
    453 StringInit *StringInit::get(StringRef V) {
    454   static StringMap<std::unique_ptr<StringInit>> ThePool;
    455 
    456   std::unique_ptr<StringInit> &I = ThePool[V];
    457   if (!I) I.reset(new StringInit(V));
    458   return I.get();
    459 }
    460 
    461 Init *StringInit::convertInitializerTo(RecTy *Ty) const {
    462   if (isa<StringRecTy>(Ty))
    463     return const_cast<StringInit *>(this);
    464 
    465   return nullptr;
    466 }
    467 
    468 static void ProfileListInit(FoldingSetNodeID &ID,
    469                             ArrayRef<Init *> Range,
    470                             RecTy *EltTy) {
    471   ID.AddInteger(Range.size());
    472   ID.AddPointer(EltTy);
    473 
    474   for (Init *I : Range)
    475     ID.AddPointer(I);
    476 }
    477 
    478 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
    479   static FoldingSet<ListInit> ThePool;
    480   static std::vector<std::unique_ptr<ListInit>> TheActualPool;
    481 
    482   FoldingSetNodeID ID;
    483   ProfileListInit(ID, Range, EltTy);
    484 
    485   void *IP = nullptr;
    486   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
    487     return I;
    488 
    489   ListInit *I = new ListInit(Range, EltTy);
    490   ThePool.InsertNode(I, IP);
    491   TheActualPool.push_back(std::unique_ptr<ListInit>(I));
    492   return I;
    493 }
    494 
    495 void ListInit::Profile(FoldingSetNodeID &ID) const {
    496   RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
    497 
    498   ProfileListInit(ID, Values, EltTy);
    499 }
    500 
    501 Init *ListInit::convertInitializerTo(RecTy *Ty) const {
    502   if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
    503     std::vector<Init*> Elements;
    504 
    505     // Verify that all of the elements of the list are subclasses of the
    506     // appropriate class!
    507     for (Init *I : getValues())
    508       if (Init *CI = I->convertInitializerTo(LRT->getElementType()))
    509         Elements.push_back(CI);
    510       else
    511         return nullptr;
    512 
    513     if (isa<ListRecTy>(getType()))
    514       return ListInit::get(Elements, Ty);
    515   }
    516 
    517   return nullptr;
    518 }
    519 
    520 Init *
    521 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
    522   std::vector<Init*> Vals;
    523   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
    524     if (Elements[i] >= size())
    525       return nullptr;
    526     Vals.push_back(getElement(Elements[i]));
    527   }
    528   return ListInit::get(Vals, getType());
    529 }
    530 
    531 Record *ListInit::getElementAsRecord(unsigned i) const {
    532   assert(i < Values.size() && "List element index out of range!");
    533   DefInit *DI = dyn_cast<DefInit>(Values[i]);
    534   if (!DI)
    535     PrintFatalError("Expected record in list!");
    536   return DI->getDef();
    537 }
    538 
    539 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
    540   std::vector<Init*> Resolved;
    541   Resolved.reserve(size());
    542   bool Changed = false;
    543 
    544   for (Init *CurElt : getValues()) {
    545     Init *E;
    546 
    547     do {
    548       E = CurElt;
    549       CurElt = CurElt->resolveReferences(R, RV);
    550       Changed |= E != CurElt;
    551     } while (E != CurElt);
    552     Resolved.push_back(E);
    553   }
    554 
    555   if (Changed)
    556     return ListInit::get(Resolved, getType());
    557   return const_cast<ListInit *>(this);
    558 }
    559 
    560 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
    561                                             unsigned Elt) const {
    562   if (Elt >= size())
    563     return nullptr;  // Out of range reference.
    564   Init *E = getElement(Elt);
    565   // If the element is set to some value, or if we are resolving a reference
    566   // to a specific variable and that variable is explicitly unset, then
    567   // replace the VarListElementInit with it.
    568   if (IRV || !isa<UnsetInit>(E))
    569     return E;
    570   return nullptr;
    571 }
    572 
    573 std::string ListInit::getAsString() const {
    574   std::string Result = "[";
    575   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
    576     if (i) Result += ", ";
    577     Result += Values[i]->getAsString();
    578   }
    579   return Result + "]";
    580 }
    581 
    582 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
    583                                           unsigned Elt) const {
    584   Init *Resolved = resolveReferences(R, IRV);
    585   OpInit *OResolved = dyn_cast<OpInit>(Resolved);
    586   if (OResolved) {
    587     Resolved = OResolved->Fold(&R, nullptr);
    588   }
    589 
    590   if (Resolved != this) {
    591     TypedInit *Typed = cast<TypedInit>(Resolved);
    592     if (Init *New = Typed->resolveListElementReference(R, IRV, Elt))
    593       return New;
    594     return VarListElementInit::get(Typed, Elt);
    595   }
    596 
    597   return nullptr;
    598 }
    599 
    600 Init *OpInit::getBit(unsigned Bit) const {
    601   if (getType() == BitRecTy::get())
    602     return const_cast<OpInit*>(this);
    603   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
    604 }
    605 
    606 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
    607   typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
    608   static DenseMap<Key, std::unique_ptr<UnOpInit>> ThePool;
    609 
    610   Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
    611 
    612   std::unique_ptr<UnOpInit> &I = ThePool[TheKey];
    613   if (!I) I.reset(new UnOpInit(opc, lhs, Type));
    614   return I.get();
    615 }
    616 
    617 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
    618   switch (getOpcode()) {
    619   case CAST: {
    620     if (isa<StringRecTy>(getType())) {
    621       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
    622         return LHSs;
    623 
    624       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
    625         return StringInit::get(LHSd->getAsString());
    626 
    627       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
    628         return StringInit::get(LHSi->getAsString());
    629     } else {
    630       if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
    631         std::string Name = LHSs->getValue();
    632 
    633         // From TGParser::ParseIDValue
    634         if (CurRec) {
    635           if (const RecordVal *RV = CurRec->getValue(Name)) {
    636             if (RV->getType() != getType())
    637               PrintFatalError("type mismatch in cast");
    638             return VarInit::get(Name, RV->getType());
    639           }
    640 
    641           Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
    642                                               ":");
    643 
    644           if (CurRec->isTemplateArg(TemplateArgName)) {
    645             const RecordVal *RV = CurRec->getValue(TemplateArgName);
    646             assert(RV && "Template arg doesn't exist??");
    647 
    648             if (RV->getType() != getType())
    649               PrintFatalError("type mismatch in cast");
    650 
    651             return VarInit::get(TemplateArgName, RV->getType());
    652           }
    653         }
    654 
    655         if (CurMultiClass) {
    656           Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
    657                                      "::");
    658 
    659           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
    660             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
    661             assert(RV && "Template arg doesn't exist??");
    662 
    663             if (RV->getType() != getType())
    664               PrintFatalError("type mismatch in cast");
    665 
    666             return VarInit::get(MCName, RV->getType());
    667           }
    668         }
    669         assert(CurRec && "NULL pointer");
    670         if (Record *D = (CurRec->getRecords()).getDef(Name))
    671           return DefInit::get(D);
    672 
    673         PrintFatalError(CurRec->getLoc(),
    674                         "Undefined reference:'" + Name + "'\n");
    675       }
    676 
    677       if (isa<IntRecTy>(getType())) {
    678         if (BitsInit *BI = dyn_cast<BitsInit>(LHS)) {
    679           if (Init *NewInit = BI->convertInitializerTo(IntRecTy::get()))
    680             return NewInit;
    681           break;
    682         }
    683       }
    684     }
    685     break;
    686   }
    687   case HEAD: {
    688     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
    689       assert(!LHSl->empty() && "Empty list in head");
    690       return LHSl->getElement(0);
    691     }
    692     break;
    693   }
    694   case TAIL: {
    695     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
    696       assert(!LHSl->empty() && "Empty list in tail");
    697       // Note the +1.  We can't just pass the result of getValues()
    698       // directly.
    699       return ListInit::get(LHSl->getValues().slice(1), LHSl->getType());
    700     }
    701     break;
    702   }
    703   case EMPTY: {
    704     if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
    705       return IntInit::get(LHSl->empty());
    706     if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
    707       return IntInit::get(LHSs->getValue().empty());
    708 
    709     break;
    710   }
    711   }
    712   return const_cast<UnOpInit *>(this);
    713 }
    714 
    715 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
    716   Init *lhs = LHS->resolveReferences(R, RV);
    717 
    718   if (LHS != lhs)
    719     return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
    720   return Fold(&R, nullptr);
    721 }
    722 
    723 std::string UnOpInit::getAsString() const {
    724   std::string Result;
    725   switch (Opc) {
    726   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
    727   case HEAD: Result = "!head"; break;
    728   case TAIL: Result = "!tail"; break;
    729   case EMPTY: Result = "!empty"; break;
    730   }
    731   return Result + "(" + LHS->getAsString() + ")";
    732 }
    733 
    734 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
    735                           Init *rhs, RecTy *Type) {
    736   typedef std::pair<
    737     std::pair<std::pair<unsigned, Init *>, Init *>,
    738     RecTy *
    739     > Key;
    740 
    741   static DenseMap<Key, std::unique_ptr<BinOpInit>> ThePool;
    742 
    743   Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
    744                             Type));
    745 
    746   std::unique_ptr<BinOpInit> &I = ThePool[TheKey];
    747   if (!I) I.reset(new BinOpInit(opc, lhs, rhs, Type));
    748   return I.get();
    749 }
    750 
    751 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
    752   switch (getOpcode()) {
    753   case CONCAT: {
    754     DagInit *LHSs = dyn_cast<DagInit>(LHS);
    755     DagInit *RHSs = dyn_cast<DagInit>(RHS);
    756     if (LHSs && RHSs) {
    757       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
    758       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
    759       if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
    760         PrintFatalError("Concated Dag operators do not match!");
    761       std::vector<Init*> Args;
    762       std::vector<std::string> ArgNames;
    763       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
    764         Args.push_back(LHSs->getArg(i));
    765         ArgNames.push_back(LHSs->getArgName(i));
    766       }
    767       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
    768         Args.push_back(RHSs->getArg(i));
    769         ArgNames.push_back(RHSs->getArgName(i));
    770       }
    771       return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
    772     }
    773     break;
    774   }
    775   case LISTCONCAT: {
    776     ListInit *LHSs = dyn_cast<ListInit>(LHS);
    777     ListInit *RHSs = dyn_cast<ListInit>(RHS);
    778     if (LHSs && RHSs) {
    779       std::vector<Init *> Args;
    780       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
    781       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
    782       return ListInit::get(
    783           Args, cast<ListRecTy>(LHSs->getType())->getElementType());
    784     }
    785     break;
    786   }
    787   case STRCONCAT: {
    788     StringInit *LHSs = dyn_cast<StringInit>(LHS);
    789     StringInit *RHSs = dyn_cast<StringInit>(RHS);
    790     if (LHSs && RHSs)
    791       return StringInit::get(LHSs->getValue() + RHSs->getValue());
    792     break;
    793   }
    794   case EQ: {
    795     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
    796     // to string objects.
    797     IntInit *L =
    798       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
    799     IntInit *R =
    800       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
    801 
    802     if (L && R)
    803       return IntInit::get(L->getValue() == R->getValue());
    804 
    805     StringInit *LHSs = dyn_cast<StringInit>(LHS);
    806     StringInit *RHSs = dyn_cast<StringInit>(RHS);
    807 
    808     // Make sure we've resolved
    809     if (LHSs && RHSs)
    810       return IntInit::get(LHSs->getValue() == RHSs->getValue());
    811 
    812     break;
    813   }
    814   case ADD:
    815   case AND:
    816   case SHL:
    817   case SRA:
    818   case SRL: {
    819     IntInit *LHSi =
    820       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
    821     IntInit *RHSi =
    822       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
    823     if (LHSi && RHSi) {
    824       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
    825       int64_t Result;
    826       switch (getOpcode()) {
    827       default: llvm_unreachable("Bad opcode!");
    828       case ADD: Result = LHSv +  RHSv; break;
    829       case AND: Result = LHSv &  RHSv; break;
    830       case SHL: Result = LHSv << RHSv; break;
    831       case SRA: Result = LHSv >> RHSv; break;
    832       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
    833       }
    834       return IntInit::get(Result);
    835     }
    836     break;
    837   }
    838   }
    839   return const_cast<BinOpInit *>(this);
    840 }
    841 
    842 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
    843   Init *lhs = LHS->resolveReferences(R, RV);
    844   Init *rhs = RHS->resolveReferences(R, RV);
    845 
    846   if (LHS != lhs || RHS != rhs)
    847     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
    848   return Fold(&R, nullptr);
    849 }
    850 
    851 std::string BinOpInit::getAsString() const {
    852   std::string Result;
    853   switch (Opc) {
    854   case CONCAT: Result = "!con"; break;
    855   case ADD: Result = "!add"; break;
    856   case AND: Result = "!and"; break;
    857   case SHL: Result = "!shl"; break;
    858   case SRA: Result = "!sra"; break;
    859   case SRL: Result = "!srl"; break;
    860   case EQ: Result = "!eq"; break;
    861   case LISTCONCAT: Result = "!listconcat"; break;
    862   case STRCONCAT: Result = "!strconcat"; break;
    863   }
    864   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
    865 }
    866 
    867 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
    868                             RecTy *Type) {
    869   typedef std::pair<
    870     std::pair<
    871       std::pair<std::pair<unsigned, RecTy *>, Init *>,
    872       Init *
    873       >,
    874     Init *
    875     > Key;
    876 
    877   static DenseMap<Key, std::unique_ptr<TernOpInit>> ThePool;
    878 
    879   Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
    880                                                                          Type),
    881                                                           lhs),
    882                                            mhs),
    883                             rhs));
    884 
    885   std::unique_ptr<TernOpInit> &I = ThePool[TheKey];
    886   if (!I) I.reset(new TernOpInit(opc, lhs, mhs, rhs, Type));
    887   return I.get();
    888 }
    889 
    890 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
    891                            Record *CurRec, MultiClass *CurMultiClass);
    892 
    893 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
    894                                RecTy *Type, Record *CurRec,
    895                                MultiClass *CurMultiClass) {
    896   // If this is a dag, recurse
    897   if (auto *TArg = dyn_cast<TypedInit>(Arg))
    898     if (isa<DagRecTy>(TArg->getType()))
    899       return ForeachHelper(LHS, Arg, RHSo, Type, CurRec, CurMultiClass);
    900 
    901   std::vector<Init *> NewOperands;
    902   for (unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
    903     if (auto *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i))) {
    904       if (Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
    905                                            Type, CurRec, CurMultiClass))
    906         NewOperands.push_back(Result);
    907       else
    908         NewOperands.push_back(Arg);
    909     } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
    910       NewOperands.push_back(Arg);
    911     } else {
    912       NewOperands.push_back(RHSo->getOperand(i));
    913     }
    914   }
    915 
    916   // Now run the operator and use its result as the new leaf
    917   const OpInit *NewOp = RHSo->clone(NewOperands);
    918   Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
    919   return (NewVal != NewOp) ? NewVal : nullptr;
    920 }
    921 
    922 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
    923                            Record *CurRec, MultiClass *CurMultiClass) {
    924 
    925   OpInit *RHSo = dyn_cast<OpInit>(RHS);
    926 
    927   if (!RHSo)
    928     PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
    929 
    930   TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
    931 
    932   if (!LHSt)
    933     PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
    934 
    935   DagInit *MHSd = dyn_cast<DagInit>(MHS);
    936   if (MHSd && isa<DagRecTy>(Type)) {
    937     Init *Val = MHSd->getOperator();
    938     if (Init *Result = EvaluateOperation(RHSo, LHS, Val,
    939                                          Type, CurRec, CurMultiClass))
    940       Val = Result;
    941 
    942     std::vector<std::pair<Init *, std::string> > args;
    943     for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
    944       Init *Arg = MHSd->getArg(i);
    945       std::string ArgName = MHSd->getArgName(i);
    946 
    947       // Process args
    948       if (Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
    949                                            CurRec, CurMultiClass))
    950         Arg = Result;
    951 
    952       // TODO: Process arg names
    953       args.push_back(std::make_pair(Arg, ArgName));
    954     }
    955 
    956     return DagInit::get(Val, "", args);
    957   }
    958 
    959   ListInit *MHSl = dyn_cast<ListInit>(MHS);
    960   if (MHSl && isa<ListRecTy>(Type)) {
    961     std::vector<Init *> NewOperands;
    962     std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
    963 
    964     for (Init *&Item : NewList) {
    965       NewOperands.clear();
    966       for(unsigned i = 0; i < RHSo->getNumOperands(); ++i) {
    967         // First, replace the foreach variable with the list item
    968         if (LHS->getAsString() == RHSo->getOperand(i)->getAsString())
    969           NewOperands.push_back(Item);
    970         else
    971           NewOperands.push_back(RHSo->getOperand(i));
    972       }
    973 
    974       // Now run the operator and use its result as the new list item
    975       const OpInit *NewOp = RHSo->clone(NewOperands);
    976       Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
    977       if (NewItem != NewOp)
    978         Item = NewItem;
    979     }
    980     return ListInit::get(NewList, MHSl->getType());
    981   }
    982   return nullptr;
    983 }
    984 
    985 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
    986   switch (getOpcode()) {
    987   case SUBST: {
    988     DefInit *LHSd = dyn_cast<DefInit>(LHS);
    989     VarInit *LHSv = dyn_cast<VarInit>(LHS);
    990     StringInit *LHSs = dyn_cast<StringInit>(LHS);
    991 
    992     DefInit *MHSd = dyn_cast<DefInit>(MHS);
    993     VarInit *MHSv = dyn_cast<VarInit>(MHS);
    994     StringInit *MHSs = dyn_cast<StringInit>(MHS);
    995 
    996     DefInit *RHSd = dyn_cast<DefInit>(RHS);
    997     VarInit *RHSv = dyn_cast<VarInit>(RHS);
    998     StringInit *RHSs = dyn_cast<StringInit>(RHS);
    999 
   1000     if (LHSd && MHSd && RHSd) {
   1001       Record *Val = RHSd->getDef();
   1002       if (LHSd->getAsString() == RHSd->getAsString())
   1003         Val = MHSd->getDef();
   1004       return DefInit::get(Val);
   1005     }
   1006     if (LHSv && MHSv && RHSv) {
   1007       std::string Val = RHSv->getName();
   1008       if (LHSv->getAsString() == RHSv->getAsString())
   1009         Val = MHSv->getName();
   1010       return VarInit::get(Val, getType());
   1011     }
   1012     if (LHSs && MHSs && RHSs) {
   1013       std::string Val = RHSs->getValue();
   1014 
   1015       std::string::size_type found;
   1016       std::string::size_type idx = 0;
   1017       while (true) {
   1018         found = Val.find(LHSs->getValue(), idx);
   1019         if (found == std::string::npos)
   1020           break;
   1021         Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
   1022         idx = found + MHSs->getValue().size();
   1023       }
   1024 
   1025       return StringInit::get(Val);
   1026     }
   1027     break;
   1028   }
   1029 
   1030   case FOREACH: {
   1031     if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
   1032                                      CurRec, CurMultiClass))
   1033       return Result;
   1034     break;
   1035   }
   1036 
   1037   case IF: {
   1038     IntInit *LHSi = dyn_cast<IntInit>(LHS);
   1039     if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
   1040       LHSi = dyn_cast<IntInit>(I);
   1041     if (LHSi) {
   1042       if (LHSi->getValue())
   1043         return MHS;
   1044       return RHS;
   1045     }
   1046     break;
   1047   }
   1048   }
   1049 
   1050   return const_cast<TernOpInit *>(this);
   1051 }
   1052 
   1053 Init *TernOpInit::resolveReferences(Record &R,
   1054                                     const RecordVal *RV) const {
   1055   Init *lhs = LHS->resolveReferences(R, RV);
   1056 
   1057   if (Opc == IF && lhs != LHS) {
   1058     IntInit *Value = dyn_cast<IntInit>(lhs);
   1059     if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
   1060       Value = dyn_cast<IntInit>(I);
   1061     if (Value) {
   1062       // Short-circuit
   1063       if (Value->getValue()) {
   1064         Init *mhs = MHS->resolveReferences(R, RV);
   1065         return (TernOpInit::get(getOpcode(), lhs, mhs,
   1066                                 RHS, getType()))->Fold(&R, nullptr);
   1067       }
   1068       Init *rhs = RHS->resolveReferences(R, RV);
   1069       return (TernOpInit::get(getOpcode(), lhs, MHS,
   1070                               rhs, getType()))->Fold(&R, nullptr);
   1071     }
   1072   }
   1073 
   1074   Init *mhs = MHS->resolveReferences(R, RV);
   1075   Init *rhs = RHS->resolveReferences(R, RV);
   1076 
   1077   if (LHS != lhs || MHS != mhs || RHS != rhs)
   1078     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
   1079                             getType()))->Fold(&R, nullptr);
   1080   return Fold(&R, nullptr);
   1081 }
   1082 
   1083 std::string TernOpInit::getAsString() const {
   1084   std::string Result;
   1085   switch (Opc) {
   1086   case SUBST: Result = "!subst"; break;
   1087   case FOREACH: Result = "!foreach"; break;
   1088   case IF: Result = "!if"; break;
   1089   }
   1090   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " +
   1091          RHS->getAsString() + ")";
   1092 }
   1093 
   1094 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
   1095   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
   1096     if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
   1097       return Field->getType();
   1098   return nullptr;
   1099 }
   1100 
   1101 Init *
   1102 TypedInit::convertInitializerTo(RecTy *Ty) const {
   1103   if (isa<IntRecTy>(Ty)) {
   1104     if (getType()->typeIsConvertibleTo(Ty))
   1105       return const_cast<TypedInit *>(this);
   1106     return nullptr;
   1107   }
   1108 
   1109   if (isa<StringRecTy>(Ty)) {
   1110     if (isa<StringRecTy>(getType()))
   1111       return const_cast<TypedInit *>(this);
   1112     return nullptr;
   1113   }
   1114 
   1115   if (isa<BitRecTy>(Ty)) {
   1116     // Accept variable if it is already of bit type!
   1117     if (isa<BitRecTy>(getType()))
   1118       return const_cast<TypedInit *>(this);
   1119     if (auto *BitsTy = dyn_cast<BitsRecTy>(getType())) {
   1120       // Accept only bits<1> expression.
   1121       if (BitsTy->getNumBits() == 1)
   1122         return const_cast<TypedInit *>(this);
   1123       return nullptr;
   1124     }
   1125     // Ternary !if can be converted to bit, but only if both sides are
   1126     // convertible to a bit.
   1127     if (const auto *TOI = dyn_cast<TernOpInit>(this)) {
   1128       if (TOI->getOpcode() == TernOpInit::TernaryOp::IF &&
   1129           TOI->getMHS()->convertInitializerTo(BitRecTy::get()) &&
   1130           TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
   1131         return const_cast<TypedInit *>(this);
   1132       return nullptr;
   1133     }
   1134     return nullptr;
   1135   }
   1136 
   1137   if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
   1138     if (BRT->getNumBits() == 1 && isa<BitRecTy>(getType()))
   1139       return BitsInit::get(const_cast<TypedInit *>(this));
   1140 
   1141     if (getType()->typeIsConvertibleTo(BRT)) {
   1142       SmallVector<Init *, 16> NewBits(BRT->getNumBits());
   1143 
   1144       for (unsigned i = 0; i != BRT->getNumBits(); ++i)
   1145         NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), i);
   1146       return BitsInit::get(NewBits);
   1147     }
   1148 
   1149     return nullptr;
   1150   }
   1151 
   1152   if (auto *DLRT = dyn_cast<ListRecTy>(Ty)) {
   1153     if (auto *SLRT = dyn_cast<ListRecTy>(getType()))
   1154       if (SLRT->getElementType()->typeIsConvertibleTo(DLRT->getElementType()))
   1155         return const_cast<TypedInit *>(this);
   1156     return nullptr;
   1157   }
   1158 
   1159   if (auto *DRT = dyn_cast<DagRecTy>(Ty)) {
   1160     if (getType()->typeIsConvertibleTo(DRT))
   1161       return const_cast<TypedInit *>(this);
   1162     return nullptr;
   1163   }
   1164 
   1165   if (auto *SRRT = dyn_cast<RecordRecTy>(Ty)) {
   1166     // Ensure that this is compatible with Rec.
   1167     if (RecordRecTy *DRRT = dyn_cast<RecordRecTy>(getType()))
   1168       if (DRRT->getRecord()->isSubClassOf(SRRT->getRecord()) ||
   1169           DRRT->getRecord() == SRRT->getRecord())
   1170         return const_cast<TypedInit *>(this);
   1171     return nullptr;
   1172   }
   1173 
   1174   return nullptr;
   1175 }
   1176 
   1177 Init *
   1178 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
   1179   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
   1180   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
   1181   unsigned NumBits = T->getNumBits();
   1182 
   1183   SmallVector<Init *, 16> NewBits(Bits.size());
   1184   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
   1185     if (Bits[i] >= NumBits)
   1186       return nullptr;
   1187 
   1188     NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
   1189   }
   1190   return BitsInit::get(NewBits);
   1191 }
   1192 
   1193 Init *
   1194 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
   1195   ListRecTy *T = dyn_cast<ListRecTy>(getType());
   1196   if (!T) return nullptr;  // Cannot subscript a non-list variable.
   1197 
   1198   if (Elements.size() == 1)
   1199     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
   1200 
   1201   std::vector<Init*> ListInits;
   1202   ListInits.reserve(Elements.size());
   1203   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
   1204     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
   1205                                                 Elements[i]));
   1206   return ListInit::get(ListInits, T);
   1207 }
   1208 
   1209 
   1210 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
   1211   Init *Value = StringInit::get(VN);
   1212   return VarInit::get(Value, T);
   1213 }
   1214 
   1215 VarInit *VarInit::get(Init *VN, RecTy *T) {
   1216   typedef std::pair<RecTy *, Init *> Key;
   1217   static DenseMap<Key, std::unique_ptr<VarInit>> ThePool;
   1218 
   1219   Key TheKey(std::make_pair(T, VN));
   1220 
   1221   std::unique_ptr<VarInit> &I = ThePool[TheKey];
   1222   if (!I) I.reset(new VarInit(VN, T));
   1223   return I.get();
   1224 }
   1225 
   1226 const std::string &VarInit::getName() const {
   1227   StringInit *NameString = cast<StringInit>(getNameInit());
   1228   return NameString->getValue();
   1229 }
   1230 
   1231 Init *VarInit::getBit(unsigned Bit) const {
   1232   if (getType() == BitRecTy::get())
   1233     return const_cast<VarInit*>(this);
   1234   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
   1235 }
   1236 
   1237 Init *VarInit::resolveListElementReference(Record &R,
   1238                                            const RecordVal *IRV,
   1239                                            unsigned Elt) const {
   1240   if (R.isTemplateArg(getNameInit())) return nullptr;
   1241   if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
   1242 
   1243   RecordVal *RV = R.getValue(getNameInit());
   1244   assert(RV && "Reference to a non-existent variable?");
   1245   ListInit *LI = dyn_cast<ListInit>(RV->getValue());
   1246   if (!LI)
   1247     return VarListElementInit::get(cast<TypedInit>(RV->getValue()), Elt);
   1248 
   1249   if (Elt >= LI->size())
   1250     return nullptr;  // Out of range reference.
   1251   Init *E = LI->getElement(Elt);
   1252   // If the element is set to some value, or if we are resolving a reference
   1253   // to a specific variable and that variable is explicitly unset, then
   1254   // replace the VarListElementInit with it.
   1255   if (IRV || !isa<UnsetInit>(E))
   1256     return E;
   1257   return nullptr;
   1258 }
   1259 
   1260 
   1261 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
   1262   if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
   1263     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
   1264       return RV->getType();
   1265   return nullptr;
   1266 }
   1267 
   1268 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
   1269                             const std::string &FieldName) const {
   1270   if (isa<RecordRecTy>(getType()))
   1271     if (const RecordVal *Val = R.getValue(VarName)) {
   1272       if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
   1273         return nullptr;
   1274       Init *TheInit = Val->getValue();
   1275       assert(TheInit != this && "Infinite loop detected!");
   1276       if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
   1277         return I;
   1278       return nullptr;
   1279     }
   1280   return nullptr;
   1281 }
   1282 
   1283 /// resolveReferences - This method is used by classes that refer to other
   1284 /// variables which may not be defined at the time the expression is formed.
   1285 /// If a value is set for the variable later, this method will be called on
   1286 /// users of the value to allow the value to propagate out.
   1287 ///
   1288 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
   1289   if (RecordVal *Val = R.getValue(VarName))
   1290     if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
   1291       return Val->getValue();
   1292   return const_cast<VarInit *>(this);
   1293 }
   1294 
   1295 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
   1296   typedef std::pair<TypedInit *, unsigned> Key;
   1297   static DenseMap<Key, std::unique_ptr<VarBitInit>> ThePool;
   1298 
   1299   Key TheKey(std::make_pair(T, B));
   1300 
   1301   std::unique_ptr<VarBitInit> &I = ThePool[TheKey];
   1302   if (!I) I.reset(new VarBitInit(T, B));
   1303   return I.get();
   1304 }
   1305 
   1306 Init *VarBitInit::convertInitializerTo(RecTy *Ty) const {
   1307   if (isa<BitRecTy>(Ty))
   1308     return const_cast<VarBitInit *>(this);
   1309 
   1310   return nullptr;
   1311 }
   1312 
   1313 std::string VarBitInit::getAsString() const {
   1314   return TI->getAsString() + "{" + utostr(Bit) + "}";
   1315 }
   1316 
   1317 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
   1318   Init *I = TI->resolveReferences(R, RV);
   1319   if (TI != I)
   1320     return I->getBit(getBitNum());
   1321 
   1322   return const_cast<VarBitInit*>(this);
   1323 }
   1324 
   1325 VarListElementInit *VarListElementInit::get(TypedInit *T,
   1326                                             unsigned E) {
   1327   typedef std::pair<TypedInit *, unsigned> Key;
   1328   static DenseMap<Key, std::unique_ptr<VarListElementInit>> ThePool;
   1329 
   1330   Key TheKey(std::make_pair(T, E));
   1331 
   1332   std::unique_ptr<VarListElementInit> &I = ThePool[TheKey];
   1333   if (!I) I.reset(new VarListElementInit(T, E));
   1334   return I.get();
   1335 }
   1336 
   1337 std::string VarListElementInit::getAsString() const {
   1338   return TI->getAsString() + "[" + utostr(Element) + "]";
   1339 }
   1340 
   1341 Init *
   1342 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
   1343   if (Init *I = getVariable()->resolveListElementReference(R, RV,
   1344                                                            getElementNum()))
   1345     return I;
   1346   return const_cast<VarListElementInit *>(this);
   1347 }
   1348 
   1349 Init *VarListElementInit::getBit(unsigned Bit) const {
   1350   if (getType() == BitRecTy::get())
   1351     return const_cast<VarListElementInit*>(this);
   1352   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
   1353 }
   1354 
   1355 Init *VarListElementInit:: resolveListElementReference(Record &R,
   1356                                                        const RecordVal *RV,
   1357                                                        unsigned Elt) const {
   1358   if (Init *Result = TI->resolveListElementReference(R, RV, Element)) {
   1359     if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
   1360       if (Init *Result2 = TInit->resolveListElementReference(R, RV, Elt))
   1361         return Result2;
   1362       return VarListElementInit::get(TInit, Elt);
   1363     }
   1364     return Result;
   1365   }
   1366 
   1367   return nullptr;
   1368 }
   1369 
   1370 DefInit *DefInit::get(Record *R) {
   1371   return R->getDefInit();
   1372 }
   1373 
   1374 Init *DefInit::convertInitializerTo(RecTy *Ty) const {
   1375   if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
   1376     if (getDef()->isSubClassOf(RRT->getRecord()))
   1377       return const_cast<DefInit *>(this);
   1378   return nullptr;
   1379 }
   1380 
   1381 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
   1382   if (const RecordVal *RV = Def->getValue(FieldName))
   1383     return RV->getType();
   1384   return nullptr;
   1385 }
   1386 
   1387 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
   1388                             const std::string &FieldName) const {
   1389   return Def->getValue(FieldName)->getValue();
   1390 }
   1391 
   1392 
   1393 std::string DefInit::getAsString() const {
   1394   return Def->getName();
   1395 }
   1396 
   1397 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
   1398   typedef std::pair<Init *, TableGenStringKey> Key;
   1399   static DenseMap<Key, std::unique_ptr<FieldInit>> ThePool;
   1400 
   1401   Key TheKey(std::make_pair(R, FN));
   1402 
   1403   std::unique_ptr<FieldInit> &I = ThePool[TheKey];
   1404   if (!I) I.reset(new FieldInit(R, FN));
   1405   return I.get();
   1406 }
   1407 
   1408 Init *FieldInit::getBit(unsigned Bit) const {
   1409   if (getType() == BitRecTy::get())
   1410     return const_cast<FieldInit*>(this);
   1411   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
   1412 }
   1413 
   1414 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
   1415                                              unsigned Elt) const {
   1416   if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
   1417     if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
   1418       if (Elt >= LI->size()) return nullptr;
   1419       Init *E = LI->getElement(Elt);
   1420 
   1421       // If the element is set to some value, or if we are resolving a
   1422       // reference to a specific variable and that variable is explicitly
   1423       // unset, then replace the VarListElementInit with it.
   1424       if (RV || !isa<UnsetInit>(E))
   1425         return E;
   1426     }
   1427   return nullptr;
   1428 }
   1429 
   1430 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
   1431   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
   1432 
   1433   if (Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName)) {
   1434     Init *BVR = BitsVal->resolveReferences(R, RV);
   1435     return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
   1436   }
   1437 
   1438   if (NewRec != Rec)
   1439     return FieldInit::get(NewRec, FieldName);
   1440   return const_cast<FieldInit *>(this);
   1441 }
   1442 
   1443 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
   1444                            ArrayRef<Init *> ArgRange,
   1445                            ArrayRef<std::string> NameRange) {
   1446   ID.AddPointer(V);
   1447   ID.AddString(VN);
   1448 
   1449   ArrayRef<Init *>::iterator Arg  = ArgRange.begin();
   1450   ArrayRef<std::string>::iterator  Name = NameRange.begin();
   1451   while (Arg != ArgRange.end()) {
   1452     assert(Name != NameRange.end() && "Arg name underflow!");
   1453     ID.AddPointer(*Arg++);
   1454     ID.AddString(*Name++);
   1455   }
   1456   assert(Name == NameRange.end() && "Arg name overflow!");
   1457 }
   1458 
   1459 DagInit *
   1460 DagInit::get(Init *V, const std::string &VN,
   1461              ArrayRef<Init *> ArgRange,
   1462              ArrayRef<std::string> NameRange) {
   1463   static FoldingSet<DagInit> ThePool;
   1464   static std::vector<std::unique_ptr<DagInit>> TheActualPool;
   1465 
   1466   FoldingSetNodeID ID;
   1467   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
   1468 
   1469   void *IP = nullptr;
   1470   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
   1471     return I;
   1472 
   1473   DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
   1474   ThePool.InsertNode(I, IP);
   1475   TheActualPool.push_back(std::unique_ptr<DagInit>(I));
   1476   return I;
   1477 }
   1478 
   1479 DagInit *
   1480 DagInit::get(Init *V, const std::string &VN,
   1481              const std::vector<std::pair<Init*, std::string> > &args) {
   1482   std::vector<Init *> Args;
   1483   std::vector<std::string> Names;
   1484 
   1485   for (const auto &Arg : args) {
   1486     Args.push_back(Arg.first);
   1487     Names.push_back(Arg.second);
   1488   }
   1489 
   1490   return DagInit::get(V, VN, Args, Names);
   1491 }
   1492 
   1493 void DagInit::Profile(FoldingSetNodeID &ID) const {
   1494   ProfileDagInit(ID, Val, ValName, Args, ArgNames);
   1495 }
   1496 
   1497 Init *DagInit::convertInitializerTo(RecTy *Ty) const {
   1498   if (isa<DagRecTy>(Ty))
   1499     return const_cast<DagInit *>(this);
   1500 
   1501   return nullptr;
   1502 }
   1503 
   1504 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
   1505   std::vector<Init*> NewArgs;
   1506   for (unsigned i = 0, e = Args.size(); i != e; ++i)
   1507     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
   1508 
   1509   Init *Op = Val->resolveReferences(R, RV);
   1510 
   1511   if (Args != NewArgs || Op != Val)
   1512     return DagInit::get(Op, ValName, NewArgs, ArgNames);
   1513 
   1514   return const_cast<DagInit *>(this);
   1515 }
   1516 
   1517 
   1518 std::string DagInit::getAsString() const {
   1519   std::string Result = "(" + Val->getAsString();
   1520   if (!ValName.empty())
   1521     Result += ":" + ValName;
   1522   if (!Args.empty()) {
   1523     Result += " " + Args[0]->getAsString();
   1524     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
   1525     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
   1526       Result += ", " + Args[i]->getAsString();
   1527       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
   1528     }
   1529   }
   1530   return Result + ")";
   1531 }
   1532 
   1533 
   1534 //===----------------------------------------------------------------------===//
   1535 //    Other implementations
   1536 //===----------------------------------------------------------------------===//
   1537 
   1538 RecordVal::RecordVal(Init *N, RecTy *T, bool P)
   1539   : NameAndPrefix(N, P), Ty(T) {
   1540   Value = UnsetInit::get()->convertInitializerTo(Ty);
   1541   assert(Value && "Cannot create unset value for current type!");
   1542 }
   1543 
   1544 RecordVal::RecordVal(const std::string &N, RecTy *T, bool P)
   1545   : NameAndPrefix(StringInit::get(N), P), Ty(T) {
   1546   Value = UnsetInit::get()->convertInitializerTo(Ty);
   1547   assert(Value && "Cannot create unset value for current type!");
   1548 }
   1549 
   1550 const std::string &RecordVal::getName() const {
   1551   return cast<StringInit>(getNameInit())->getValue();
   1552 }
   1553 
   1554 void RecordVal::dump() const { errs() << *this; }
   1555 
   1556 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
   1557   if (getPrefix()) OS << "field ";
   1558   OS << *getType() << " " << getNameInitAsString();
   1559 
   1560   if (getValue())
   1561     OS << " = " << *getValue();
   1562 
   1563   if (PrintSem) OS << ";\n";
   1564 }
   1565 
   1566 unsigned Record::LastID = 0;
   1567 
   1568 void Record::init() {
   1569   checkName();
   1570 
   1571   // Every record potentially has a def at the top.  This value is
   1572   // replaced with the top-level def name at instantiation time.
   1573   RecordVal DN("NAME", StringRecTy::get(), 0);
   1574   addValue(DN);
   1575 }
   1576 
   1577 void Record::checkName() {
   1578   // Ensure the record name has string type.
   1579   const TypedInit *TypedName = cast<const TypedInit>(Name);
   1580   if (!isa<StringRecTy>(TypedName->getType()))
   1581     PrintFatalError(getLoc(), "Record name is not a string!");
   1582 }
   1583 
   1584 DefInit *Record::getDefInit() {
   1585   if (!TheInit)
   1586     TheInit.reset(new DefInit(this, new RecordRecTy(this)));
   1587   return TheInit.get();
   1588 }
   1589 
   1590 const std::string &Record::getName() const {
   1591   return cast<StringInit>(Name)->getValue();
   1592 }
   1593 
   1594 void Record::setName(Init *NewName) {
   1595   Name = NewName;
   1596   checkName();
   1597   // DO NOT resolve record values to the name at this point because
   1598   // there might be default values for arguments of this def.  Those
   1599   // arguments might not have been resolved yet so we don't want to
   1600   // prematurely assume values for those arguments were not passed to
   1601   // this def.
   1602   //
   1603   // Nonetheless, it may be that some of this Record's values
   1604   // reference the record name.  Indeed, the reason for having the
   1605   // record name be an Init is to provide this flexibility.  The extra
   1606   // resolve steps after completely instantiating defs takes care of
   1607   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
   1608 }
   1609 
   1610 void Record::setName(const std::string &Name) {
   1611   setName(StringInit::get(Name));
   1612 }
   1613 
   1614 /// resolveReferencesTo - If anything in this record refers to RV, replace the
   1615 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
   1616 /// references.
   1617 void Record::resolveReferencesTo(const RecordVal *RV) {
   1618   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
   1619     if (RV == &Values[i]) // Skip resolve the same field as the given one
   1620       continue;
   1621     if (Init *V = Values[i].getValue())
   1622       if (Values[i].setValue(V->resolveReferences(*this, RV)))
   1623         PrintFatalError(getLoc(), "Invalid value is found when setting '" +
   1624                         Values[i].getNameInitAsString() +
   1625                         "' after resolving references" +
   1626                         (RV ? " against '" + RV->getNameInitAsString() +
   1627                               "' of (" + RV->getValue()->getAsUnquotedString() +
   1628                               ")"
   1629                             : "") + "\n");
   1630   }
   1631   Init *OldName = getNameInit();
   1632   Init *NewName = Name->resolveReferences(*this, RV);
   1633   if (NewName != OldName) {
   1634     // Re-register with RecordKeeper.
   1635     setName(NewName);
   1636   }
   1637 }
   1638 
   1639 void Record::dump() const { errs() << *this; }
   1640 
   1641 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
   1642   OS << R.getNameInitAsString();
   1643 
   1644   ArrayRef<Init *> TArgs = R.getTemplateArgs();
   1645   if (!TArgs.empty()) {
   1646     OS << "<";
   1647     bool NeedComma = false;
   1648     for (const Init *TA : TArgs) {
   1649       if (NeedComma) OS << ", ";
   1650       NeedComma = true;
   1651       const RecordVal *RV = R.getValue(TA);
   1652       assert(RV && "Template argument record not found??");
   1653       RV->print(OS, false);
   1654     }
   1655     OS << ">";
   1656   }
   1657 
   1658   OS << " {";
   1659   ArrayRef<Record *> SC = R.getSuperClasses();
   1660   if (!SC.empty()) {
   1661     OS << "\t//";
   1662     for (const Record *Super : SC)
   1663       OS << " " << Super->getNameInitAsString();
   1664   }
   1665   OS << "\n";
   1666 
   1667   for (const RecordVal &Val : R.getValues())
   1668     if (Val.getPrefix() && !R.isTemplateArg(Val.getName()))
   1669       OS << Val;
   1670   for (const RecordVal &Val : R.getValues())
   1671     if (!Val.getPrefix() && !R.isTemplateArg(Val.getName()))
   1672       OS << Val;
   1673 
   1674   return OS << "}\n";
   1675 }
   1676 
   1677 /// getValueInit - Return the initializer for a value with the specified name,
   1678 /// or abort if the field does not exist.
   1679 ///
   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();
   1686 }
   1687 
   1688 
   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.
   1692 ///
   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");
   1698 
   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!");
   1703 }
   1704 
   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.
   1708 ///
   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");
   1714 
   1715   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
   1716     return BI;
   1717   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1718     FieldName + "' does not have a BitsInit initializer!");
   1719 }
   1720 
   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.
   1724 ///
   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");
   1730 
   1731   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
   1732     return LI;
   1733   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1734     FieldName + "' does not have a list initializer!");
   1735 }
   1736 
   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.
   1740 ///
   1741 std::vector<Record*>
   1742 Record::getValueAsListOfDefs(StringRef FieldName) const {
   1743   ListInit *List = getValueAsListInit(FieldName);
   1744   std::vector<Record*> Defs;
   1745   for (Init *I : List->getValues()) {
   1746     if (DefInit *DI = dyn_cast<DefInit>(I))
   1747       Defs.push_back(DI->getDef());
   1748     else
   1749       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1750         FieldName + "' list is not entirely DefInit!");
   1751   }
   1752   return Defs;
   1753 }
   1754 
   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.
   1758 ///
   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");
   1764 
   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!");
   1769 }
   1770 
   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.
   1774 ///
   1775 std::vector<int64_t>
   1776 Record::getValueAsListOfInts(StringRef FieldName) const {
   1777   ListInit *List = getValueAsListInit(FieldName);
   1778   std::vector<int64_t> Ints;
   1779   for (Init *I : List->getValues()) {
   1780     if (IntInit *II = dyn_cast<IntInit>(I))
   1781       Ints.push_back(II->getValue());
   1782     else
   1783       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1784         FieldName + "' does not have a list of ints initializer!");
   1785   }
   1786   return Ints;
   1787 }
   1788 
   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.
   1792 ///
   1793 std::vector<std::string>
   1794 Record::getValueAsListOfStrings(StringRef FieldName) const {
   1795   ListInit *List = getValueAsListInit(FieldName);
   1796   std::vector<std::string> Strings;
   1797   for (Init *I : List->getValues()) {
   1798     if (StringInit *SI = dyn_cast<StringInit>(I))
   1799       Strings.push_back(SI->getValue());
   1800     else
   1801       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1802         FieldName + "' does not have a list of strings initializer!");
   1803   }
   1804   return Strings;
   1805 }
   1806 
   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.
   1810 ///
   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");
   1816 
   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!");
   1821 }
   1822 
   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.
   1826 ///
   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");
   1832 
   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!");
   1837 }
   1838 
   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");
   1844 
   1845   if (isa<UnsetInit>(R->getValue())) {
   1846     Unset = true;
   1847     return false;
   1848   }
   1849   Unset = false;
   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!");
   1854 }
   1855 
   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.
   1859 ///
   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");
   1865 
   1866   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
   1867     return DI;
   1868   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
   1869     FieldName + "' does not have a dag initializer!");
   1870 }
   1871 
   1872 
   1873 void MultiClass::dump() const {
   1874   errs() << "Record:\n";
   1875   Rec.dump();
   1876 
   1877   errs() << "Defs:\n";
   1878   for (const auto &Proto : DefPrototypes)
   1879     Proto->dump();
   1880 }
   1881 
   1882 
   1883 void RecordKeeper::dump() const { errs() << *this; }
   1884 
   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;
   1889 
   1890   OS << "------------- Defs -----------------\n";
   1891   for (const auto &D : RK.getDefs())
   1892     OS << "def " << *D.second;
   1893   return OS;
   1894 }
   1895 
   1896 
   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);
   1903   if (!Class)
   1904     PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
   1905 
   1906   std::vector<Record*> Defs;
   1907   for (const auto &D : getDefs())
   1908     if (D.second->isSubClassOf(Class))
   1909       Defs.push_back(D.second.get());
   1910 
   1911   return Defs;
   1912 }
   1913 
   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();
   1919 
   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),
   1926                    Name,
   1927                    Type);
   1928 
   1929   if (CurMultiClass && Scoper != "::") {
   1930     NewName =
   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),
   1937                      Type);
   1938   }
   1939 
   1940   return NewName->Fold(&CurRec, CurMultiClass);
   1941 }
   1942 
   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);
   1949 }
   1950