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