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