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