133a1581c0e3dfd083f6e091aaf8e65fa8df57a9
[oota-llvm.git] / utils / TableGen / Record.cpp
1
2 //===- Record.cpp - Record implementation ---------------------------------===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // Implement the tablegen record classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Record.h"
16 #include "Error.h"
17 #include "llvm/Support/DataTypes.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //    std::string wrapper for DenseMap purposes
30 //===----------------------------------------------------------------------===//
31
32 /// TableGenStringKey - This is a wrapper for std::string suitable for
33 /// using as a key to a DenseMap.  Because there isn't a particularly
34 /// good way to indicate tombstone or empty keys for strings, we want
35 /// to wrap std::string to indicate that this is a "special" string
36 /// not expected to take on certain values (those of the tombstone and
37 /// empty keys).  This makes things a little safer as it clarifies
38 /// that DenseMap is really not appropriate for general strings.
39
40 class TableGenStringKey {
41 public:
42   TableGenStringKey(const std::string &str) : data(str) {}
43   TableGenStringKey(const char *str) : data(str) {}
44
45   const std::string &str() const { return data; }
46   
47 private:
48   std::string data;
49 };
50
51 /// Specialize DenseMapInfo for TableGenStringKey.
52 namespace llvm {
53
54 template<> struct DenseMapInfo<TableGenStringKey> {
55   static inline TableGenStringKey getEmptyKey() {
56     TableGenStringKey Empty("<<<EMPTY KEY>>>");
57     return Empty;
58   }
59   static inline TableGenStringKey getTombstoneKey() {
60     TableGenStringKey Tombstone("<<<TOMBSTONE KEY>>>");
61     return Tombstone;
62   }
63   static unsigned getHashValue(const TableGenStringKey& Val) {
64     return HashString(Val.str());
65   }
66   static bool isEqual(const TableGenStringKey& LHS,
67                       const TableGenStringKey& RHS) {
68     return LHS.str() == RHS.str();
69   }
70 };
71
72 }
73
74 //===----------------------------------------------------------------------===//
75 //    Type implementations
76 //===----------------------------------------------------------------------===//
77
78 BitRecTy BitRecTy::Shared;
79 IntRecTy IntRecTy::Shared;
80 StringRecTy StringRecTy::Shared;
81 CodeRecTy CodeRecTy::Shared;
82 DagRecTy DagRecTy::Shared;
83
84 void RecTy::dump() const { print(errs()); }
85
86 ListRecTy *RecTy::getListTy() {
87   if (!ListTy)
88     ListTy = new ListRecTy(this);
89   return ListTy;
90 }
91
92 const Init *BitRecTy::convertValue(const 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 const Init *BitRecTy::convertValue(const 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 const Init *BitRecTy::convertValue(const 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 const Init *BitsRecTy::convertValue(const UnsetInit *UI) {
129   SmallVector<const 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 const Init *BitsRecTy::convertValue(const 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 const Init *BitsRecTy::convertValue(const 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<const 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 const Init *BitsRecTy::convertValue(const 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 const Init *BitsRecTy::convertValue(const TypedInit *VI) {
175   if (BitsRecTy *BRT = dynamic_cast<BitsRecTy*>(VI->getType()))
176     if (BRT->Size == Size) {
177       SmallVector<const 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 (const TernOpInit *Tern = dynamic_cast<const TernOpInit*>(VI)) {
188     if (Tern->getOpcode() == TernOpInit::IF) {
189       const Init *LHS = Tern->getLHS();
190       const Init *MHS = Tern->getMHS();
191       const Init *RHS = Tern->getRHS();
192
193       const IntInit *MHSi = dynamic_cast<const IntInit*>(MHS);
194       const IntInit *RHSi = dynamic_cast<const 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<const 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         const BitsInit *MHSbs = dynamic_cast<const BitsInit*>(MHS);
214         const BitsInit *RHSbs = dynamic_cast<const BitsInit*>(RHS);
215
216         if (MHSbs && RHSbs) {
217           SmallVector<const 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 const Init *IntRecTy::convertValue(const BitInit *BI) {
235   return IntInit::get(BI->getValue());
236 }
237
238 const Init *IntRecTy::convertValue(const BitsInit *BI) {
239   int64_t Result = 0;
240   for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
241     if (const BitInit *Bit = dynamic_cast<const BitInit*>(BI->getBit(i))) {
242       Result |= Bit->getValue() << i;
243     } else {
244       return 0;
245     }
246   return IntInit::get(Result);
247 }
248
249 const Init *IntRecTy::convertValue(const 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 const Init *StringRecTy::convertValue(const UnOpInit *BO) {
256   if (BO->getOpcode() == UnOpInit::CAST) {
257     const 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((const TypedInit*)BO);
265 }
266
267 const Init *StringRecTy::convertValue(const BinOpInit *BO) {
268   if (BO->getOpcode() == BinOpInit::STRCONCAT) {
269     const Init *L = BO->getLHS()->convertInitializerTo(this);
270     const 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((const TypedInit*)BO);
278 }
279
280
281 const Init *StringRecTy::convertValue(const 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 const Init *ListRecTy::convertValue(const ListInit *LI) {
292   std::vector<const 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 (const 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 const Init *ListRecTy::convertValue(const 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 const Init *CodeRecTy::convertValue(const TypedInit *TI) {
319   if (TI->getType()->typeIsConvertibleTo(this))
320     return TI;
321   return 0;
322 }
323
324 const Init *DagRecTy::convertValue(const TypedInit *TI) {
325   if (TI->getType()->typeIsConvertibleTo(this))
326     return TI;
327   return 0;
328 }
329
330 const Init *DagRecTy::convertValue(const UnOpInit *BO) {
331   if (BO->getOpcode() == UnOpInit::CAST) {
332     const Init *L = BO->getOperand()->convertInitializerTo(this);
333     if (L == 0) return 0;
334     if (L != BO->getOperand())
335       return UnOpInit::get(UnOpInit::CAST, L, new DagRecTy);
336     return BO;
337   }
338   return 0;
339 }
340
341 const Init *DagRecTy::convertValue(const BinOpInit *BO) {
342   if (BO->getOpcode() == BinOpInit::CONCAT) {
343     const Init *L = BO->getLHS()->convertInitializerTo(this);
344     const Init *R = BO->getRHS()->convertInitializerTo(this);
345     if (L == 0 || R == 0) return 0;
346     if (L != BO->getLHS() || R != BO->getRHS())
347       return BinOpInit::get(BinOpInit::CONCAT, L, R, new DagRecTy);
348     return BO;
349   }
350   return 0;
351 }
352
353 RecordRecTy *RecordRecTy::get(Record *R) {
354   return &dynamic_cast<RecordRecTy&>(*R->getDefInit()->getType());
355 }
356
357 std::string RecordRecTy::getAsString() const {
358   return Rec->getName();
359 }
360
361 const Init *RecordRecTy::convertValue(const DefInit *DI) {
362   // Ensure that DI is a subclass of Rec.
363   if (!DI->getDef()->isSubClassOf(Rec))
364     return 0;
365   return DI;
366 }
367
368 const Init *RecordRecTy::convertValue(const TypedInit *TI) {
369   // Ensure that TI is compatible with Rec.
370   if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
371     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
372         RRT->getRecord() == getRecord())
373       return TI;
374   return 0;
375 }
376
377 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
378   if (Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec))
379     return true;
380
381   const std::vector<Record*> &SC = Rec->getSuperClasses();
382   for (unsigned i = 0, e = SC.size(); i != e; ++i)
383     if (RHS->getRecord()->isSubClassOf(SC[i]))
384       return true;
385
386   return false;
387 }
388
389
390 /// resolveTypes - Find a common type that T1 and T2 convert to.
391 /// Return 0 if no such type exists.
392 ///
393 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
394   if (!T1->typeIsConvertibleTo(T2)) {
395     if (!T2->typeIsConvertibleTo(T1)) {
396       // If one is a Record type, check superclasses
397       RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
398       if (RecTy1) {
399         // See if T2 inherits from a type T1 also inherits from
400         const std::vector<Record *> &T1SuperClasses =
401           RecTy1->getRecord()->getSuperClasses();
402         for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
403               iend = T1SuperClasses.end();
404             i != iend;
405             ++i) {
406           RecordRecTy *SuperRecTy1 = RecordRecTy::get(*i);
407           RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
408           if (NewType1 != 0) {
409             if (NewType1 != SuperRecTy1) {
410               delete SuperRecTy1;
411             }
412             return NewType1;
413           }
414         }
415       }
416       RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
417       if (RecTy2) {
418         // See if T1 inherits from a type T2 also inherits from
419         const std::vector<Record *> &T2SuperClasses =
420           RecTy2->getRecord()->getSuperClasses();
421         for (std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
422               iend = T2SuperClasses.end();
423             i != iend;
424             ++i) {
425           RecordRecTy *SuperRecTy2 = RecordRecTy::get(*i);
426           RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
427           if (NewType2 != 0) {
428             if (NewType2 != SuperRecTy2) {
429               delete SuperRecTy2;
430             }
431             return NewType2;
432           }
433         }
434       }
435       return 0;
436     }
437     return T2;
438   }
439   return T1;
440 }
441
442
443 //===----------------------------------------------------------------------===//
444 //    Initializer implementations
445 //===----------------------------------------------------------------------===//
446
447 void Init::dump() const { return print(errs()); }
448
449 const UnsetInit *UnsetInit::get() {
450   static const UnsetInit TheInit;
451   return &TheInit;
452 }
453
454 const BitInit *BitInit::get(bool V) {
455   static const BitInit True(true);
456   static const BitInit False(false);
457
458   return V ? &True : &False;
459 }
460
461 static void
462 ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<const Init *> Range) {
463   ID.AddInteger(Range.size());
464
465   for (ArrayRef<const Init *>::iterator i = Range.begin(),
466          iend = Range.end();
467        i != iend;
468        ++i)
469     ID.AddPointer(*i);
470 }
471
472 const BitsInit *BitsInit::get(ArrayRef<const Init *> Range) {
473   typedef FoldingSet<BitsInit> Pool;
474   static Pool ThePool;  
475
476   FoldingSetNodeID ID;
477   ProfileBitsInit(ID, Range);
478
479   void *IP = 0;
480   if (const BitsInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
481     return I;
482
483   BitsInit *I = new BitsInit(Range);
484   ThePool.InsertNode(I, IP);
485
486   return I;
487 }
488
489 void BitsInit::Profile(FoldingSetNodeID &ID) const {
490   ProfileBitsInit(ID, Bits);
491 }
492
493 const Init *
494 BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
495   SmallVector<const Init *, 16> NewBits(Bits.size());
496
497   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
498     if (Bits[i] >= getNumBits())
499       return 0;
500     NewBits[i] = getBit(Bits[i]);
501   }
502   return BitsInit::get(NewBits);
503 }
504
505 std::string BitsInit::getAsString() const {
506   std::string Result = "{ ";
507   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
508     if (i) Result += ", ";
509     if (const Init *Bit = getBit(e-i-1))
510       Result += Bit->getAsString();
511     else
512       Result += "*";
513   }
514   return Result + " }";
515 }
516
517 // resolveReferences - If there are any field references that refer to fields
518 // that have been filled in, we can propagate the values now.
519 //
520 const Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) const {
521   bool Changed = false;
522   SmallVector<const Init *, 16> NewBits(getNumBits());
523
524   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
525     const Init *B;
526     const Init *CurBit = getBit(i);
527
528     do {
529       B = CurBit;
530       CurBit = CurBit->resolveReferences(R, RV);
531       Changed |= B != CurBit;
532     } while (B != CurBit);
533     NewBits[i] = CurBit;
534   }
535
536   if (Changed)
537     return BitsInit::get(NewBits);
538
539   return this;
540 }
541
542 const IntInit *IntInit::get(int64_t V) {
543   typedef DenseMap<int64_t, IntInit *> Pool;
544   static Pool ThePool;
545
546   IntInit *&I = ThePool[V];
547   if (!I) I = new IntInit(V);
548   return I;
549 }
550
551 std::string IntInit::getAsString() const {
552   return itostr(Value);
553 }
554
555 const Init *
556 IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
557   SmallVector<const Init *, 16> NewBits(Bits.size());
558
559   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
560     if (Bits[i] >= 64)
561       return 0;
562
563     NewBits[i] = BitInit::get(Value & (INT64_C(1) << Bits[i]));
564   }
565   return BitsInit::get(NewBits);
566 }
567
568 const StringInit *StringInit::get(const std::string &V) {
569   typedef StringMap<StringInit *> Pool;
570   static Pool ThePool;
571
572   StringInit *&I = ThePool[V];
573   if (!I) I = new StringInit(V);
574   return I;
575 }
576
577 const CodeInit *CodeInit::get(const std::string &V) {
578   typedef StringMap<CodeInit *> Pool;
579   static Pool ThePool;
580
581   CodeInit *&I = ThePool[V];
582   if (!I) I = new CodeInit(V);
583   return I;
584 }
585
586 const ListInit *ListInit::get(ArrayRef<const Init *> Range, RecTy *EltTy) {
587   return new ListInit(Range, EltTy);
588 }
589
590 const Init *
591 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
592   std::vector<const Init*> Vals;
593   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
594     if (Elements[i] >= getSize())
595       return 0;
596     Vals.push_back(getElement(Elements[i]));
597   }
598   return ListInit::get(Vals, getType());
599 }
600
601 Record *ListInit::getElementAsRecord(unsigned i) const {
602   assert(i < Values.size() && "List element index out of range!");
603   const DefInit *DI = dynamic_cast<const DefInit*>(Values[i]);
604   if (DI == 0) throw "Expected record in list!";
605   return DI->getDef();
606 }
607
608 const Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
609   std::vector<const Init*> Resolved;
610   Resolved.reserve(getSize());
611   bool Changed = false;
612
613   for (unsigned i = 0, e = getSize(); i != e; ++i) {
614     const Init *E;
615     const Init *CurElt = getElement(i);
616
617     do {
618       E = CurElt;
619       CurElt = CurElt->resolveReferences(R, RV);
620       Changed |= E != CurElt;
621     } while (E != CurElt);
622     Resolved.push_back(E);
623   }
624
625   if (Changed)
626     return ListInit::get(Resolved, getType());
627   return this;
628 }
629
630 const Init *ListInit::resolveListElementReference(Record &R,
631                                                   const RecordVal *IRV,
632                                                   unsigned Elt) const {
633   if (Elt >= getSize())
634     return 0;  // Out of range reference.
635   const Init *E = getElement(Elt);
636   // If the element is set to some value, or if we are resolving a reference
637   // to a specific variable and that variable is explicitly unset, then
638   // replace the VarListElementInit with it.
639   if (IRV || !dynamic_cast<const UnsetInit*>(E))
640     return E;
641   return 0;
642 }
643
644 std::string ListInit::getAsString() const {
645   std::string Result = "[";
646   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
647     if (i) Result += ", ";
648     Result += Values[i]->getAsString();
649   }
650   return Result + "]";
651 }
652
653 const Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
654                                         unsigned Bit) const {
655   const Init *Folded = Fold(&R, 0);
656
657   if (Folded != this) {
658     const TypedInit *Typed = dynamic_cast<const TypedInit *>(Folded);
659     if (Typed) {
660       return Typed->resolveBitReference(R, IRV, Bit);
661     }
662   }
663
664   return 0;
665 }
666
667 const Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
668                                                 unsigned Elt) const {
669   const Init *Folded = Fold(&R, 0);
670
671   if (Folded != this) {
672     const TypedInit *Typed = dynamic_cast<const TypedInit *>(Folded);
673     if (Typed) {
674       return Typed->resolveListElementReference(R, IRV, Elt);
675     }
676   }
677
678   return 0;
679 }
680
681 const UnOpInit *UnOpInit::get(UnaryOp opc, const Init *lhs, RecTy *Type) {
682   return new UnOpInit(opc, lhs, Type);
683 }
684
685 const Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
686   switch (getOpcode()) {
687   default: assert(0 && "Unknown unop");
688   case CAST: {
689     if (getType()->getAsString() == "string") {
690       const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
691       if (LHSs) {
692         return LHSs;
693       }
694
695       const DefInit *LHSd = dynamic_cast<const DefInit*>(LHS);
696       if (LHSd) {
697         return StringInit::get(LHSd->getDef()->getName());
698       }
699     } else {
700       const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
701       if (LHSs) {
702         std::string Name = LHSs->getValue();
703
704         // From TGParser::ParseIDValue
705         if (CurRec) {
706           if (const RecordVal *RV = CurRec->getValue(Name)) {
707             if (RV->getType() != getType())
708               throw "type mismatch in cast";
709             return VarInit::get(Name, RV->getType());
710           }
711
712           std::string TemplateArgName = CurRec->getName()+":"+Name;
713           if (CurRec->isTemplateArg(TemplateArgName)) {
714             const RecordVal *RV = CurRec->getValue(TemplateArgName);
715             assert(RV && "Template arg doesn't exist??");
716
717             if (RV->getType() != getType())
718               throw "type mismatch in cast";
719
720             return VarInit::get(TemplateArgName, RV->getType());
721           }
722         }
723
724         if (CurMultiClass) {
725           std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
726           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
727             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
728             assert(RV && "Template arg doesn't exist??");
729
730             if (RV->getType() != getType())
731               throw "type mismatch in cast";
732
733             return VarInit::get(MCName, RV->getType());
734           }
735         }
736
737         if (Record *D = (CurRec->getRecords()).getDef(Name))
738           return DefInit::get(D);
739
740         throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
741       }
742     }
743     break;
744   }
745   case HEAD: {
746     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
747     if (LHSl) {
748       if (LHSl->getSize() == 0) {
749         assert(0 && "Empty list in car");
750         return 0;
751       }
752       return LHSl->getElement(0);
753     }
754     break;
755   }
756   case TAIL: {
757     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
758     if (LHSl) {
759       if (LHSl->getSize() == 0) {
760         assert(0 && "Empty list in cdr");
761         return 0;
762       }
763       // Note the +1.  We can't just pass the result of getValues()
764       // directly.
765       ArrayRef<const Init *>::iterator begin = LHSl->getValues().begin()+1;
766       ArrayRef<const Init *>::iterator end   = LHSl->getValues().end();
767       const ListInit *Result =
768         ListInit::get(ArrayRef<const Init *>(begin, end - begin),
769                       LHSl->getType());
770       return Result;
771     }
772     break;
773   }
774   case EMPTY: {
775     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
776     if (LHSl) {
777       if (LHSl->getSize() == 0) {
778         return IntInit::get(1);
779       } else {
780         return IntInit::get(0);
781       }
782     }
783     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
784     if (LHSs) {
785       if (LHSs->getValue().empty()) {
786         return IntInit::get(1);
787       } else {
788         return IntInit::get(0);
789       }
790     }
791
792     break;
793   }
794   }
795   return this;
796 }
797
798 const Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
799   const Init *lhs = LHS->resolveReferences(R, RV);
800
801   if (LHS != lhs)
802     return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
803   return Fold(&R, 0);
804 }
805
806 std::string UnOpInit::getAsString() const {
807   std::string Result;
808   switch (Opc) {
809   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
810   case HEAD: Result = "!head"; break;
811   case TAIL: Result = "!tail"; break;
812   case EMPTY: Result = "!empty"; break;
813   }
814   return Result + "(" + LHS->getAsString() + ")";
815 }
816
817 const BinOpInit *BinOpInit::get(BinaryOp opc, const Init *lhs,
818                                 const Init *rhs, RecTy *Type) {
819   return new BinOpInit(opc, lhs, rhs, Type);
820 }
821
822 const Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
823   switch (getOpcode()) {
824   default: assert(0 && "Unknown binop");
825   case CONCAT: {
826     const DagInit *LHSs = dynamic_cast<const DagInit*>(LHS);
827     const DagInit *RHSs = dynamic_cast<const DagInit*>(RHS);
828     if (LHSs && RHSs) {
829       const DefInit *LOp = dynamic_cast<const DefInit*>(LHSs->getOperator());
830       const DefInit *ROp = dynamic_cast<const DefInit*>(RHSs->getOperator());
831       if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
832         throw "Concated Dag operators do not match!";
833       std::vector<const Init*> Args;
834       std::vector<std::string> ArgNames;
835       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
836         Args.push_back(LHSs->getArg(i));
837         ArgNames.push_back(LHSs->getArgName(i));
838       }
839       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
840         Args.push_back(RHSs->getArg(i));
841         ArgNames.push_back(RHSs->getArgName(i));
842       }
843       return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
844     }
845     break;
846   }
847   case STRCONCAT: {
848     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
849     const StringInit *RHSs = dynamic_cast<const StringInit*>(RHS);
850     if (LHSs && RHSs)
851       return StringInit::get(LHSs->getValue() + RHSs->getValue());
852     break;
853   }
854   case EQ: {
855     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
856     // to string objects.
857     const IntInit* L =
858       dynamic_cast<const IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
859     const IntInit* R =
860       dynamic_cast<const IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
861
862     if (L && R)
863       return IntInit::get(L->getValue() == R->getValue());
864
865     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
866     const StringInit *RHSs = dynamic_cast<const StringInit*>(RHS);
867
868     // Make sure we've resolved
869     if (LHSs && RHSs)
870       return IntInit::get(LHSs->getValue() == RHSs->getValue());
871
872     break;
873   }
874   case SHL:
875   case SRA:
876   case SRL: {
877     const IntInit *LHSi = dynamic_cast<const IntInit*>(LHS);
878     const IntInit *RHSi = dynamic_cast<const IntInit*>(RHS);
879     if (LHSi && RHSi) {
880       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
881       int64_t Result;
882       switch (getOpcode()) {
883       default: assert(0 && "Bad opcode!");
884       case SHL: Result = LHSv << RHSv; break;
885       case SRA: Result = LHSv >> RHSv; break;
886       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
887       }
888       return IntInit::get(Result);
889     }
890     break;
891   }
892   }
893   return this;
894 }
895
896 const Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
897   const Init *lhs = LHS->resolveReferences(R, RV);
898   const Init *rhs = RHS->resolveReferences(R, RV);
899
900   if (LHS != lhs || RHS != rhs)
901     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
902   return Fold(&R, 0);
903 }
904
905 std::string BinOpInit::getAsString() const {
906   std::string Result;
907   switch (Opc) {
908   case CONCAT: Result = "!con"; break;
909   case SHL: Result = "!shl"; break;
910   case SRA: Result = "!sra"; break;
911   case SRL: Result = "!srl"; break;
912   case EQ: Result = "!eq"; break;
913   case STRCONCAT: Result = "!strconcat"; break;
914   }
915   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
916 }
917
918 const TernOpInit *TernOpInit::get(TernaryOp opc, const Init *lhs,
919                                   const Init *mhs, const Init *rhs,
920                                   RecTy *Type) {
921   return new TernOpInit(opc, lhs, mhs, rhs, Type);
922 }
923
924 static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
925                                  const Init *RHS, RecTy *Type,
926                                  Record *CurRec, MultiClass *CurMultiClass);
927
928 static const Init *EvaluateOperation(const OpInit *RHSo, const Init *LHS,
929                                      const Init *Arg,
930                                      RecTy *Type, Record *CurRec,
931                                      MultiClass *CurMultiClass) {
932   std::vector<const Init *> NewOperands;
933
934   const TypedInit *TArg = dynamic_cast<const TypedInit*>(Arg);
935
936   // If this is a dag, recurse
937   if (TArg && TArg->getType()->getAsString() == "dag") {
938     const Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
939                                  CurRec, CurMultiClass);
940     if (Result != 0) {
941       return Result;
942     } else {
943       return 0;
944     }
945   }
946
947   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
948     const OpInit *RHSoo = dynamic_cast<const OpInit*>(RHSo->getOperand(i));
949
950     if (RHSoo) {
951       const Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
952                                        Type, CurRec, CurMultiClass);
953       if (Result != 0) {
954         NewOperands.push_back(Result);
955       } else {
956         NewOperands.push_back(Arg);
957       }
958     } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
959       NewOperands.push_back(Arg);
960     } else {
961       NewOperands.push_back(RHSo->getOperand(i));
962     }
963   }
964
965   // Now run the operator and use its result as the new leaf
966   const OpInit *NewOp = RHSo->clone(NewOperands);
967   const Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
968   if (NewVal != NewOp)
969     return NewVal;
970
971   return 0;
972 }
973
974 static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
975                                  const Init *RHS, RecTy *Type,
976                                  Record *CurRec,
977                                  MultiClass *CurMultiClass) {
978   const DagInit *MHSd = dynamic_cast<const DagInit*>(MHS);
979   const ListInit *MHSl = dynamic_cast<const ListInit*>(MHS);
980
981   DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
982   ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
983
984   const OpInit *RHSo = dynamic_cast<const OpInit*>(RHS);
985
986   if (!RHSo) {
987     throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
988   }
989
990   const TypedInit *LHSt = dynamic_cast<const TypedInit*>(LHS);
991
992   if (!LHSt) {
993     throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
994   }
995
996   if ((MHSd && DagType) || (MHSl && ListType)) {
997     if (MHSd) {
998       const Init *Val = MHSd->getOperator();
999       const Init *Result = EvaluateOperation(RHSo, LHS, Val,
1000                                        Type, CurRec, CurMultiClass);
1001       if (Result != 0) {
1002         Val = Result;
1003       }
1004
1005       std::vector<std::pair<const Init *, std::string> > args;
1006       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1007         const Init *Arg;
1008         std::string ArgName;
1009         Arg = MHSd->getArg(i);
1010         ArgName = MHSd->getArgName(i);
1011
1012         // Process args
1013         const Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1014                                          CurRec, CurMultiClass);
1015         if (Result != 0) {
1016           Arg = Result;
1017         }
1018
1019         // TODO: Process arg names
1020         args.push_back(std::make_pair(Arg, ArgName));
1021       }
1022
1023       return DagInit::get(Val, "", args);
1024     }
1025     if (MHSl) {
1026       std::vector<const Init *> NewOperands;
1027       std::vector<const Init *> NewList(MHSl->begin(), MHSl->end());
1028
1029       for (std::vector<const Init *>::iterator li = NewList.begin(),
1030              liend = NewList.end();
1031            li != liend;
1032            ++li) {
1033         const Init *Item = *li;
1034         NewOperands.clear();
1035         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1036           // First, replace the foreach variable with the list item
1037           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1038             NewOperands.push_back(Item);
1039           } else {
1040             NewOperands.push_back(RHSo->getOperand(i));
1041           }
1042         }
1043
1044         // Now run the operator and use its result as the new list item
1045         const OpInit *NewOp = RHSo->clone(NewOperands);
1046         const Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1047         if (NewItem != NewOp)
1048           *li = NewItem;
1049       }
1050       return ListInit::get(NewList, MHSl->getType());
1051     }
1052   }
1053   return 0;
1054 }
1055
1056 const Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1057   switch (getOpcode()) {
1058   default: assert(0 && "Unknown binop");
1059   case SUBST: {
1060     const DefInit *LHSd = dynamic_cast<const DefInit*>(LHS);
1061     const VarInit *LHSv = dynamic_cast<const VarInit*>(LHS);
1062     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
1063
1064     const DefInit *MHSd = dynamic_cast<const DefInit*>(MHS);
1065     const VarInit *MHSv = dynamic_cast<const VarInit*>(MHS);
1066     const StringInit *MHSs = dynamic_cast<const StringInit*>(MHS);
1067
1068     const DefInit *RHSd = dynamic_cast<const DefInit*>(RHS);
1069     const VarInit *RHSv = dynamic_cast<const VarInit*>(RHS);
1070     const StringInit *RHSs = dynamic_cast<const StringInit*>(RHS);
1071
1072     if ((LHSd && MHSd && RHSd)
1073         || (LHSv && MHSv && RHSv)
1074         || (LHSs && MHSs && RHSs)) {
1075       if (RHSd) {
1076         Record *Val = RHSd->getDef();
1077         if (LHSd->getAsString() == RHSd->getAsString()) {
1078           Val = MHSd->getDef();
1079         }
1080         return DefInit::get(Val);
1081       }
1082       if (RHSv) {
1083         std::string Val = RHSv->getName();
1084         if (LHSv->getAsString() == RHSv->getAsString()) {
1085           Val = MHSv->getName();
1086         }
1087         return VarInit::get(Val, getType());
1088       }
1089       if (RHSs) {
1090         std::string Val = RHSs->getValue();
1091
1092         std::string::size_type found;
1093         std::string::size_type idx = 0;
1094         do {
1095           found = Val.find(LHSs->getValue(), idx);
1096           if (found != std::string::npos) {
1097             Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1098           }
1099           idx = found +  MHSs->getValue().size();
1100         } while (found != std::string::npos);
1101
1102         return StringInit::get(Val);
1103       }
1104     }
1105     break;
1106   }
1107
1108   case FOREACH: {
1109     const Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1110                                  CurRec, CurMultiClass);
1111     if (Result != 0) {
1112       return Result;
1113     }
1114     break;
1115   }
1116
1117   case IF: {
1118     const IntInit *LHSi = dynamic_cast<const IntInit*>(LHS);
1119     if (const Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1120       LHSi = dynamic_cast<const IntInit*>(I);
1121     if (LHSi) {
1122       if (LHSi->getValue()) {
1123         return MHS;
1124       } else {
1125         return RHS;
1126       }
1127     }
1128     break;
1129   }
1130   }
1131
1132   return this;
1133 }
1134
1135 const Init *TernOpInit::resolveReferences(Record &R,
1136                                           const RecordVal *RV) const {
1137   const Init *lhs = LHS->resolveReferences(R, RV);
1138
1139   if (Opc == IF && lhs != LHS) {
1140     const IntInit *Value = dynamic_cast<const IntInit*>(lhs);
1141     if (const Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1142       Value = dynamic_cast<const IntInit*>(I);
1143     if (Value != 0) {
1144       // Short-circuit
1145       if (Value->getValue()) {
1146         const Init *mhs = MHS->resolveReferences(R, RV);
1147         return (TernOpInit::get(getOpcode(), lhs, mhs,
1148                                 RHS, getType()))->Fold(&R, 0);
1149       } else {
1150         const Init *rhs = RHS->resolveReferences(R, RV);
1151         return (TernOpInit::get(getOpcode(), lhs, MHS,
1152                                 rhs, getType()))->Fold(&R, 0);
1153       }
1154     }
1155   }
1156
1157   const Init *mhs = MHS->resolveReferences(R, RV);
1158   const Init *rhs = RHS->resolveReferences(R, RV);
1159
1160   if (LHS != lhs || MHS != mhs || RHS != rhs)
1161     return (TernOpInit::get(getOpcode(), lhs, mhs, rhs,
1162                             getType()))->Fold(&R, 0);
1163   return Fold(&R, 0);
1164 }
1165
1166 std::string TernOpInit::getAsString() const {
1167   std::string Result;
1168   switch (Opc) {
1169   case SUBST: Result = "!subst"; break;
1170   case FOREACH: Result = "!foreach"; break;
1171   case IF: Result = "!if"; break;
1172  }
1173   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", "
1174     + RHS->getAsString() + ")";
1175 }
1176
1177 RecTy *TypedInit::getFieldType(const std::string &FieldName) const {
1178   RecordRecTy *RecordType = dynamic_cast<RecordRecTy *>(getType());
1179   if (RecordType) {
1180     RecordVal *Field = RecordType->getRecord()->getValue(FieldName);
1181     if (Field) {
1182       return Field->getType();
1183     }
1184   }
1185   return 0;
1186 }
1187
1188 const Init *
1189 TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) const {
1190   BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1191   if (T == 0) return 0;  // Cannot subscript a non-bits variable.
1192   unsigned NumBits = T->getNumBits();
1193
1194   SmallVector<const Init *, 16> NewBits(Bits.size());
1195   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1196     if (Bits[i] >= NumBits)
1197       return 0;
1198
1199     NewBits[i] = VarBitInit::get(this, Bits[i]);
1200   }
1201   return BitsInit::get(NewBits);
1202 }
1203
1204 const Init *
1205 TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
1206   ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1207   if (T == 0) return 0;  // Cannot subscript a non-list variable.
1208
1209   if (Elements.size() == 1)
1210     return VarListElementInit::get(this, Elements[0]);
1211
1212   std::vector<const Init*> ListInits;
1213   ListInits.reserve(Elements.size());
1214   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1215     ListInits.push_back(VarListElementInit::get(this, Elements[i]));
1216   return ListInit::get(ListInits, T);
1217 }
1218
1219
1220 const VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1221   return new VarInit(VN, T);
1222 }
1223
1224 const Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1225                                          unsigned Bit) const {
1226   if (R.isTemplateArg(getName())) return 0;
1227   if (IRV && IRV->getName() != getName()) return 0;
1228
1229   RecordVal *RV = R.getValue(getName());
1230   assert(RV && "Reference to a non-existent variable?");
1231   assert(dynamic_cast<const BitsInit*>(RV->getValue()));
1232   const BitsInit *BI = (const BitsInit*)RV->getValue();
1233
1234   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1235   const Init *B = BI->getBit(Bit);
1236
1237   // If the bit is set to some value, or if we are resolving a reference to a
1238   // specific variable and that variable is explicitly unset, then replace the
1239   // VarBitInit with it.
1240   if (IRV || !dynamic_cast<const UnsetInit*>(B))
1241     return B;
1242   return 0;
1243 }
1244
1245 const Init *VarInit::resolveListElementReference(Record &R,
1246                                                  const RecordVal *IRV,
1247                                                  unsigned Elt) const {
1248   if (R.isTemplateArg(getName())) return 0;
1249   if (IRV && IRV->getName() != getName()) return 0;
1250
1251   RecordVal *RV = R.getValue(getName());
1252   assert(RV && "Reference to a non-existent variable?");
1253   const ListInit *LI = dynamic_cast<const ListInit*>(RV->getValue());
1254   if (!LI) {
1255     const VarInit *VI = dynamic_cast<const VarInit*>(RV->getValue());
1256     assert(VI && "Invalid list element!");
1257     return VarListElementInit::get(VI, Elt);
1258   }
1259
1260   if (Elt >= LI->getSize())
1261     return 0;  // Out of range reference.
1262   const Init *E = LI->getElement(Elt);
1263   // If the element is set to some value, or if we are resolving a reference
1264   // to a specific variable and that variable is explicitly unset, then
1265   // replace the VarListElementInit with it.
1266   if (IRV || !dynamic_cast<const UnsetInit*>(E))
1267     return E;
1268   return 0;
1269 }
1270
1271
1272 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1273   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1274     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1275       return RV->getType();
1276   return 0;
1277 }
1278
1279 const Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1280                                   const std::string &FieldName) const {
1281   if (dynamic_cast<RecordRecTy*>(getType()))
1282     if (const RecordVal *Val = R.getValue(VarName)) {
1283       if (RV != Val && (RV || dynamic_cast<const UnsetInit*>(Val->getValue())))
1284         return 0;
1285       const Init *TheInit = Val->getValue();
1286       assert(TheInit != this && "Infinite loop detected!");
1287       if (const Init *I = TheInit->getFieldInit(R, RV, FieldName))
1288         return I;
1289       else
1290         return 0;
1291     }
1292   return 0;
1293 }
1294
1295 /// resolveReferences - This method is used by classes that refer to other
1296 /// variables which may not be defined at the time the expression is formed.
1297 /// If a value is set for the variable later, this method will be called on
1298 /// users of the value to allow the value to propagate out.
1299 ///
1300 const Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1301   if (RecordVal *Val = R.getValue(VarName))
1302     if (RV == Val || (RV == 0 && !dynamic_cast<const UnsetInit*>(Val->getValue())))
1303       return Val->getValue();
1304   return this;
1305 }
1306
1307 const VarBitInit *VarBitInit::get(const TypedInit *T, unsigned B) {
1308   return new VarBitInit(T, B);
1309 }
1310
1311 std::string VarBitInit::getAsString() const {
1312    return TI->getAsString() + "{" + utostr(Bit) + "}";
1313 }
1314
1315 const Init *VarBitInit::resolveReferences(Record &R,
1316                                           const RecordVal *RV) const {
1317   if (const Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1318     return I;
1319   return this;
1320 }
1321
1322 const VarListElementInit *VarListElementInit::get(const TypedInit *T,
1323                                                   unsigned E) {
1324   return new VarListElementInit(T, E);
1325 }
1326
1327 std::string VarListElementInit::getAsString() const {
1328   return TI->getAsString() + "[" + utostr(Element) + "]";
1329 }
1330
1331 const Init *VarListElementInit::resolveReferences(Record &R,
1332                                                   const RecordVal *RV) const {
1333   if (const Init *I = getVariable()->resolveListElementReference(R, RV,
1334                                                            getElementNum()))
1335     return I;
1336   return this;
1337 }
1338
1339 const Init *VarListElementInit::resolveBitReference(Record &R,
1340                                                     const RecordVal *RV,
1341                                                     unsigned Bit) const {
1342   // FIXME: This should be implemented, to support references like:
1343   // bit B = AA[0]{1};
1344   return 0;
1345 }
1346
1347 const Init *VarListElementInit::
1348 resolveListElementReference(Record &R, const RecordVal *RV,
1349                             unsigned Elt) const {
1350   // FIXME: This should be implemented, to support references like:
1351   // int B = AA[0][1];
1352   return 0;
1353 }
1354
1355 const DefInit *DefInit::get(Record *R) {
1356   return R->getDefInit();
1357 }
1358
1359 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1360   if (const RecordVal *RV = Def->getValue(FieldName))
1361     return RV->getType();
1362   return 0;
1363 }
1364
1365 const Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1366                                   const std::string &FieldName) const {
1367   return Def->getValue(FieldName)->getValue();
1368 }
1369
1370
1371 std::string DefInit::getAsString() const {
1372   return Def->getName();
1373 }
1374
1375 const FieldInit *FieldInit::get(const Init *R, const std::string &FN) {
1376   return new FieldInit(R, FN);
1377 }
1378
1379 const Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1380                                            unsigned Bit) const {
1381   if (const Init *BitsVal = Rec->getFieldInit(R, RV, FieldName))
1382     if (const BitsInit *BI = dynamic_cast<const BitsInit*>(BitsVal)) {
1383       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1384       const Init *B = BI->getBit(Bit);
1385
1386       if (dynamic_cast<const BitInit*>(B))  // If the bit is set.
1387         return B;                     // Replace the VarBitInit with it.
1388     }
1389   return 0;
1390 }
1391
1392 const Init *FieldInit::resolveListElementReference(Record &R,
1393                                                    const RecordVal *RV,
1394                                                    unsigned Elt) const {
1395   if (const Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1396     if (const ListInit *LI = dynamic_cast<const ListInit*>(ListVal)) {
1397       if (Elt >= LI->getSize()) return 0;
1398       const Init *E = LI->getElement(Elt);
1399
1400       // If the element is set to some value, or if we are resolving a
1401       // reference to a specific variable and that variable is explicitly
1402       // unset, then replace the VarListElementInit with it.
1403       if (RV || !dynamic_cast<const UnsetInit*>(E))
1404         return E;
1405     }
1406   return 0;
1407 }
1408
1409 const Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1410   const Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1411
1412   const Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1413   if (BitsVal) {
1414     const Init *BVR = BitsVal->resolveReferences(R, RV);
1415     return BVR->isComplete() ? BVR : this;
1416   }
1417
1418   if (NewRec != Rec) {
1419     return FieldInit::get(NewRec, FieldName);
1420   }
1421   return this;
1422 }
1423
1424 const DagInit *
1425 DagInit::get(const Init *V, const std::string &VN,
1426              const std::vector<std::pair<const Init*, std::string> > &args) {
1427   typedef std::pair<const Init*, std::string> PairType;
1428
1429   std::vector<const Init *> Args;
1430   std::vector<std::string> Names;
1431
1432   for (std::vector<PairType>::const_iterator i = args.begin(),
1433          iend = args.end();
1434        i != iend;
1435        ++i) {
1436     Args.push_back(i->first);
1437     Names.push_back(i->second);
1438   }
1439
1440   return DagInit::get(V, VN, Args, Names);
1441 }
1442
1443 const DagInit *
1444 DagInit::get(const Init *V, const std::string &VN,
1445              const std::vector<const Init*> &args,
1446              const std::vector<std::string> &argNames) {
1447   return new DagInit(V, VN, args, argNames);
1448 }
1449
1450 const Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1451   std::vector<const Init*> NewArgs;
1452   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1453     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1454
1455   const Init *Op = Val->resolveReferences(R, RV);
1456
1457   if (Args != NewArgs || Op != Val)
1458     return DagInit::get(Op, ValName, NewArgs, ArgNames);
1459
1460   return this;
1461 }
1462
1463
1464 std::string DagInit::getAsString() const {
1465   std::string Result = "(" + Val->getAsString();
1466   if (!ValName.empty())
1467     Result += ":" + ValName;
1468   if (Args.size()) {
1469     Result += " " + Args[0]->getAsString();
1470     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1471     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1472       Result += ", " + Args[i]->getAsString();
1473       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1474     }
1475   }
1476   return Result + ")";
1477 }
1478
1479
1480 //===----------------------------------------------------------------------===//
1481 //    Other implementations
1482 //===----------------------------------------------------------------------===//
1483
1484 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1485   : Name(N), Ty(T), Prefix(P) {
1486   Value = Ty->convertValue(UnsetInit::get());
1487   assert(Value && "Cannot create unset value for current type!");
1488 }
1489
1490 void RecordVal::dump() const { errs() << *this; }
1491
1492 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1493   if (getPrefix()) OS << "field ";
1494   OS << *getType() << " " << getName();
1495
1496   if (getValue())
1497     OS << " = " << *getValue();
1498
1499   if (PrintSem) OS << ";\n";
1500 }
1501
1502 unsigned Record::LastID = 0;
1503
1504 DefInit *Record::getDefInit() {
1505   if (!TheInit)
1506     TheInit = new DefInit(this, new RecordRecTy(this));
1507   return TheInit;
1508 }
1509
1510 void Record::setName(const std::string &Name) {
1511   if (TrackedRecords.getDef(getName()) == this) {
1512     TrackedRecords.removeDef(getName());
1513     this->Name = Name;
1514     TrackedRecords.addDef(this);
1515   } else {
1516     TrackedRecords.removeClass(getName());
1517     this->Name = Name;
1518     TrackedRecords.addClass(this);
1519   }
1520 }
1521
1522 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1523 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1524 /// references.
1525 void Record::resolveReferencesTo(const RecordVal *RV) {
1526   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1527     if (const Init *V = Values[i].getValue())
1528       Values[i].setValue(V->resolveReferences(*this, RV));
1529   }
1530 }
1531
1532 void Record::dump() const { errs() << *this; }
1533
1534 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1535   OS << R.getName();
1536
1537   const std::vector<std::string> &TArgs = R.getTemplateArgs();
1538   if (!TArgs.empty()) {
1539     OS << "<";
1540     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1541       if (i) OS << ", ";
1542       const RecordVal *RV = R.getValue(TArgs[i]);
1543       assert(RV && "Template argument record not found??");
1544       RV->print(OS, false);
1545     }
1546     OS << ">";
1547   }
1548
1549   OS << " {";
1550   const std::vector<Record*> &SC = R.getSuperClasses();
1551   if (!SC.empty()) {
1552     OS << "\t//";
1553     for (unsigned i = 0, e = SC.size(); i != e; ++i)
1554       OS << " " << SC[i]->getName();
1555   }
1556   OS << "\n";
1557
1558   const std::vector<RecordVal> &Vals = R.getValues();
1559   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1560     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1561       OS << Vals[i];
1562   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1563     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1564       OS << Vals[i];
1565
1566   return OS << "}\n";
1567 }
1568
1569 /// getValueInit - Return the initializer for a value with the specified name,
1570 /// or throw an exception if the field does not exist.
1571 ///
1572 const Init *Record::getValueInit(StringRef FieldName) const {
1573   const RecordVal *R = getValue(FieldName);
1574   if (R == 0 || R->getValue() == 0)
1575     throw "Record `" + getName() + "' does not have a field named `" +
1576       FieldName.str() + "'!\n";
1577   return R->getValue();
1578 }
1579
1580
1581 /// getValueAsString - This method looks up the specified field and returns its
1582 /// value as a string, throwing an exception if the field does not exist or if
1583 /// the value is not a string.
1584 ///
1585 std::string Record::getValueAsString(StringRef FieldName) const {
1586   const RecordVal *R = getValue(FieldName);
1587   if (R == 0 || R->getValue() == 0)
1588     throw "Record `" + getName() + "' does not have a field named `" +
1589           FieldName.str() + "'!\n";
1590
1591   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
1592     return SI->getValue();
1593   throw "Record `" + getName() + "', field `" + FieldName.str() +
1594         "' does not have a string initializer!";
1595 }
1596
1597 /// getValueAsBitsInit - This method looks up the specified field and returns
1598 /// its value as a BitsInit, throwing an exception if the field does not exist
1599 /// or if the value is not the right type.
1600 ///
1601 const BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1602   const RecordVal *R = getValue(FieldName);
1603   if (R == 0 || R->getValue() == 0)
1604     throw "Record `" + getName() + "' does not have a field named `" +
1605           FieldName.str() + "'!\n";
1606
1607   if (const BitsInit *BI = dynamic_cast<const BitsInit*>(R->getValue()))
1608     return BI;
1609   throw "Record `" + getName() + "', field `" + FieldName.str() +
1610         "' does not have a BitsInit initializer!";
1611 }
1612
1613 /// getValueAsListInit - This method looks up the specified field and returns
1614 /// its value as a ListInit, throwing an exception if the field does not exist
1615 /// or if the value is not the right type.
1616 ///
1617 const ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1618   const RecordVal *R = getValue(FieldName);
1619   if (R == 0 || R->getValue() == 0)
1620     throw "Record `" + getName() + "' does not have a field named `" +
1621           FieldName.str() + "'!\n";
1622
1623   if (const ListInit *LI = dynamic_cast<const ListInit*>(R->getValue()))
1624     return LI;
1625   throw "Record `" + getName() + "', field `" + FieldName.str() +
1626         "' does not have a list initializer!";
1627 }
1628
1629 /// getValueAsListOfDefs - This method looks up the specified field and returns
1630 /// its value as a vector of records, throwing an exception if the field does
1631 /// not exist or if the value is not the right type.
1632 ///
1633 std::vector<Record*>
1634 Record::getValueAsListOfDefs(StringRef FieldName) const {
1635   const ListInit *List = getValueAsListInit(FieldName);
1636   std::vector<Record*> Defs;
1637   for (unsigned i = 0; i < List->getSize(); i++) {
1638     if (const DefInit *DI = dynamic_cast<const DefInit*>(List->getElement(i))) {
1639       Defs.push_back(DI->getDef());
1640     } else {
1641       throw "Record `" + getName() + "', field `" + FieldName.str() +
1642             "' list is not entirely DefInit!";
1643     }
1644   }
1645   return Defs;
1646 }
1647
1648 /// getValueAsInt - This method looks up the specified field and returns its
1649 /// value as an int64_t, throwing an exception if the field does not exist or if
1650 /// the value is not the right type.
1651 ///
1652 int64_t Record::getValueAsInt(StringRef FieldName) const {
1653   const RecordVal *R = getValue(FieldName);
1654   if (R == 0 || R->getValue() == 0)
1655     throw "Record `" + getName() + "' does not have a field named `" +
1656           FieldName.str() + "'!\n";
1657
1658   if (const IntInit *II = dynamic_cast<const IntInit*>(R->getValue()))
1659     return II->getValue();
1660   throw "Record `" + getName() + "', field `" + FieldName.str() +
1661         "' does not have an int initializer!";
1662 }
1663
1664 /// getValueAsListOfInts - This method looks up the specified field and returns
1665 /// its value as a vector of integers, throwing an exception if the field does
1666 /// not exist or if the value is not the right type.
1667 ///
1668 std::vector<int64_t>
1669 Record::getValueAsListOfInts(StringRef FieldName) const {
1670   const ListInit *List = getValueAsListInit(FieldName);
1671   std::vector<int64_t> Ints;
1672   for (unsigned i = 0; i < List->getSize(); i++) {
1673     if (const IntInit *II = dynamic_cast<const IntInit*>(List->getElement(i))) {
1674       Ints.push_back(II->getValue());
1675     } else {
1676       throw "Record `" + getName() + "', field `" + FieldName.str() +
1677             "' does not have a list of ints initializer!";
1678     }
1679   }
1680   return Ints;
1681 }
1682
1683 /// getValueAsListOfStrings - This method looks up the specified field and
1684 /// returns its value as a vector of strings, throwing an exception if the
1685 /// field does not exist or if the value is not the right type.
1686 ///
1687 std::vector<std::string>
1688 Record::getValueAsListOfStrings(StringRef FieldName) const {
1689   const ListInit *List = getValueAsListInit(FieldName);
1690   std::vector<std::string> Strings;
1691   for (unsigned i = 0; i < List->getSize(); i++) {
1692     if (const StringInit *II = dynamic_cast<const StringInit*>(List->getElement(i))) {
1693       Strings.push_back(II->getValue());
1694     } else {
1695       throw "Record `" + getName() + "', field `" + FieldName.str() +
1696             "' does not have a list of strings initializer!";
1697     }
1698   }
1699   return Strings;
1700 }
1701
1702 /// getValueAsDef - This method looks up the specified field and returns its
1703 /// value as a Record, throwing an exception if the field does not exist or if
1704 /// the value is not the right type.
1705 ///
1706 Record *Record::getValueAsDef(StringRef FieldName) const {
1707   const RecordVal *R = getValue(FieldName);
1708   if (R == 0 || R->getValue() == 0)
1709     throw "Record `" + getName() + "' does not have a field named `" +
1710       FieldName.str() + "'!\n";
1711
1712   if (const DefInit *DI = dynamic_cast<const DefInit*>(R->getValue()))
1713     return DI->getDef();
1714   throw "Record `" + getName() + "', field `" + FieldName.str() +
1715         "' does not have a def initializer!";
1716 }
1717
1718 /// getValueAsBit - This method looks up the specified field and returns its
1719 /// value as a bit, throwing an exception if the field does not exist or if
1720 /// the value is not the right type.
1721 ///
1722 bool Record::getValueAsBit(StringRef FieldName) const {
1723   const RecordVal *R = getValue(FieldName);
1724   if (R == 0 || R->getValue() == 0)
1725     throw "Record `" + getName() + "' does not have a field named `" +
1726       FieldName.str() + "'!\n";
1727
1728   if (const BitInit *BI = dynamic_cast<const BitInit*>(R->getValue()))
1729     return BI->getValue();
1730   throw "Record `" + getName() + "', field `" + FieldName.str() +
1731         "' does not have a bit initializer!";
1732 }
1733
1734 /// getValueAsDag - This method looks up the specified field and returns its
1735 /// value as an Dag, throwing an exception if the field does not exist or if
1736 /// the value is not the right type.
1737 ///
1738 const DagInit *Record::getValueAsDag(StringRef FieldName) const {
1739   const RecordVal *R = getValue(FieldName);
1740   if (R == 0 || R->getValue() == 0)
1741     throw "Record `" + getName() + "' does not have a field named `" +
1742       FieldName.str() + "'!\n";
1743
1744   if (const DagInit *DI = dynamic_cast<const DagInit*>(R->getValue()))
1745     return DI;
1746   throw "Record `" + getName() + "', field `" + FieldName.str() +
1747         "' does not have a dag initializer!";
1748 }
1749
1750 std::string Record::getValueAsCode(StringRef FieldName) const {
1751   const RecordVal *R = getValue(FieldName);
1752   if (R == 0 || R->getValue() == 0)
1753     throw "Record `" + getName() + "' does not have a field named `" +
1754       FieldName.str() + "'!\n";
1755
1756   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
1757     return CI->getValue();
1758   throw "Record `" + getName() + "', field `" + FieldName.str() +
1759     "' does not have a code initializer!";
1760 }
1761
1762
1763 void MultiClass::dump() const {
1764   errs() << "Record:\n";
1765   Rec.dump();
1766
1767   errs() << "Defs:\n";
1768   for (RecordVector::const_iterator r = DefPrototypes.begin(),
1769          rend = DefPrototypes.end();
1770        r != rend;
1771        ++r) {
1772     (*r)->dump();
1773   }
1774 }
1775
1776
1777 void RecordKeeper::dump() const { errs() << *this; }
1778
1779 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1780   OS << "------------- Classes -----------------\n";
1781   const std::map<std::string, Record*> &Classes = RK.getClasses();
1782   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1783          E = Classes.end(); I != E; ++I)
1784     OS << "class " << *I->second;
1785
1786   OS << "------------- Defs -----------------\n";
1787   const std::map<std::string, Record*> &Defs = RK.getDefs();
1788   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1789          E = Defs.end(); I != E; ++I)
1790     OS << "def " << *I->second;
1791   return OS;
1792 }
1793
1794
1795 /// getAllDerivedDefinitions - This method returns all concrete definitions
1796 /// that derive from the specified class name.  If a class with the specified
1797 /// name does not exist, an error is printed and true is returned.
1798 std::vector<Record*>
1799 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1800   Record *Class = getClass(ClassName);
1801   if (!Class)
1802     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1803
1804   std::vector<Record*> Defs;
1805   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1806          E = getDefs().end(); I != E; ++I)
1807     if (I->second->isSubClassOf(Class))
1808       Defs.push_back(I->second);
1809
1810   return Defs;
1811 }
1812