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