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