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