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