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