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