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