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