LLVM API Documentation

Record.cpp
Go to the documentation of this file.
00001 //===- Record.cpp - Record implementation ---------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implement the tablegen record classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/TableGen/Record.h"
00015 #include "llvm/ADT/DenseMap.h"
00016 #include "llvm/ADT/FoldingSet.h"
00017 #include "llvm/ADT/Hashing.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/StringExtras.h"
00021 #include "llvm/ADT/StringMap.h"
00022 #include "llvm/Support/DataTypes.h"
00023 #include "llvm/Support/ErrorHandling.h"
00024 #include "llvm/Support/Format.h"
00025 #include "llvm/TableGen/Error.h"
00026 
00027 using namespace llvm;
00028 
00029 //===----------------------------------------------------------------------===//
00030 //    std::string wrapper for DenseMap purposes
00031 //===----------------------------------------------------------------------===//
00032 
00033 namespace llvm {
00034 
00035 /// TableGenStringKey - This is a wrapper for std::string suitable for
00036 /// using as a key to a DenseMap.  Because there isn't a particularly
00037 /// good way to indicate tombstone or empty keys for strings, we want
00038 /// to wrap std::string to indicate that this is a "special" string
00039 /// not expected to take on certain values (those of the tombstone and
00040 /// empty keys).  This makes things a little safer as it clarifies
00041 /// that DenseMap is really not appropriate for general strings.
00042 
00043 class TableGenStringKey {
00044 public:
00045   TableGenStringKey(const std::string &str) : data(str) {}
00046   TableGenStringKey(const char *str) : data(str) {}
00047 
00048   const std::string &str() const { return data; }
00049 
00050   friend hash_code hash_value(const TableGenStringKey &Value) {
00051     using llvm::hash_value;
00052     return hash_value(Value.str());
00053   }
00054 private:
00055   std::string data;
00056 };
00057 
00058 /// Specialize DenseMapInfo for TableGenStringKey.
00059 template<> struct DenseMapInfo<TableGenStringKey> {
00060   static inline TableGenStringKey getEmptyKey() {
00061     TableGenStringKey Empty("<<<EMPTY KEY>>>");
00062     return Empty;
00063   }
00064   static inline TableGenStringKey getTombstoneKey() {
00065     TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
00066     return Tombstone;
00067   }
00068   static unsigned getHashValue(const TableGenStringKey& Val) {
00069     using llvm::hash_value;
00070     return hash_value(Val);
00071   }
00072   static bool isEqual(const TableGenStringKey& LHS,
00073                       const TableGenStringKey& RHS) {
00074     return LHS.str() == RHS.str();
00075   }
00076 };
00077 
00078 } // namespace llvm
00079 
00080 //===----------------------------------------------------------------------===//
00081 //    Type implementations
00082 //===----------------------------------------------------------------------===//
00083 
00084 BitRecTy BitRecTy::Shared;
00085 IntRecTy IntRecTy::Shared;
00086 StringRecTy StringRecTy::Shared;
00087 DagRecTy DagRecTy::Shared;
00088 
00089 void RecTy::anchor() { }
00090 void RecTy::dump() const { print(errs()); }
00091 
00092 ListRecTy *RecTy::getListTy() {
00093   if (!ListTy)
00094     ListTy = new ListRecTy(this);
00095   return ListTy;
00096 }
00097 
00098 bool RecTy::baseClassOf(const RecTy *RHS) const{
00099   assert (RHS && "NULL pointer");
00100   return Kind == RHS->getRecTyKind();
00101 }
00102 
00103 Init *BitRecTy::convertValue(BitsInit *BI) {
00104   if (BI->getNumBits() != 1) return nullptr; // Only accept if just one bit!
00105   return BI->getBit(0);
00106 }
00107 
00108 Init *BitRecTy::convertValue(IntInit *II) {
00109   int64_t Val = II->getValue();
00110   if (Val != 0 && Val != 1) return nullptr;  // Only accept 0 or 1 for a bit!
00111 
00112   return BitInit::get(Val != 0);
00113 }
00114 
00115 Init *BitRecTy::convertValue(TypedInit *VI) {
00116   RecTy *Ty = VI->getType();
00117   if (isa<BitRecTy>(Ty))
00118     return VI;  // Accept variable if it is already of bit type!
00119   if (auto *BitsTy = dyn_cast<BitsRecTy>(Ty))
00120     // Accept only bits<1> expression.
00121     return BitsTy->getNumBits() == 1 ? VI : nullptr;
00122   // Ternary !if can be converted to bit, but only if both sides are
00123   // convertible to a bit.
00124   if (TernOpInit *TOI = dyn_cast<TernOpInit>(VI)) {
00125     if (TOI->getOpcode() != TernOpInit::TernaryOp::IF)
00126       return nullptr;
00127     if (!TOI->getMHS()->convertInitializerTo(BitRecTy::get()) ||
00128         !TOI->getRHS()->convertInitializerTo(BitRecTy::get()))
00129       return nullptr;
00130     return TOI;
00131   }
00132   return nullptr;
00133 }
00134 
00135 bool BitRecTy::baseClassOf(const RecTy *RHS) const{
00136   if(RecTy::baseClassOf(RHS) || getRecTyKind() == IntRecTyKind)
00137     return true;
00138   if(const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
00139     return BitsTy->getNumBits() == 1;
00140   return false;
00141 }
00142 
00143 BitsRecTy *BitsRecTy::get(unsigned Sz) {
00144   static std::vector<BitsRecTy*> Shared;
00145   if (Sz >= Shared.size())
00146     Shared.resize(Sz + 1);
00147   BitsRecTy *&Ty = Shared[Sz];
00148   if (!Ty)
00149     Ty = new BitsRecTy(Sz);
00150   return Ty;
00151 }
00152 
00153 std::string BitsRecTy::getAsString() const {
00154   return "bits<" + utostr(Size) + ">";
00155 }
00156 
00157 Init *BitsRecTy::convertValue(UnsetInit *UI) {
00158   SmallVector<Init *, 16> NewBits(Size);
00159 
00160   for (unsigned i = 0; i != Size; ++i)
00161     NewBits[i] = UnsetInit::get();
00162 
00163   return BitsInit::get(NewBits);
00164 }
00165 
00166 Init *BitsRecTy::convertValue(BitInit *UI) {
00167   if (Size != 1) return nullptr;  // Can only convert single bit.
00168   return BitsInit::get(UI);
00169 }
00170 
00171 /// canFitInBitfield - Return true if the number of bits is large enough to hold
00172 /// the integer value.
00173 static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
00174   // For example, with NumBits == 4, we permit Values from [-7 .. 15].
00175   return (NumBits >= sizeof(Value) * 8) ||
00176          (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
00177 }
00178 
00179 /// convertValue from Int initializer to bits type: Split the integer up into the
00180 /// appropriate bits.
00181 ///
00182 Init *BitsRecTy::convertValue(IntInit *II) {
00183   int64_t Value = II->getValue();
00184   // Make sure this bitfield is large enough to hold the integer value.
00185   if (!canFitInBitfield(Value, Size))
00186     return nullptr;
00187 
00188   SmallVector<Init *, 16> NewBits(Size);
00189 
00190   for (unsigned i = 0; i != Size; ++i)
00191     NewBits[i] = BitInit::get(Value & (1LL << i));
00192 
00193   return BitsInit::get(NewBits);
00194 }
00195 
00196 Init *BitsRecTy::convertValue(BitsInit *BI) {
00197   // If the number of bits is right, return it.  Otherwise we need to expand or
00198   // truncate.
00199   if (BI->getNumBits() == Size) return BI;
00200   return nullptr;
00201 }
00202 
00203 Init *BitsRecTy::convertValue(TypedInit *VI) {
00204   if (Size == 1 && isa<BitRecTy>(VI->getType()))
00205     return BitsInit::get(VI);
00206 
00207   if (VI->getType()->typeIsConvertibleTo(this)) {
00208     SmallVector<Init *, 16> NewBits(Size);
00209 
00210     for (unsigned i = 0; i != Size; ++i)
00211       NewBits[i] = VarBitInit::get(VI, i);
00212     return BitsInit::get(NewBits);
00213   }
00214 
00215   return nullptr;
00216 }
00217 
00218 bool BitsRecTy::baseClassOf(const RecTy *RHS) const{
00219   if (RecTy::baseClassOf(RHS)) //argument and the receiver are the same type
00220     return cast<BitsRecTy>(RHS)->Size == Size;
00221   RecTyKind kind = RHS->getRecTyKind();
00222   return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
00223 }
00224 
00225 Init *IntRecTy::convertValue(BitInit *BI) {
00226   return IntInit::get(BI->getValue());
00227 }
00228 
00229 Init *IntRecTy::convertValue(BitsInit *BI) {
00230   int64_t Result = 0;
00231   for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
00232     if (BitInit *Bit = dyn_cast<BitInit>(BI->getBit(i))) {
00233       Result |= Bit->getValue() << i;
00234     } else {
00235       return nullptr;
00236     }
00237   return IntInit::get(Result);
00238 }
00239 
00240 Init *IntRecTy::convertValue(TypedInit *TI) {
00241   if (TI->getType()->typeIsConvertibleTo(this))
00242     return TI;  // Accept variable if already of the right type!
00243   return nullptr;
00244 }
00245 
00246 bool IntRecTy::baseClassOf(const RecTy *RHS) const{
00247   RecTyKind kind = RHS->getRecTyKind();
00248   return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
00249 }
00250 
00251 Init *StringRecTy::convertValue(UnOpInit *BO) {
00252   if (BO->getOpcode() == UnOpInit::CAST) {
00253     Init *L = BO->getOperand()->convertInitializerTo(this);
00254     if (!L) return nullptr;
00255     if (L != BO->getOperand())
00256       return UnOpInit::get(UnOpInit::CAST, L, new StringRecTy);
00257     return BO;
00258   }
00259 
00260   return convertValue((TypedInit*)BO);
00261 }
00262 
00263 Init *StringRecTy::convertValue(BinOpInit *BO) {
00264   if (BO->getOpcode() == BinOpInit::STRCONCAT) {
00265     Init *L = BO->getLHS()->convertInitializerTo(this);
00266     Init *R = BO->getRHS()->convertInitializerTo(this);
00267     if (!L || !R) return nullptr;
00268     if (L != BO->getLHS() || R != BO->getRHS())
00269       return BinOpInit::get(BinOpInit::STRCONCAT, L, R, new StringRecTy);
00270     return BO;
00271   }
00272 
00273   return convertValue((TypedInit*)BO);
00274 }
00275 
00276 
00277 Init *StringRecTy::convertValue(TypedInit *TI) {
00278   if (isa<StringRecTy>(TI->getType()))
00279     return TI;  // Accept variable if already of the right type!
00280   return nullptr;
00281 }
00282 
00283 std::string ListRecTy::getAsString() const {
00284   return "list<" + Ty->getAsString() + ">";
00285 }
00286 
00287 Init *ListRecTy::convertValue(ListInit *LI) {
00288   std::vector<Init*> Elements;
00289 
00290   // Verify that all of the elements of the list are subclasses of the
00291   // appropriate class!
00292   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
00293     if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
00294       Elements.push_back(CI);
00295     else
00296       return nullptr;
00297 
00298   if (!isa<ListRecTy>(LI->getType()))
00299     return nullptr;
00300 
00301   return ListInit::get(Elements, this);
00302 }
00303 
00304 Init *ListRecTy::convertValue(TypedInit *TI) {
00305   // Ensure that TI is compatible with our class.
00306   if (ListRecTy *LRT = dyn_cast<ListRecTy>(TI->getType()))
00307     if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
00308       return TI;
00309   return nullptr;
00310 }
00311 
00312 bool ListRecTy::baseClassOf(const RecTy *RHS) const{
00313   if(const ListRecTy* ListTy = dyn_cast<ListRecTy>(RHS))
00314     return ListTy->getElementType()->typeIsConvertibleTo(Ty);
00315   return false;
00316 }
00317 
00318 Init *DagRecTy::convertValue(TypedInit *TI) {
00319   if (TI->getType()->typeIsConvertibleTo(this))
00320     return TI;
00321   return nullptr;
00322 }
00323 
00324 Init *DagRecTy::convertValue(UnOpInit *BO) {
00325   if (BO->getOpcode() == UnOpInit::CAST) {
00326     Init *L = BO->getOperand()->convertInitializerTo(this);
00327     if (!L) return nullptr;
00328     if (L != BO->getOperand())
00329       return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
00330     return BO;
00331   }
00332   return nullptr;
00333 }
00334 
00335 Init *DagRecTy::convertValue(BinOpInit *BO) {
00336   if (BO->getOpcode() == BinOpInit::CONCAT) {
00337     Init *L = BO->getLHS()->convertInitializerTo(this);
00338     Init *R = BO->getRHS()->convertInitializerTo(this);
00339     if (!L || !R) return nullptr;
00340     if (L != BO->getLHS() || R != BO->getRHS())
00341       return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
00342     return BO;
00343   }
00344   return nullptr;
00345 }
00346 
00347 RecordRecTy *RecordRecTy::get(Record *R) {
00348   return dyn_cast<RecordRecTy>(R->getDefInit()->getType());
00349 }
00350 
00351 std::string RecordRecTy::getAsString() const {
00352   return Rec->getName();
00353 }
00354 
00355 Init *RecordRecTy::convertValue(DefInit *DI) {
00356   // Ensure that DI is a subclass of Rec.
00357   if (!DI->getDef()->isSubClassOf(Rec))
00358     return nullptr;
00359   return DI;
00360 }
00361 
00362 Init *RecordRecTy::convertValue(TypedInit *TI) {
00363   // Ensure that TI is compatible with Rec.
00364   if (RecordRecTy *RRT = dyn_cast<RecordRecTy>(TI->getType()))
00365     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
00366         RRT->getRecord() == getRecord())
00367       return TI;
00368   return nullptr;
00369 }
00370 
00371 bool RecordRecTy::baseClassOf(const RecTy *RHS) const{
00372   const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
00373   if (!RTy)
00374     return false;
00375 
00376   if (Rec == RTy->getRecord() || RTy->getRecord()->isSubClassOf(Rec))
00377     return true;
00378 
00379   const std::vector<Record*> &SC = Rec->getSuperClasses();
00380   for (unsigned i = 0, e = SC.size(); i != e; ++i)
00381     if (RTy->getRecord()->isSubClassOf(SC[i]))
00382       return true;
00383 
00384   return false;
00385 }
00386 
00387 /// resolveTypes - Find a common type that T1 and T2 convert to.
00388 /// Return 0 if no such type exists.
00389 ///
00390 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
00391   if (T1->typeIsConvertibleTo(T2))
00392     return T2;
00393   if (T2->typeIsConvertibleTo(T1))
00394     return T1;
00395 
00396   // If one is a Record type, check superclasses
00397   if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
00398     // See if T2 inherits from a type T1 also inherits from
00399     const std::vector<Record *> &T1SuperClasses =
00400       RecTy1->getRecord()->getSuperClasses();
00401     for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
00402           iend = T1SuperClasses.end();
00403         i != iend;
00404         ++i) {
00405       RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
00406       RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
00407       if (NewType1) {
00408         if (NewType1 != SuperRecTy1) {
00409           delete SuperRecTy1;
00410         }
00411         return NewType1;
00412       }
00413     }
00414   }
00415   if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2)) {
00416     // See if T1 inherits from a type T2 also inherits from
00417     const std::vector<Record *> &T2SuperClasses =
00418       RecTy2->getRecord()->getSuperClasses();
00419     for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
00420           iend = T2SuperClasses.end();
00421         i != iend;
00422         ++i) {
00423       RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
00424       RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
00425       if (NewType2) {
00426         if (NewType2 != SuperRecTy2) {
00427           delete SuperRecTy2;
00428         }
00429         return NewType2;
00430       }
00431     }
00432   }
00433   return nullptr;
00434 }
00435 
00436 
00437 //===----------------------------------------------------------------------===//
00438 //    Initializer implementations
00439 //===----------------------------------------------------------------------===//
00440 
00441 void Init::anchor() { }
00442 void Init::dump() const { return print(errs()); }
00443 
00444 void UnsetInit::anchor() { }
00445 
00446 UnsetInit *UnsetInit::get() {
00447   static UnsetInit TheInit;
00448   return &TheInit;
00449 }
00450 
00451 void BitInit::anchor() { }
00452 
00453 BitInit *BitInit::get(bool V) {
00454   static BitInit True(true);
00455   static BitInit False(false);
00456 
00457   return V ? &True : &False;
00458 }
00459 
00460 static void
00461 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
00462   ID.AddInteger(Range.size());
00463 
00464   for (ArrayRef<Init *>::iterator i = Range.begin(),
00465          iend = Range.end();
00466        i != iend;
00467        ++i)
00468     ID.AddPointer(*i);
00469 }
00470 
00471 BitsInit *BitsInit::get(ArrayRef<Init *> Range) {
00472   typedef FoldingSet<BitsInit> Pool;
00473   static Pool ThePool;  
00474 
00475   FoldingSetNodeID ID;
00476   ProfileBitsInit(ID, Range);
00477 
00478   void *IP = nullptr;
00479   if (BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
00480     return I;
00481 
00482   BitsInit *I = new BitsInit(Range);
00483   ThePool.InsertNode(I, IP);
00484 
00485   return I;
00486 }
00487 
00488 void BitsInit::Profile(FoldingSetNodeID &ID) const {
00489   ProfileBitsInit(ID, Bits);
00490 }
00491 
00492 Init *
00493 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
00494   SmallVector<Init *, 16> NewBits(Bits.size());
00495 
00496   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
00497     if (Bits[i] >= getNumBits())
00498       return nullptr;
00499     NewBits[i] = getBit(Bits[i]);
00500   }
00501   return BitsInit::get(NewBits);
00502 }
00503 
00504 std::string BitsInit::getAsString() const {
00505   std::string Result = "{ ";
00506   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
00507     if (i) Result += ", ";
00508     if (Init *Bit = getBit(e-i-1))
00509       Result += Bit->getAsString();
00510     else
00511       Result += "*";
00512   }
00513   return Result + " }";
00514 }
00515 
00516 // Fix bit initializer to preserve the behavior that bit reference from a unset
00517 // bits initializer will resolve into VarBitInit to keep the field name and bit
00518 // number used in targets with fixed insn length.
00519 static Init *fixBitInit(const RecordVal *RV, Init *Before, Init *After) {
00520   if (RV || After != UnsetInit::get())
00521     return After;
00522   return Before;
00523 }
00524 
00525 // resolveReferences - If there are any field references that refer to fields
00526 // that have been filled in, we can propagate the values now.
00527 //
00528 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
00529   bool Changed = false;
00530   SmallVector<Init *, 16> NewBits(getNumBits());
00531 
00532   Init *CachedInit = nullptr;
00533   Init *CachedBitVar = nullptr;
00534   bool CachedBitVarChanged = false;
00535 
00536   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
00537     Init *CurBit = Bits[i];
00538     Init *CurBitVar = CurBit->getBitVar();
00539 
00540     NewBits[i] = CurBit;
00541 
00542     if (CurBitVar == CachedBitVar) {
00543       if (CachedBitVarChanged) {
00544         Init *Bit = CachedInit->getBit(CurBit->getBitNum());
00545         NewBits[i] = fixBitInit(RV, CurBit, Bit);
00546       }
00547       continue;
00548     }
00549     CachedBitVar = CurBitVar;
00550     CachedBitVarChanged = false;
00551 
00552     Init *B;
00553     do {
00554       B = CurBitVar;
00555       CurBitVar = CurBitVar->resolveReferences(R, RV);
00556       CachedBitVarChanged |= B != CurBitVar;
00557       Changed |= B != CurBitVar;
00558     } while (B != CurBitVar);
00559     CachedInit = CurBitVar;
00560 
00561     if (CachedBitVarChanged) {
00562       Init *Bit = CurBitVar->getBit(CurBit->getBitNum());
00563       NewBits[i] = fixBitInit(RV, CurBit, Bit);
00564     }
00565   }
00566 
00567   if (Changed)
00568     return BitsInit::get(NewBits);
00569 
00570   return const_cast<BitsInit *>(this);
00571 }
00572 
00573 namespace {
00574   template<typename T>
00575   class Pool : public T {
00576   public:
00577     ~Pool();
00578   };
00579   template<typename T>
00580   Pool<T>::~Pool() {
00581     for (typename T::iterator I = this->begin(), E = this->end(); I != E; ++I) {
00582       typename T::value_type &Item = *I;
00583       delete Item.second;
00584     }
00585   }
00586 }
00587 
00588 IntInit *IntInit::get(int64_t V) {
00589   static Pool<DenseMap<int64_t, IntInit *> > ThePool;
00590 
00591   IntInit *&I = ThePool[V];
00592   if (!I) I = new IntInit(V);
00593   return I;
00594 }
00595 
00596 std::string IntInit::getAsString() const {
00597   return itostr(Value);
00598 }
00599 
00600 Init *
00601 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
00602   SmallVector<Init *, 16> NewBits(Bits.size());
00603 
00604   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
00605     if (Bits[i] >= 64)
00606       return nullptr;
00607 
00608     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
00609   }
00610   return BitsInit::get(NewBits);
00611 }
00612 
00613 void StringInit::anchor() { }
00614 
00615 StringInit *StringInit::get(StringRef V) {
00616   static Pool<StringMap<StringInit *> > ThePool;
00617 
00618   StringInit *&I = ThePool[V];
00619   if (!I) I = new StringInit(V);
00620   return I;
00621 }
00622 
00623 static void ProfileListInit(FoldingSetNodeID &ID,
00624                             ArrayRef<Init *> Range,
00625                             RecTy *EltTy) {
00626   ID.AddInteger(Range.size());
00627   ID.AddPointer(EltTy);
00628 
00629   for (ArrayRef<Init *>::iterator i = Range.begin(),
00630          iend = Range.end();
00631        i != iend;
00632        ++i)
00633     ID.AddPointer(*i);
00634 }
00635 
00636 ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
00637   typedef FoldingSet<ListInit> Pool;
00638   static Pool ThePool;
00639   static std::vector<std::unique_ptr<ListInit>> TheActualPool;
00640 
00641   FoldingSetNodeID ID;
00642   ProfileListInit(ID, Range, EltTy);
00643 
00644   void *IP = nullptr;
00645   if (ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
00646     return I;
00647 
00648   ListInit *I = new ListInit(Range, EltTy);
00649   ThePool.InsertNode(I, IP);
00650   TheActualPool.push_back(std::unique_ptr<ListInit>(I));
00651   return I;
00652 }
00653 
00654 void ListInit::Profile(FoldingSetNodeID &ID) const {
00655   ListRecTy *ListType = dyn_cast<ListRecTy>(getType());
00656   assert(ListType && "Bad type for ListInit!");
00657   RecTy *EltTy = ListType->getElementType();
00658 
00659   ProfileListInit(ID, Values, EltTy);
00660 }
00661 
00662 Init *
00663 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
00664   std::vector<Init*> Vals;
00665   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00666     if (Elements[i] >= getSize())
00667       return nullptr;
00668     Vals.push_back(getElement(Elements[i]));
00669   }
00670   return ListInit::get(Vals, getType());
00671 }
00672 
00673 Record *ListInit::getElementAsRecord(unsigned i) const {
00674   assert(i < Values.size() && "List element index out of range!");
00675   DefInit *DI = dyn_cast<DefInit>(Values[i]);
00676   if (!DI)
00677     PrintFatalError("Expected record in list!");
00678   return DI->getDef();
00679 }
00680 
00681 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
00682   std::vector<Init*> Resolved;
00683   Resolved.reserve(getSize());
00684   bool Changed = false;
00685 
00686   for (unsigned i = 0, e = getSize(); i != e; ++i) {
00687     Init *E;
00688     Init *CurElt = getElement(i);
00689 
00690     do {
00691       E = CurElt;
00692       CurElt = CurElt->resolveReferences(R, RV);
00693       Changed |= E != CurElt;
00694     } while (E != CurElt);
00695     Resolved.push_back(E);
00696   }
00697 
00698   if (Changed)
00699     return ListInit::get(Resolved, getType());
00700   return const_cast<ListInit *>(this);
00701 }
00702 
00703 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
00704                                             unsigned Elt) const {
00705   if (Elt >= getSize())
00706     return nullptr;  // Out of range reference.
00707   Init *E = getElement(Elt);
00708   // If the element is set to some value, or if we are resolving a reference
00709   // to a specific variable and that variable is explicitly unset, then
00710   // replace the VarListElementInit with it.
00711   if (IRV || !isa<UnsetInit>(E))
00712     return E;
00713   return nullptr;
00714 }
00715 
00716 std::string ListInit::getAsString() const {
00717   std::string Result = "[";
00718   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
00719     if (i) Result += ", ";
00720     Result += Values[i]->getAsString();
00721   }
00722   return Result + "]";
00723 }
00724 
00725 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
00726                                           unsigned Elt) const {
00727   Init *Resolved = resolveReferences(R, IRV);
00728   OpInit *OResolved = dyn_cast<OpInit>(Resolved);
00729   if (OResolved) {
00730     Resolved = OResolved->Fold(&R, nullptr);
00731   }
00732 
00733   if (Resolved != this) {
00734     TypedInit *Typed = dyn_cast<TypedInit>(Resolved);
00735     assert(Typed && "Expected typed init for list reference");
00736     if (Typed) {
00737       Init *New = Typed->resolveListElementReference(R, IRV, Elt);
00738       if (New)
00739         return New;
00740       return VarListElementInit::get(Typed, Elt);
00741     }
00742   }
00743 
00744   return nullptr;
00745 }
00746 
00747 Init *OpInit::getBit(unsigned Bit) const {
00748   if (getType() == BitRecTy::get())
00749     return const_cast<OpInit*>(this);
00750   return VarBitInit::get(const_cast<OpInit*>(this), Bit);
00751 }
00752 
00753 UnOpInit *UnOpInit::get(UnaryOp opc, Init *lhs, RecTy *Type) {
00754   typedef std::pair<std::pair<unsigned, Init *>, RecTy *> Key;
00755   static Pool<DenseMap<Key, UnOpInit *> > ThePool;
00756 
00757   Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
00758 
00759   UnOpInit *&I = ThePool[TheKey];
00760   if (!I) I = new UnOpInit(opc, lhs, Type);
00761   return I;
00762 }
00763 
00764 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
00765   switch (getOpcode()) {
00766   case CAST: {
00767     if (getType()->getAsString() == "string") {
00768       if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
00769         return LHSs;
00770 
00771       if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
00772         return StringInit::get(LHSd->getDef()->getName());
00773 
00774       if (IntInit *LHSi = dyn_cast<IntInit>(LHS))
00775         return StringInit::get(LHSi->getAsString());
00776     } else {
00777       if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
00778         std::string Name = LHSs->getValue();
00779 
00780         // From TGParser::ParseIDValue
00781         if (CurRec) {
00782           if (const RecordVal *RV = CurRec->getValue(Name)) {
00783             if (RV->getType() != getType())
00784               PrintFatalError("type mismatch in cast");
00785             return VarInit::get(Name, RV->getType());
00786           }
00787 
00788           Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name,
00789                                               ":");
00790       
00791           if (CurRec->isTemplateArg(TemplateArgName)) {
00792             const RecordVal *RV = CurRec->getValue(TemplateArgName);
00793             assert(RV && "Template arg doesn't exist??");
00794 
00795             if (RV->getType() != getType())
00796               PrintFatalError("type mismatch in cast");
00797 
00798             return VarInit::get(TemplateArgName, RV->getType());
00799           }
00800         }
00801 
00802         if (CurMultiClass) {
00803           Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
00804 
00805           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
00806             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
00807             assert(RV && "Template arg doesn't exist??");
00808 
00809             if (RV->getType() != getType())
00810               PrintFatalError("type mismatch in cast");
00811 
00812             return VarInit::get(MCName, RV->getType());
00813           }
00814         }
00815 
00816         if (Record *D = (CurRec->getRecords()).getDef(Name))
00817           return DefInit::get(D);
00818 
00819         PrintFatalError(CurRec->getLoc(),
00820                         "Undefined reference:'" + Name + "'\n");
00821       }
00822     }
00823     break;
00824   }
00825   case HEAD: {
00826     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
00827       assert(LHSl->getSize() != 0 && "Empty list in car");
00828       return LHSl->getElement(0);
00829     }
00830     break;
00831   }
00832   case TAIL: {
00833     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
00834       assert(LHSl->getSize() != 0 && "Empty list in cdr");
00835       // Note the +1.  We can't just pass the result of getValues()
00836       // directly.
00837       ArrayRef<Init *>::iterator begin = LHSl->getValues().begin()+1;
00838       ArrayRef<Init *>::iterator end   = LHSl->getValues().end();
00839       ListInit *Result =
00840         ListInit::get(ArrayRef<Init *>(begin, end - begin),
00841                       LHSl->getType());
00842       return Result;
00843     }
00844     break;
00845   }
00846   case EMPTY: {
00847     if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
00848       if (LHSl->getSize() == 0) {
00849         return IntInit::get(1);
00850       } else {
00851         return IntInit::get(0);
00852       }
00853     }
00854     if (StringInit *LHSs = dyn_cast<StringInit>(LHS)) {
00855       if (LHSs->getValue().empty()) {
00856         return IntInit::get(1);
00857       } else {
00858         return IntInit::get(0);
00859       }
00860     }
00861 
00862     break;
00863   }
00864   }
00865   return const_cast<UnOpInit *>(this);
00866 }
00867 
00868 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
00869   Init *lhs = LHS->resolveReferences(R, RV);
00870 
00871   if (LHS != lhs)
00872     return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, nullptr);
00873   return Fold(&R, nullptr);
00874 }
00875 
00876 std::string UnOpInit::getAsString() const {
00877   std::string Result;
00878   switch (Opc) {
00879   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
00880   case HEAD: Result = "!head"; break;
00881   case TAIL: Result = "!tail"; break;
00882   case EMPTY: Result = "!empty"; break;
00883   }
00884   return Result + "(" + LHS->getAsString() + ")";
00885 }
00886 
00887 BinOpInit *BinOpInit::get(BinaryOp opc, Init *lhs,
00888                           Init *rhs, RecTy *Type) {
00889   typedef std::pair<
00890     std::pair<std::pair<unsigned, Init *>, Init *>,
00891     RecTy *
00892     > Key;
00893 
00894   static Pool<DenseMap<Key, BinOpInit *> > ThePool;
00895 
00896   Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
00897                             Type));
00898 
00899   BinOpInit *&I = ThePool[TheKey];
00900   if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
00901   return I;
00902 }
00903 
00904 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
00905   switch (getOpcode()) {
00906   case CONCAT: {
00907     DagInit *LHSs = dyn_cast<DagInit>(LHS);
00908     DagInit *RHSs = dyn_cast<DagInit>(RHS);
00909     if (LHSs && RHSs) {
00910       DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
00911       DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
00912       if (!LOp || !ROp || LOp->getDef() != ROp->getDef())
00913         PrintFatalError("Concated Dag operators do not match!");
00914       std::vector<Init*> Args;
00915       std::vector<std::string> ArgNames;
00916       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
00917         Args.push_back(LHSs->getArg(i));
00918         ArgNames.push_back(LHSs->getArgName(i));
00919       }
00920       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
00921         Args.push_back(RHSs->getArg(i));
00922         ArgNames.push_back(RHSs->getArgName(i));
00923       }
00924       return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
00925     }
00926     break;
00927   }
00928   case LISTCONCAT: {
00929     ListInit *LHSs = dyn_cast<ListInit>(LHS);
00930     ListInit *RHSs = dyn_cast<ListInit>(RHS);
00931     if (LHSs && RHSs) {
00932       std::vector<Init *> Args;
00933       Args.insert(Args.end(), LHSs->begin(), LHSs->end());
00934       Args.insert(Args.end(), RHSs->begin(), RHSs->end());
00935       return ListInit::get(
00936           Args, static_cast<ListRecTy *>(LHSs->getType())->getElementType());
00937     }
00938     break;
00939   }
00940   case STRCONCAT: {
00941     StringInit *LHSs = dyn_cast<StringInit>(LHS);
00942     StringInit *RHSs = dyn_cast<StringInit>(RHS);
00943     if (LHSs && RHSs)
00944       return StringInit::get(LHSs->getValue() + RHSs->getValue());
00945     break;
00946   }
00947   case EQ: {
00948     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
00949     // to string objects.
00950     IntInit *L =
00951       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
00952     IntInit *R =
00953       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
00954 
00955     if (L && R)
00956       return IntInit::get(L->getValue() == R->getValue());
00957 
00958     StringInit *LHSs = dyn_cast<StringInit>(LHS);
00959     StringInit *RHSs = dyn_cast<StringInit>(RHS);
00960 
00961     // Make sure we've resolved
00962     if (LHSs && RHSs)
00963       return IntInit::get(LHSs->getValue() == RHSs->getValue());
00964 
00965     break;
00966   }
00967   case ADD:
00968   case AND:
00969   case SHL:
00970   case SRA:
00971   case SRL: {
00972     IntInit *LHSi =
00973       dyn_cast_or_null<IntInit>(LHS->convertInitializerTo(IntRecTy::get()));
00974     IntInit *RHSi =
00975       dyn_cast_or_null<IntInit>(RHS->convertInitializerTo(IntRecTy::get()));
00976     if (LHSi && RHSi) {
00977       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
00978       int64_t Result;
00979       switch (getOpcode()) {
00980       default: llvm_unreachable("Bad opcode!");
00981       case ADD: Result = LHSv +  RHSv; break;
00982       case AND: Result = LHSv &  RHSv; break;
00983       case SHL: Result = LHSv << RHSv; break;
00984       case SRA: Result = LHSv >> RHSv; break;
00985       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
00986       }
00987       return IntInit::get(Result);
00988     }
00989     break;
00990   }
00991   }
00992   return const_cast<BinOpInit *>(this);
00993 }
00994 
00995 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
00996   Init *lhs = LHS->resolveReferences(R, RV);
00997   Init *rhs = RHS->resolveReferences(R, RV);
00998 
00999   if (LHS != lhs || RHS != rhs)
01000     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R,nullptr);
01001   return Fold(&R, nullptr);
01002 }
01003 
01004 std::string BinOpInit::getAsString() const {
01005   std::string Result;
01006   switch (Opc) {
01007   case CONCAT: Result = "!con"; break;
01008   case ADD: Result = "!add"; break;
01009   case AND: Result = "!and"; break;
01010   case SHL: Result = "!shl"; break;
01011   case SRA: Result = "!sra"; break;
01012   case SRL: Result = "!srl"; break;
01013   case EQ: Result = "!eq"; break;
01014   case LISTCONCAT: Result = "!listconcat"; break;
01015   case STRCONCAT: Result = "!strconcat"; break;
01016   }
01017   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
01018 }
01019 
01020 TernOpInit *TernOpInit::get(TernaryOp opc, Init *lhs,
01021                                   Init *mhs, Init *rhs,
01022                                   RecTy *Type) {
01023   typedef std::pair<
01024     std::pair<
01025       std::pair<std::pair<unsigned, RecTy *>, Init *>,
01026       Init *
01027       >,
01028     Init *
01029     > Key;
01030 
01031   typedef DenseMap<Key, TernOpInit *> Pool;
01032   static Pool ThePool;
01033 
01034   Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
01035                                                                          Type),
01036                                                           lhs),
01037                                            mhs),
01038                             rhs));
01039 
01040   TernOpInit *&I = ThePool[TheKey];
01041   if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
01042   return I;
01043 }
01044 
01045 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
01046                            Record *CurRec, MultiClass *CurMultiClass);
01047 
01048 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
01049                                RecTy *Type, Record *CurRec,
01050                                MultiClass *CurMultiClass) {
01051   std::vector<Init *> NewOperands;
01052 
01053   TypedInit *TArg = dyn_cast<TypedInit>(Arg);
01054 
01055   // If this is a dag, recurse
01056   if (TArg && TArg->getType()->getAsString() == "dag") {
01057     Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
01058                                  CurRec, CurMultiClass);
01059     return Result;
01060   }
01061 
01062   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
01063     OpInit *RHSoo = dyn_cast<OpInit>(RHSo->getOperand(i));
01064 
01065     if (RHSoo) {
01066       Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
01067                                        Type, CurRec, CurMultiClass);
01068       if (Result) {
01069         NewOperands.push_back(Result);
01070       } else {
01071         NewOperands.push_back(Arg);
01072       }
01073     } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
01074       NewOperands.push_back(Arg);
01075     } else {
01076       NewOperands.push_back(RHSo->getOperand(i));
01077     }
01078   }
01079 
01080   // Now run the operator and use its result as the new leaf
01081   const OpInit *NewOp = RHSo->clone(NewOperands);
01082   Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
01083   return (NewVal != NewOp) ? NewVal : nullptr;
01084 }
01085 
01086 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
01087                            Record *CurRec, MultiClass *CurMultiClass) {
01088   DagInit *MHSd = dyn_cast<DagInit>(MHS);
01089   ListInit *MHSl = dyn_cast<ListInit>(MHS);
01090 
01091   OpInit *RHSo = dyn_cast<OpInit>(RHS);
01092 
01093   if (!RHSo) {
01094     PrintFatalError(CurRec->getLoc(), "!foreach requires an operator\n");
01095   }
01096 
01097   TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
01098 
01099   if (!LHSt)
01100     PrintFatalError(CurRec->getLoc(), "!foreach requires typed variable\n");
01101 
01102   if ((MHSd && isa<DagRecTy>(Type)) || (MHSl && isa<ListRecTy>(Type))) {
01103     if (MHSd) {
01104       Init *Val = MHSd->getOperator();
01105       Init *Result = EvaluateOperation(RHSo, LHS, Val,
01106                                        Type, CurRec, CurMultiClass);
01107       if (Result) {
01108         Val = Result;
01109       }
01110 
01111       std::vector<std::pair<Init *, std::string> > args;
01112       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
01113         Init *Arg;
01114         std::string ArgName;
01115         Arg = MHSd->getArg(i);
01116         ArgName = MHSd->getArgName(i);
01117 
01118         // Process args
01119         Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
01120                                          CurRec, CurMultiClass);
01121         if (Result) {
01122           Arg = Result;
01123         }
01124 
01125         // TODO: Process arg names
01126         args.push_back(std::make_pair(Arg, ArgName));
01127       }
01128 
01129       return DagInit::get(Val, "", args);
01130     }
01131     if (MHSl) {
01132       std::vector<Init *> NewOperands;
01133       std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
01134 
01135       for (std::vector<Init *>::iterator li = NewList.begin(),
01136              liend = NewList.end();
01137            li != liend;
01138            ++li) {
01139         Init *Item = *li;
01140         NewOperands.clear();
01141         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
01142           // First, replace the foreach variable with the list item
01143           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
01144             NewOperands.push_back(Item);
01145           } else {
01146             NewOperands.push_back(RHSo->getOperand(i));
01147           }
01148         }
01149 
01150         // Now run the operator and use its result as the new list item
01151         const OpInit *NewOp = RHSo->clone(NewOperands);
01152         Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
01153         if (NewItem != NewOp)
01154           *li = NewItem;
01155       }
01156       return ListInit::get(NewList, MHSl->getType());
01157     }
01158   }
01159   return nullptr;
01160 }
01161 
01162 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
01163   switch (getOpcode()) {
01164   case SUBST: {
01165     DefInit *LHSd = dyn_cast<DefInit>(LHS);
01166     VarInit *LHSv = dyn_cast<VarInit>(LHS);
01167     StringInit *LHSs = dyn_cast<StringInit>(LHS);
01168 
01169     DefInit *MHSd = dyn_cast<DefInit>(MHS);
01170     VarInit *MHSv = dyn_cast<VarInit>(MHS);
01171     StringInit *MHSs = dyn_cast<StringInit>(MHS);
01172 
01173     DefInit *RHSd = dyn_cast<DefInit>(RHS);
01174     VarInit *RHSv = dyn_cast<VarInit>(RHS);
01175     StringInit *RHSs = dyn_cast<StringInit>(RHS);
01176 
01177     if ((LHSd && MHSd && RHSd)
01178         || (LHSv && MHSv && RHSv)
01179         || (LHSs && MHSs && RHSs)) {
01180       if (RHSd) {
01181         Record *Val = RHSd->getDef();
01182         if (LHSd->getAsString() == RHSd->getAsString()) {
01183           Val = MHSd->getDef();
01184         }
01185         return DefInit::get(Val);
01186       }
01187       if (RHSv) {
01188         std::string Val = RHSv->getName();
01189         if (LHSv->getAsString() == RHSv->getAsString()) {
01190           Val = MHSv->getName();
01191         }
01192         return VarInit::get(Val, getType());
01193       }
01194       if (RHSs) {
01195         std::string Val = RHSs->getValue();
01196 
01197         std::string::size_type found;
01198         std::string::size_type idx = 0;
01199         do {
01200           found = Val.find(LHSs->getValue(), idx);
01201           if (found != std::string::npos) {
01202             Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
01203           }
01204           idx = found +  MHSs->getValue().size();
01205         } while (found != std::string::npos);
01206 
01207         return StringInit::get(Val);
01208       }
01209     }
01210     break;
01211   }
01212 
01213   case FOREACH: {
01214     Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
01215                                  CurRec, CurMultiClass);
01216     if (Result) {
01217       return Result;
01218     }
01219     break;
01220   }
01221 
01222   case IF: {
01223     IntInit *LHSi = dyn_cast<IntInit>(LHS);
01224     if (Init *I = LHS->convertInitializerTo(IntRecTy::get()))
01225       LHSi = dyn_cast<IntInit>(I);
01226     if (LHSi) {
01227       if (LHSi->getValue()) {
01228         return MHS;
01229       } else {
01230         return RHS;
01231       }
01232     }
01233     break;
01234   }
01235   }
01236 
01237   return const_cast<TernOpInit *>(this);
01238 }
01239 
01240 Init *TernOpInit::resolveReferences(Record &R,
01241                                     const RecordVal *RV) const {
01242   Init *lhs = LHS->resolveReferences(R, RV);
01243 
01244   if (Opc == IF && lhs != LHS) {
01245     IntInit *Value = dyn_cast<IntInit>(lhs);
01246     if (Init *I = lhs->convertInitializerTo(IntRecTy::get()))
01247       Value = dyn_cast<IntInit>(I);
01248     if (Value) {
01249       // Short-circuit
01250       if (Value->getValue()) {
01251         Init *mhs = MHS->resolveReferences(R, RV);
01252         return (TernOpInit::get(getOpcode(), lhs, mhs,
01253                                 RHS, getType()))->Fold(&R, nullptr);
01254       } else {
01255         Init *rhs = RHS->resolveReferences(R, RV);
01256         return (TernOpInit::get(getOpcode(), lhs, MHS,
01257                                 rhs, getType()))->Fold(&R, nullptr);
01258       }
01259     }
01260   }
01261 
01262   Init *mhs = MHS->resolveReferences(R, RV);
01263   Init *rhs = RHS->resolveReferences(R, RV);
01264 
01265   if (LHS != lhs || MHS != mhs || RHS != rhs)
01266     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
01267                             getType()))->Fold(&R, nullptr);
01268   return Fold(&R, nullptr);
01269 }
01270 
01271 std::string TernOpInit::getAsString() const {
01272   std::string Result;
01273   switch (Opc) {
01274   case SUBST: Result = "!subst"; break;
01275   case FOREACH: Result = "!foreach"; break;
01276   case IF: Result = "!if"; break;
01277  }
01278   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
01279     + RHS->getAsString() + ")";
01280 }
01281 
01282 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
01283   if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType()))
01284     if (RecordVal *Field = RecordType->getRecord()->getValue(FieldName))
01285       return Field->getType();
01286   return nullptr;
01287 }
01288 
01289 Init *
01290 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
01291   BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
01292   if (!T) return nullptr;  // Cannot subscript a non-bits variable.
01293   unsigned NumBits = T->getNumBits();
01294 
01295   SmallVector<Init *, 16> NewBits(Bits.size());
01296   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
01297     if (Bits[i] >= NumBits)
01298       return nullptr;
01299 
01300     NewBits[i] = VarBitInit::get(const_cast<TypedInit *>(this), Bits[i]);
01301   }
01302   return BitsInit::get(NewBits);
01303 }
01304 
01305 Init *
01306 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
01307   ListRecTy *T = dyn_cast<ListRecTy>(getType());
01308   if (!T) return nullptr;  // Cannot subscript a non-list variable.
01309 
01310   if (Elements.size() == 1)
01311     return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
01312 
01313   std::vector<Init*> ListInits;
01314   ListInits.reserve(Elements.size());
01315   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
01316     ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
01317                                                 Elements[i]));
01318   return ListInit::get(ListInits, T);
01319 }
01320 
01321 
01322 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
01323   Init *Value = StringInit::get(VN);
01324   return VarInit::get(Value, T);
01325 }
01326 
01327 VarInit *VarInit::get(Init *VN, RecTy *T) {
01328   typedef std::pair<RecTy *, Init *> Key;
01329   static Pool<DenseMap<Key, VarInit *> > ThePool;
01330 
01331   Key TheKey(std::make_pair(T, VN));
01332 
01333   VarInit *&I = ThePool[TheKey];
01334   if (!I) I = new VarInit(VN, T);
01335   return I;
01336 }
01337 
01338 const std::string &VarInit::getName() const {
01339   StringInit *NameString = dyn_cast<StringInit>(getNameInit());
01340   assert(NameString && "VarInit name is not a string!");
01341   return NameString->getValue();
01342 }
01343 
01344 Init *VarInit::getBit(unsigned Bit) const {
01345   if (getType() == BitRecTy::get())
01346     return const_cast<VarInit*>(this);
01347   return VarBitInit::get(const_cast<VarInit*>(this), Bit);
01348 }
01349 
01350 Init *VarInit::resolveListElementReference(Record &R,
01351                                            const RecordVal *IRV,
01352                                            unsigned Elt) const {
01353   if (R.isTemplateArg(getNameInit())) return nullptr;
01354   if (IRV && IRV->getNameInit() != getNameInit()) return nullptr;
01355 
01356   RecordVal *RV = R.getValue(getNameInit());
01357   assert(RV && "Reference to a non-existent variable?");
01358   ListInit *LI = dyn_cast<ListInit>(RV->getValue());
01359   if (!LI) {
01360     TypedInit *VI = dyn_cast<TypedInit>(RV->getValue());
01361     assert(VI && "Invalid list element!");
01362     return VarListElementInit::get(VI, Elt);
01363   }
01364 
01365   if (Elt >= LI->getSize())
01366     return nullptr;  // Out of range reference.
01367   Init *E = LI->getElement(Elt);
01368   // If the element is set to some value, or if we are resolving a reference
01369   // to a specific variable and that variable is explicitly unset, then
01370   // replace the VarListElementInit with it.
01371   if (IRV || !isa<UnsetInit>(E))
01372     return E;
01373   return nullptr;
01374 }
01375 
01376 
01377 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
01378   if (RecordRecTy *RTy = dyn_cast<RecordRecTy>(getType()))
01379     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
01380       return RV->getType();
01381   return nullptr;
01382 }
01383 
01384 Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
01385                             const std::string &FieldName) const {
01386   if (isa<RecordRecTy>(getType()))
01387     if (const RecordVal *Val = R.getValue(VarName)) {
01388       if (RV != Val && (RV || isa<UnsetInit>(Val->getValue())))
01389         return nullptr;
01390       Init *TheInit = Val->getValue();
01391       assert(TheInit != this && "Infinite loop detected!");
01392       if (Init *I = TheInit->getFieldInit(R, RV, FieldName))
01393         return I;
01394       else
01395         return nullptr;
01396     }
01397   return nullptr;
01398 }
01399 
01400 /// resolveReferences - This method is used by classes that refer to other
01401 /// variables which may not be defined at the time the expression is formed.
01402 /// If a value is set for the variable later, this method will be called on
01403 /// users of the value to allow the value to propagate out.
01404 ///
01405 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
01406   if (RecordVal *Val = R.getValue(VarName))
01407     if (RV == Val || (!RV && !isa<UnsetInit>(Val->getValue())))
01408       return Val->getValue();
01409   return const_cast<VarInit *>(this);
01410 }
01411 
01412 VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
01413   typedef std::pair<TypedInit *, unsigned> Key;
01414   typedef DenseMap<Key, VarBitInit *> Pool;
01415 
01416   static Pool ThePool;
01417 
01418   Key TheKey(std::make_pair(T, B));
01419 
01420   VarBitInit *&I = ThePool[TheKey];
01421   if (!I) I = new VarBitInit(T, B);
01422   return I;
01423 }
01424 
01425 std::string VarBitInit::getAsString() const {
01426    return TI->getAsString() + "{" + utostr(Bit) + "}";
01427 }
01428 
01429 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) const {
01430   Init *I = TI->resolveReferences(R, RV);
01431   if (TI != I)
01432     return I->getBit(getBitNum());
01433 
01434   return const_cast<VarBitInit*>(this);
01435 }
01436 
01437 VarListElementInit *VarListElementInit::get(TypedInit *T,
01438                                             unsigned E) {
01439   typedef std::pair<TypedInit *, unsigned> Key;
01440   typedef DenseMap<Key, VarListElementInit *> Pool;
01441 
01442   static Pool ThePool;
01443 
01444   Key TheKey(std::make_pair(T, E));
01445 
01446   VarListElementInit *&I = ThePool[TheKey];
01447   if (!I) I = new VarListElementInit(T, E);
01448   return I;
01449 }
01450 
01451 std::string VarListElementInit::getAsString() const {
01452   return TI->getAsString() + "[" + utostr(Element) + "]";
01453 }
01454 
01455 Init *
01456 VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) const {
01457   if (Init *I = getVariable()->resolveListElementReference(R, RV,
01458                                                            getElementNum()))
01459     return I;
01460   return const_cast<VarListElementInit *>(this);
01461 }
01462 
01463 Init *VarListElementInit::getBit(unsigned Bit) const {
01464   if (getType() == BitRecTy::get())
01465     return const_cast<VarListElementInit*>(this);
01466   return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
01467 }
01468 
01469 Init *VarListElementInit:: resolveListElementReference(Record &R,
01470                                                        const RecordVal *RV,
01471                                                        unsigned Elt) const {
01472   Init *Result = TI->resolveListElementReference(R, RV, Element);
01473   
01474   if (Result) {
01475     if (TypedInit *TInit = dyn_cast<TypedInit>(Result)) {
01476       Init *Result2 = TInit->resolveListElementReference(R, RV, Elt);
01477       if (Result2) return Result2;
01478       return new VarListElementInit(TInit, Elt);
01479     }
01480     return Result;
01481   }
01482  
01483   return nullptr;
01484 }
01485 
01486 DefInit *DefInit::get(Record *R) {
01487   return R->getDefInit();
01488 }
01489 
01490 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
01491   if (const RecordVal *RV = Def->getValue(FieldName))
01492     return RV->getType();
01493   return nullptr;
01494 }
01495 
01496 Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
01497                             const std::string &FieldName) const {
01498   return Def->getValue(FieldName)->getValue();
01499 }
01500 
01501 
01502 std::string DefInit::getAsString() const {
01503   return Def->getName();
01504 }
01505 
01506 FieldInit *FieldInit::get(Init *R, const std::string &FN) {
01507   typedef std::pair<Init *, TableGenStringKey> Key;
01508   typedef DenseMap<Key, FieldInit *> Pool;
01509   static Pool ThePool;  
01510 
01511   Key TheKey(std::make_pair(R, FN));
01512 
01513   FieldInit *&I = ThePool[TheKey];
01514   if (!I) I = new FieldInit(R, FN);
01515   return I;
01516 }
01517 
01518 Init *FieldInit::getBit(unsigned Bit) const {
01519   if (getType() == BitRecTy::get())
01520     return const_cast<FieldInit*>(this);
01521   return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
01522 }
01523 
01524 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
01525                                              unsigned Elt) const {
01526   if (Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
01527     if (ListInit *LI = dyn_cast<ListInit>(ListVal)) {
01528       if (Elt >= LI->getSize()) return nullptr;
01529       Init *E = LI->getElement(Elt);
01530 
01531       // If the element is set to some value, or if we are resolving a
01532       // reference to a specific variable and that variable is explicitly
01533       // unset, then replace the VarListElementInit with it.
01534       if (RV || !isa<UnsetInit>(E))
01535         return E;
01536     }
01537   return nullptr;
01538 }
01539 
01540 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
01541   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
01542 
01543   Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
01544   if (BitsVal) {
01545     Init *BVR = BitsVal->resolveReferences(R, RV);
01546     return BVR->isComplete() ? BVR : const_cast<FieldInit *>(this);
01547   }
01548 
01549   if (NewRec != Rec) {
01550     return FieldInit::get(NewRec, FieldName);
01551   }
01552   return const_cast<FieldInit *>(this);
01553 }
01554 
01555 static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, const std::string &VN,
01556                            ArrayRef<Init *> ArgRange,
01557                            ArrayRef<std::string> NameRange) {
01558   ID.AddPointer(V);
01559   ID.AddString(VN);
01560 
01561   ArrayRef<Init *>::iterator Arg  = ArgRange.begin();
01562   ArrayRef<std::string>::iterator  Name = NameRange.begin();
01563   while (Arg != ArgRange.end()) {
01564     assert(Name != NameRange.end() && "Arg name underflow!");
01565     ID.AddPointer(*Arg++);
01566     ID.AddString(*Name++);
01567   }
01568   assert(Name == NameRange.end() && "Arg name overflow!");
01569 }
01570 
01571 DagInit *
01572 DagInit::get(Init *V, const std::string &VN,
01573              ArrayRef<Init *> ArgRange,
01574              ArrayRef<std::string> NameRange) {
01575   typedef FoldingSet<DagInit> Pool;
01576   static Pool ThePool;  
01577 
01578   FoldingSetNodeID ID;
01579   ProfileDagInit(ID, V, VN, ArgRange, NameRange);
01580 
01581   void *IP = nullptr;
01582   if (DagInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
01583     return I;
01584 
01585   DagInit *I = new DagInit(V, VN, ArgRange, NameRange);
01586   ThePool.InsertNode(I, IP);
01587 
01588   return I;
01589 }
01590 
01591 DagInit *
01592 DagInit::get(Init *V, const std::string &VN,
01593              const std::vector<std::pair<Init*, std::string> > &args) {
01594   typedef std::pair<Init*, std::string> PairType;
01595 
01596   std::vector<Init *> Args;
01597   std::vector<std::string> Names;
01598 
01599   for (std::vector<PairType>::const_iterator i = args.begin(),
01600          iend = args.end();
01601        i != iend;
01602        ++i) {
01603     Args.push_back(i->first);
01604     Names.push_back(i->second);
01605   }
01606 
01607   return DagInit::get(V, VN, Args, Names);
01608 }
01609 
01610 void DagInit::Profile(FoldingSetNodeID &ID) const {
01611   ProfileDagInit(ID, Val, ValName, Args, ArgNames);
01612 }
01613 
01614 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
01615   std::vector<Init*> NewArgs;
01616   for (unsigned i = 0, e = Args.size(); i != e; ++i)
01617     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
01618 
01619   Init *Op = Val->resolveReferences(R, RV);
01620 
01621   if (Args != NewArgs || Op != Val)
01622     return DagInit::get(Op, ValName, NewArgs, ArgNames);
01623 
01624   return const_cast<DagInit *>(this);
01625 }
01626 
01627 
01628 std::string DagInit::getAsString() const {
01629   std::string Result = "(" + Val->getAsString();
01630   if (!ValName.empty())
01631     Result += ":" + ValName;
01632   if (Args.size()) {
01633     Result += " " + Args[0]->getAsString();
01634     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
01635     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
01636       Result += ", " + Args[i]->getAsString();
01637       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
01638     }
01639   }
01640   return Result + ")";
01641 }
01642 
01643 
01644 //===----------------------------------------------------------------------===//
01645 //    Other implementations
01646 //===----------------------------------------------------------------------===//
01647 
01648 RecordVal::RecordVal(Init *N, RecTy *T, unsigned P)
01649   : Name(N), Ty(T), Prefix(P) {
01650   Value = Ty->convertValue(UnsetInit::get());
01651   assert(Value && "Cannot create unset value for current type!");
01652 }
01653 
01654 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
01655   : Name(StringInit::get(N)), Ty(T), Prefix(P) {
01656   Value = Ty->convertValue(UnsetInit::get());
01657   assert(Value && "Cannot create unset value for current type!");
01658 }
01659 
01660 const std::string &RecordVal::getName() const {
01661   StringInit *NameString = dyn_cast<StringInit>(Name);
01662   assert(NameString && "RecordVal name is not a string!");
01663   return NameString->getValue();
01664 }
01665 
01666 void RecordVal::dump() const { errs() << *this; }
01667 
01668 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
01669   if (getPrefix()) OS << "field ";
01670   OS << *getType() << " " << getNameInitAsString();
01671 
01672   if (getValue())
01673     OS << " = " << *getValue();
01674 
01675   if (PrintSem) OS << ";\n";
01676 }
01677 
01678 unsigned Record::LastID = 0;
01679 
01680 void Record::init() {
01681   checkName();
01682 
01683   // Every record potentially has a def at the top.  This value is
01684   // replaced with the top-level def name at instantiation time.
01685   RecordVal DN("NAME", StringRecTy::get(), 0);
01686   addValue(DN);
01687 }
01688 
01689 void Record::checkName() {
01690   // Ensure the record name has string type.
01691   const TypedInit *TypedName = dyn_cast<const TypedInit>(Name);
01692   assert(TypedName && "Record name is not typed!");
01693   RecTy *Type = TypedName->getType();
01694   if (!isa<StringRecTy>(Type))
01695     PrintFatalError(getLoc(), "Record name is not a string!");
01696 }
01697 
01698 DefInit *Record::getDefInit() {
01699   if (!TheInit)
01700     TheInit = new DefInit(this, new RecordRecTy(this));
01701   return TheInit;
01702 }
01703 
01704 const std::string &Record::getName() const {
01705   const StringInit *NameString = dyn_cast<StringInit>(Name);
01706   assert(NameString && "Record name is not a string!");
01707   return NameString->getValue();
01708 }
01709 
01710 void Record::setName(Init *NewName) {
01711   Name = NewName;
01712   checkName();
01713   // DO NOT resolve record values to the name at this point because
01714   // there might be default values for arguments of this def.  Those
01715   // arguments might not have been resolved yet so we don't want to
01716   // prematurely assume values for those arguments were not passed to
01717   // this def.
01718   //
01719   // Nonetheless, it may be that some of this Record's values
01720   // reference the record name.  Indeed, the reason for having the
01721   // record name be an Init is to provide this flexibility.  The extra
01722   // resolve steps after completely instantiating defs takes care of
01723   // this.  See TGParser::ParseDef and TGParser::ParseDefm.
01724 }
01725 
01726 void Record::setName(const std::string &Name) {
01727   setName(StringInit::get(Name));
01728 }
01729 
01730 /// resolveReferencesTo - If anything in this record refers to RV, replace the
01731 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
01732 /// references.
01733 void Record::resolveReferencesTo(const RecordVal *RV) {
01734   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
01735     if (RV == &Values[i]) // Skip resolve the same field as the given one
01736       continue;
01737     if (Init *V = Values[i].getValue())
01738       if (Values[i].setValue(V->resolveReferences(*this, RV)))
01739         PrintFatalError(getLoc(), "Invalid value is found when setting '"
01740                       + Values[i].getNameInitAsString()
01741                       + "' after resolving references"
01742                       + (RV ? " against '" + RV->getNameInitAsString()
01743                               + "' of ("
01744                               + RV->getValue()->getAsUnquotedString() + ")"
01745                             : "")
01746                       + "\n");
01747   }
01748   Init *OldName = getNameInit();
01749   Init *NewName = Name->resolveReferences(*this, RV);
01750   if (NewName != OldName) {
01751     // Re-register with RecordKeeper.
01752     setName(NewName);
01753   }
01754 }
01755 
01756 void Record::dump() const { errs() << *this; }
01757 
01758 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
01759   OS << R.getNameInitAsString();
01760 
01761   const std::vector<Init *> &TArgs = R.getTemplateArgs();
01762   if (!TArgs.empty()) {
01763     OS << "<";
01764     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
01765       if (i) OS << ", ";
01766       const RecordVal *RV = R.getValue(TArgs[i]);
01767       assert(RV && "Template argument record not found??");
01768       RV->print(OS, false);
01769     }
01770     OS << ">";
01771   }
01772 
01773   OS << " {";
01774   const std::vector<Record*> &SC = R.getSuperClasses();
01775   if (!SC.empty()) {
01776     OS << "\t//";
01777     for (unsigned i = 0, e = SC.size(); i != e; ++i)
01778       OS << " " << SC[i]->getNameInitAsString();
01779   }
01780   OS << "\n";
01781 
01782   const std::vector<RecordVal> &Vals = R.getValues();
01783   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
01784     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
01785       OS << Vals[i];
01786   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
01787     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
01788       OS << Vals[i];
01789 
01790   return OS << "}\n";
01791 }
01792 
01793 /// getValueInit - Return the initializer for a value with the specified name,
01794 /// or abort if the field does not exist.
01795 ///
01796 Init *Record::getValueInit(StringRef FieldName) const {
01797   const RecordVal *R = getValue(FieldName);
01798   if (!R || !R->getValue())
01799     PrintFatalError(getLoc(), "Record `" + getName() +
01800       "' does not have a field named `" + FieldName + "'!\n");
01801   return R->getValue();
01802 }
01803 
01804 
01805 /// getValueAsString - This method looks up the specified field and returns its
01806 /// value as a string, aborts if the field does not exist or if
01807 /// the value is not a string.
01808 ///
01809 std::string Record::getValueAsString(StringRef FieldName) const {
01810   const RecordVal *R = getValue(FieldName);
01811   if (!R || !R->getValue())
01812     PrintFatalError(getLoc(), "Record `" + getName() +
01813       "' does not have a field named `" + FieldName + "'!\n");
01814 
01815   if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
01816     return SI->getValue();
01817   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01818     FieldName + "' does not have a string initializer!");
01819 }
01820 
01821 /// getValueAsBitsInit - This method looks up the specified field and returns
01822 /// its value as a BitsInit, aborts if the field does not exist or if
01823 /// the value is not the right type.
01824 ///
01825 BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
01826   const RecordVal *R = getValue(FieldName);
01827   if (!R || !R->getValue())
01828     PrintFatalError(getLoc(), "Record `" + getName() +
01829       "' does not have a field named `" + FieldName + "'!\n");
01830 
01831   if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
01832     return BI;
01833   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01834     FieldName + "' does not have a BitsInit initializer!");
01835 }
01836 
01837 /// getValueAsListInit - This method looks up the specified field and returns
01838 /// its value as a ListInit, aborting if the field does not exist or if
01839 /// the value is not the right type.
01840 ///
01841 ListInit *Record::getValueAsListInit(StringRef FieldName) const {
01842   const RecordVal *R = getValue(FieldName);
01843   if (!R || !R->getValue())
01844     PrintFatalError(getLoc(), "Record `" + getName() +
01845       "' does not have a field named `" + FieldName + "'!\n");
01846 
01847   if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
01848     return LI;
01849   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01850     FieldName + "' does not have a list initializer!");
01851 }
01852 
01853 /// getValueAsListOfDefs - This method looks up the specified field and returns
01854 /// its value as a vector of records, aborting if the field does not exist
01855 /// or if the value is not the right type.
01856 ///
01857 std::vector<Record*>
01858 Record::getValueAsListOfDefs(StringRef FieldName) const {
01859   ListInit *List = getValueAsListInit(FieldName);
01860   std::vector<Record*> Defs;
01861   for (unsigned i = 0; i < List->getSize(); i++) {
01862     if (DefInit *DI = dyn_cast<DefInit>(List->getElement(i))) {
01863       Defs.push_back(DI->getDef());
01864     } else {
01865       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01866         FieldName + "' list is not entirely DefInit!");
01867     }
01868   }
01869   return Defs;
01870 }
01871 
01872 /// getValueAsInt - This method looks up the specified field and returns its
01873 /// value as an int64_t, aborting if the field does not exist or if the value
01874 /// is not the right type.
01875 ///
01876 int64_t Record::getValueAsInt(StringRef FieldName) const {
01877   const RecordVal *R = getValue(FieldName);
01878   if (!R || !R->getValue())
01879     PrintFatalError(getLoc(), "Record `" + getName() +
01880       "' does not have a field named `" + FieldName + "'!\n");
01881 
01882   if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
01883     return II->getValue();
01884   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01885     FieldName + "' does not have an int initializer!");
01886 }
01887 
01888 /// getValueAsListOfInts - This method looks up the specified field and returns
01889 /// its value as a vector of integers, aborting if the field does not exist or
01890 /// if the value is not the right type.
01891 ///
01892 std::vector<int64_t>
01893 Record::getValueAsListOfInts(StringRef FieldName) const {
01894   ListInit *List = getValueAsListInit(FieldName);
01895   std::vector<int64_t> Ints;
01896   for (unsigned i = 0; i < List->getSize(); i++) {
01897     if (IntInit *II = dyn_cast<IntInit>(List->getElement(i))) {
01898       Ints.push_back(II->getValue());
01899     } else {
01900       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01901         FieldName + "' does not have a list of ints initializer!");
01902     }
01903   }
01904   return Ints;
01905 }
01906 
01907 /// getValueAsListOfStrings - This method looks up the specified field and
01908 /// returns its value as a vector of strings, aborting if the field does not
01909 /// exist or if the value is not the right type.
01910 ///
01911 std::vector<std::string>
01912 Record::getValueAsListOfStrings(StringRef FieldName) const {
01913   ListInit *List = getValueAsListInit(FieldName);
01914   std::vector<std::string> Strings;
01915   for (unsigned i = 0; i < List->getSize(); i++) {
01916     if (StringInit *II = dyn_cast<StringInit>(List->getElement(i))) {
01917       Strings.push_back(II->getValue());
01918     } else {
01919       PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01920         FieldName + "' does not have a list of strings initializer!");
01921     }
01922   }
01923   return Strings;
01924 }
01925 
01926 /// getValueAsDef - This method looks up the specified field and returns its
01927 /// value as a Record, aborting if the field does not exist or if the value
01928 /// is not the right type.
01929 ///
01930 Record *Record::getValueAsDef(StringRef FieldName) const {
01931   const RecordVal *R = getValue(FieldName);
01932   if (!R || !R->getValue())
01933     PrintFatalError(getLoc(), "Record `" + getName() +
01934       "' does not have a field named `" + FieldName + "'!\n");
01935 
01936   if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
01937     return DI->getDef();
01938   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01939     FieldName + "' does not have a def initializer!");
01940 }
01941 
01942 /// getValueAsBit - This method looks up the specified field and returns its
01943 /// value as a bit, aborting if the field does not exist or if the value is
01944 /// not the right type.
01945 ///
01946 bool Record::getValueAsBit(StringRef FieldName) const {
01947   const RecordVal *R = getValue(FieldName);
01948   if (!R || !R->getValue())
01949     PrintFatalError(getLoc(), "Record `" + getName() +
01950       "' does not have a field named `" + FieldName + "'!\n");
01951 
01952   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
01953     return BI->getValue();
01954   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01955     FieldName + "' does not have a bit initializer!");
01956 }
01957 
01958 bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
01959   const RecordVal *R = getValue(FieldName);
01960   if (!R || !R->getValue())
01961     PrintFatalError(getLoc(), "Record `" + getName() +
01962       "' does not have a field named `" + FieldName.str() + "'!\n");
01963 
01964   if (R->getValue() == UnsetInit::get()) {
01965     Unset = true;
01966     return false;
01967   }
01968   Unset = false;
01969   if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
01970     return BI->getValue();
01971   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01972     FieldName + "' does not have a bit initializer!");
01973 }
01974 
01975 /// getValueAsDag - This method looks up the specified field and returns its
01976 /// value as an Dag, aborting if the field does not exist or if the value is
01977 /// not the right type.
01978 ///
01979 DagInit *Record::getValueAsDag(StringRef FieldName) const {
01980   const RecordVal *R = getValue(FieldName);
01981   if (!R || !R->getValue())
01982     PrintFatalError(getLoc(), "Record `" + getName() +
01983       "' does not have a field named `" + FieldName + "'!\n");
01984 
01985   if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
01986     return DI;
01987   PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
01988     FieldName + "' does not have a dag initializer!");
01989 }
01990 
01991 
01992 void MultiClass::dump() const {
01993   errs() << "Record:\n";
01994   Rec.dump();
01995 
01996   errs() << "Defs:\n";
01997   for (RecordVector::const_iterator r = DefPrototypes.begin(),
01998          rend = DefPrototypes.end();
01999        r != rend;
02000        ++r) {
02001     (*r)->dump();
02002   }
02003 }
02004 
02005 
02006 void RecordKeeper::dump() const { errs() << *this; }
02007 
02008 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
02009   OS << "------------- Classes -----------------\n";
02010   const auto &Classes = RK.getClasses();
02011   for (const auto &C : Classes)
02012     OS << "class " << *C.second;
02013 
02014   OS << "------------- Defs -----------------\n";
02015   const auto &Defs = RK.getDefs();
02016   for (const auto &D : Defs)
02017     OS << "def " << *D.second;
02018   return OS;
02019 }
02020 
02021 
02022 /// getAllDerivedDefinitions - This method returns all concrete definitions
02023 /// that derive from the specified class name.  If a class with the specified
02024 /// name does not exist, an error is printed and true is returned.
02025 std::vector<Record*>
02026 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
02027   Record *Class = getClass(ClassName);
02028   if (!Class)
02029     PrintFatalError("ERROR: Couldn't find the `" + ClassName + "' class!\n");
02030 
02031   std::vector<Record*> Defs;
02032   for (const auto &D : getDefs())
02033     if (D.second->isSubClassOf(Class))
02034       Defs.push_back(D.second.get());
02035 
02036   return Defs;
02037 }
02038 
02039 /// QualifyName - Return an Init with a qualifier prefix referring
02040 /// to CurRec's name.
02041 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
02042                         Init *Name, const std::string &Scoper) {
02043   RecTy *Type = dyn_cast<TypedInit>(Name)->getType();
02044 
02045   BinOpInit *NewName =
02046     BinOpInit::get(BinOpInit::STRCONCAT, 
02047                       BinOpInit::get(BinOpInit::STRCONCAT,
02048                                         CurRec.getNameInit(),
02049                                         StringInit::get(Scoper),
02050                                         Type)->Fold(&CurRec, CurMultiClass),
02051                       Name,
02052                       Type);
02053 
02054   if (CurMultiClass && Scoper != "::") {
02055     NewName =
02056       BinOpInit::get(BinOpInit::STRCONCAT, 
02057                         BinOpInit::get(BinOpInit::STRCONCAT,
02058                                           CurMultiClass->Rec.getNameInit(),
02059                                           StringInit::get("::"),
02060                                           Type)->Fold(&CurRec, CurMultiClass),
02061                         NewName->Fold(&CurRec, CurMultiClass),
02062                         Type);
02063   }
02064 
02065   return NewName->Fold(&CurRec, CurMultiClass);
02066 }
02067 
02068 /// QualifyName - Return an Init with a qualifier prefix referring
02069 /// to CurRec's name.
02070 Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
02071                         const std::string &Name,
02072                         const std::string &Scoper) {
02073   return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);
02074 }