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