[AVX] Make TernOpInit Unique
[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 static void ProfileListInit(FoldingSetNodeID &ID,
587                             ArrayRef<const Init *> Range,
588                             RecTy *EltTy) {
589   ID.AddInteger(Range.size());
590   ID.AddPointer(EltTy);
591
592   for (ArrayRef<const Init *>::iterator i = Range.begin(),
593          iend = Range.end();
594        i != iend;
595        ++i)
596     ID.AddPointer(*i);
597 }
598
599 const ListInit *ListInit::get(ArrayRef<const Init *> Range, RecTy *EltTy) {
600   typedef FoldingSet<ListInit> Pool;
601   static Pool ThePool;
602
603   // Just use the FoldingSetNodeID to compute a hash.  Use a DenseMap
604   // for actual storage.
605   FoldingSetNodeID ID;
606   ProfileListInit(ID, Range, EltTy);
607
608   void *IP = 0;
609   if (const ListInit *I = ThePool.FindNodeOrInsertPos(ID, IP))
610     return I;
611
612   ListInit *I = new ListInit(Range, EltTy);
613   ThePool.InsertNode(I, IP);
614   return I;
615 }
616
617 void ListInit::Profile(FoldingSetNodeID &ID) const {
618   ListRecTy *ListType = dynamic_cast<ListRecTy *>(getType());
619   assert(ListType && "Bad type for ListInit!");
620   RecTy *EltTy = ListType->getElementType();
621
622   ProfileListInit(ID, Values, EltTy);
623 }
624
625 const Init *
626 ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) const {
627   std::vector<const Init*> Vals;
628   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
629     if (Elements[i] >= getSize())
630       return 0;
631     Vals.push_back(getElement(Elements[i]));
632   }
633   return ListInit::get(Vals, getType());
634 }
635
636 Record *ListInit::getElementAsRecord(unsigned i) const {
637   assert(i < Values.size() && "List element index out of range!");
638   const DefInit *DI = dynamic_cast<const DefInit*>(Values[i]);
639   if (DI == 0) throw "Expected record in list!";
640   return DI->getDef();
641 }
642
643 const Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) const {
644   std::vector<const Init*> Resolved;
645   Resolved.reserve(getSize());
646   bool Changed = false;
647
648   for (unsigned i = 0, e = getSize(); i != e; ++i) {
649     const Init *E;
650     const Init *CurElt = getElement(i);
651
652     do {
653       E = CurElt;
654       CurElt = CurElt->resolveReferences(R, RV);
655       Changed |= E != CurElt;
656     } while (E != CurElt);
657     Resolved.push_back(E);
658   }
659
660   if (Changed)
661     return ListInit::get(Resolved, getType());
662   return this;
663 }
664
665 const Init *ListInit::resolveListElementReference(Record &R,
666                                                   const RecordVal *IRV,
667                                                   unsigned Elt) const {
668   if (Elt >= getSize())
669     return 0;  // Out of range reference.
670   const Init *E = getElement(Elt);
671   // If the element is set to some value, or if we are resolving a reference
672   // to a specific variable and that variable is explicitly unset, then
673   // replace the VarListElementInit with it.
674   if (IRV || !dynamic_cast<const UnsetInit*>(E))
675     return E;
676   return 0;
677 }
678
679 std::string ListInit::getAsString() const {
680   std::string Result = "[";
681   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
682     if (i) Result += ", ";
683     Result += Values[i]->getAsString();
684   }
685   return Result + "]";
686 }
687
688 const Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
689                                         unsigned Bit) const {
690   const Init *Folded = Fold(&R, 0);
691
692   if (Folded != this) {
693     const TypedInit *Typed = dynamic_cast<const TypedInit *>(Folded);
694     if (Typed) {
695       return Typed->resolveBitReference(R, IRV, Bit);
696     }
697   }
698
699   return 0;
700 }
701
702 const Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
703                                                 unsigned Elt) const {
704   const Init *Folded = Fold(&R, 0);
705
706   if (Folded != this) {
707     const TypedInit *Typed = dynamic_cast<const TypedInit *>(Folded);
708     if (Typed) {
709       return Typed->resolveListElementReference(R, IRV, Elt);
710     }
711   }
712
713   return 0;
714 }
715
716 const UnOpInit *UnOpInit::get(UnaryOp opc, const Init *lhs, RecTy *Type) {
717   typedef std::pair<std::pair<unsigned, const Init *>, RecTy *> Key;
718
719   typedef DenseMap<Key, UnOpInit *> Pool;
720   static Pool ThePool;  
721
722   Key TheKey(std::make_pair(std::make_pair(opc, lhs), Type));
723
724   UnOpInit *&I = ThePool[TheKey];
725   if (!I) I = new UnOpInit(opc, lhs, Type);
726   return I;
727 }
728
729 const Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
730   switch (getOpcode()) {
731   default: assert(0 && "Unknown unop");
732   case CAST: {
733     if (getType()->getAsString() == "string") {
734       const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
735       if (LHSs) {
736         return LHSs;
737       }
738
739       const DefInit *LHSd = dynamic_cast<const DefInit*>(LHS);
740       if (LHSd) {
741         return StringInit::get(LHSd->getDef()->getName());
742       }
743     } else {
744       const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
745       if (LHSs) {
746         std::string Name = LHSs->getValue();
747
748         // From TGParser::ParseIDValue
749         if (CurRec) {
750           if (const RecordVal *RV = CurRec->getValue(Name)) {
751             if (RV->getType() != getType())
752               throw "type mismatch in cast";
753             return VarInit::get(Name, RV->getType());
754           }
755
756           std::string TemplateArgName = CurRec->getName()+":"+Name;
757           if (CurRec->isTemplateArg(TemplateArgName)) {
758             const RecordVal *RV = CurRec->getValue(TemplateArgName);
759             assert(RV && "Template arg doesn't exist??");
760
761             if (RV->getType() != getType())
762               throw "type mismatch in cast";
763
764             return VarInit::get(TemplateArgName, RV->getType());
765           }
766         }
767
768         if (CurMultiClass) {
769           std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
770           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
771             const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
772             assert(RV && "Template arg doesn't exist??");
773
774             if (RV->getType() != getType())
775               throw "type mismatch in cast";
776
777             return VarInit::get(MCName, RV->getType());
778           }
779         }
780
781         if (Record *D = (CurRec->getRecords()).getDef(Name))
782           return DefInit::get(D);
783
784         throw TGError(CurRec->getLoc(), "Undefined reference:'" + Name + "'\n");
785       }
786     }
787     break;
788   }
789   case HEAD: {
790     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
791     if (LHSl) {
792       if (LHSl->getSize() == 0) {
793         assert(0 && "Empty list in car");
794         return 0;
795       }
796       return LHSl->getElement(0);
797     }
798     break;
799   }
800   case TAIL: {
801     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
802     if (LHSl) {
803       if (LHSl->getSize() == 0) {
804         assert(0 && "Empty list in cdr");
805         return 0;
806       }
807       // Note the +1.  We can't just pass the result of getValues()
808       // directly.
809       ArrayRef<const Init *>::iterator begin = LHSl->getValues().begin()+1;
810       ArrayRef<const Init *>::iterator end   = LHSl->getValues().end();
811       const ListInit *Result =
812         ListInit::get(ArrayRef<const Init *>(begin, end - begin),
813                       LHSl->getType());
814       return Result;
815     }
816     break;
817   }
818   case EMPTY: {
819     const ListInit *LHSl = dynamic_cast<const ListInit*>(LHS);
820     if (LHSl) {
821       if (LHSl->getSize() == 0) {
822         return IntInit::get(1);
823       } else {
824         return IntInit::get(0);
825       }
826     }
827     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
828     if (LHSs) {
829       if (LHSs->getValue().empty()) {
830         return IntInit::get(1);
831       } else {
832         return IntInit::get(0);
833       }
834     }
835
836     break;
837   }
838   }
839   return this;
840 }
841
842 const Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
843   const Init *lhs = LHS->resolveReferences(R, RV);
844
845   if (LHS != lhs)
846     return (UnOpInit::get(getOpcode(), lhs, getType()))->Fold(&R, 0);
847   return Fold(&R, 0);
848 }
849
850 std::string UnOpInit::getAsString() const {
851   std::string Result;
852   switch (Opc) {
853   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
854   case HEAD: Result = "!head"; break;
855   case TAIL: Result = "!tail"; break;
856   case EMPTY: Result = "!empty"; break;
857   }
858   return Result + "(" + LHS->getAsString() + ")";
859 }
860
861 const BinOpInit *BinOpInit::get(BinaryOp opc, const Init *lhs,
862                                 const Init *rhs, RecTy *Type) {
863   typedef std::pair<
864     std::pair<std::pair<unsigned, const Init *>, const Init *>,
865     RecTy *
866     > Key;
867
868   typedef DenseMap<Key, BinOpInit *> Pool;
869   static Pool ThePool;  
870
871   Key TheKey(std::make_pair(std::make_pair(std::make_pair(opc, lhs), rhs),
872                             Type));
873
874   BinOpInit *&I = ThePool[TheKey];
875   if (!I) I = new BinOpInit(opc, lhs, rhs, Type);
876   return I;
877 }
878
879 const Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
880   switch (getOpcode()) {
881   default: assert(0 && "Unknown binop");
882   case CONCAT: {
883     const DagInit *LHSs = dynamic_cast<const DagInit*>(LHS);
884     const DagInit *RHSs = dynamic_cast<const DagInit*>(RHS);
885     if (LHSs && RHSs) {
886       const DefInit *LOp = dynamic_cast<const DefInit*>(LHSs->getOperator());
887       const DefInit *ROp = dynamic_cast<const DefInit*>(RHSs->getOperator());
888       if (LOp == 0 || ROp == 0 || LOp->getDef() != ROp->getDef())
889         throw "Concated Dag operators do not match!";
890       std::vector<const Init*> Args;
891       std::vector<std::string> ArgNames;
892       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
893         Args.push_back(LHSs->getArg(i));
894         ArgNames.push_back(LHSs->getArgName(i));
895       }
896       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
897         Args.push_back(RHSs->getArg(i));
898         ArgNames.push_back(RHSs->getArgName(i));
899       }
900       return DagInit::get(LHSs->getOperator(), "", Args, ArgNames);
901     }
902     break;
903   }
904   case STRCONCAT: {
905     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
906     const StringInit *RHSs = dynamic_cast<const StringInit*>(RHS);
907     if (LHSs && RHSs)
908       return StringInit::get(LHSs->getValue() + RHSs->getValue());
909     break;
910   }
911   case EQ: {
912     // try to fold eq comparison for 'bit' and 'int', otherwise fallback
913     // to string objects.
914     const IntInit* L =
915       dynamic_cast<const IntInit*>(LHS->convertInitializerTo(IntRecTy::get()));
916     const IntInit* R =
917       dynamic_cast<const IntInit*>(RHS->convertInitializerTo(IntRecTy::get()));
918
919     if (L && R)
920       return IntInit::get(L->getValue() == R->getValue());
921
922     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
923     const StringInit *RHSs = dynamic_cast<const StringInit*>(RHS);
924
925     // Make sure we've resolved
926     if (LHSs && RHSs)
927       return IntInit::get(LHSs->getValue() == RHSs->getValue());
928
929     break;
930   }
931   case SHL:
932   case SRA:
933   case SRL: {
934     const IntInit *LHSi = dynamic_cast<const IntInit*>(LHS);
935     const IntInit *RHSi = dynamic_cast<const IntInit*>(RHS);
936     if (LHSi && RHSi) {
937       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
938       int64_t Result;
939       switch (getOpcode()) {
940       default: assert(0 && "Bad opcode!");
941       case SHL: Result = LHSv << RHSv; break;
942       case SRA: Result = LHSv >> RHSv; break;
943       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
944       }
945       return IntInit::get(Result);
946     }
947     break;
948   }
949   }
950   return this;
951 }
952
953 const Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) const {
954   const Init *lhs = LHS->resolveReferences(R, RV);
955   const Init *rhs = RHS->resolveReferences(R, RV);
956
957   if (LHS != lhs || RHS != rhs)
958     return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
959   return Fold(&R, 0);
960 }
961
962 std::string BinOpInit::getAsString() const {
963   std::string Result;
964   switch (Opc) {
965   case CONCAT: Result = "!con"; break;
966   case SHL: Result = "!shl"; break;
967   case SRA: Result = "!sra"; break;
968   case SRL: Result = "!srl"; break;
969   case EQ: Result = "!eq"; break;
970   case STRCONCAT: Result = "!strconcat"; break;
971   }
972   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
973 }
974
975 const TernOpInit *TernOpInit::get(TernaryOp opc, const Init *lhs,
976                                   const Init *mhs, const Init *rhs,
977                                   RecTy *Type) {
978   typedef std::pair<
979     std::pair<
980       std::pair<std::pair<unsigned, RecTy *>, const Init *>,
981       const Init *
982       >,
983     const Init *
984     > Key;
985
986   typedef DenseMap<Key, TernOpInit *> Pool;
987   static Pool ThePool;
988
989   Key TheKey(std::make_pair(std::make_pair(std::make_pair(std::make_pair(opc,
990                                                                          Type),
991                                                           lhs),
992                                            mhs),
993                             rhs));
994
995   TernOpInit *&I = ThePool[TheKey];
996   if (!I) I = new TernOpInit(opc, lhs, mhs, rhs, Type);
997   return I;
998 }
999
1000 static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
1001                                  const Init *RHS, RecTy *Type,
1002                                  Record *CurRec, MultiClass *CurMultiClass);
1003
1004 static const Init *EvaluateOperation(const OpInit *RHSo, const Init *LHS,
1005                                      const Init *Arg,
1006                                      RecTy *Type, Record *CurRec,
1007                                      MultiClass *CurMultiClass) {
1008   std::vector<const Init *> NewOperands;
1009
1010   const TypedInit *TArg = dynamic_cast<const TypedInit*>(Arg);
1011
1012   // If this is a dag, recurse
1013   if (TArg && TArg->getType()->getAsString() == "dag") {
1014     const Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
1015                                  CurRec, CurMultiClass);
1016     if (Result != 0) {
1017       return Result;
1018     } else {
1019       return 0;
1020     }
1021   }
1022
1023   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
1024     const OpInit *RHSoo = dynamic_cast<const OpInit*>(RHSo->getOperand(i));
1025
1026     if (RHSoo) {
1027       const Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
1028                                        Type, CurRec, CurMultiClass);
1029       if (Result != 0) {
1030         NewOperands.push_back(Result);
1031       } else {
1032         NewOperands.push_back(Arg);
1033       }
1034     } else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1035       NewOperands.push_back(Arg);
1036     } else {
1037       NewOperands.push_back(RHSo->getOperand(i));
1038     }
1039   }
1040
1041   // Now run the operator and use its result as the new leaf
1042   const OpInit *NewOp = RHSo->clone(NewOperands);
1043   const Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
1044   if (NewVal != NewOp)
1045     return NewVal;
1046
1047   return 0;
1048 }
1049
1050 static const Init *ForeachHelper(const Init *LHS, const Init *MHS,
1051                                  const Init *RHS, RecTy *Type,
1052                                  Record *CurRec,
1053                                  MultiClass *CurMultiClass) {
1054   const DagInit *MHSd = dynamic_cast<const DagInit*>(MHS);
1055   const ListInit *MHSl = dynamic_cast<const ListInit*>(MHS);
1056
1057   DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
1058   ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
1059
1060   const OpInit *RHSo = dynamic_cast<const OpInit*>(RHS);
1061
1062   if (!RHSo) {
1063     throw TGError(CurRec->getLoc(), "!foreach requires an operator\n");
1064   }
1065
1066   const TypedInit *LHSt = dynamic_cast<const TypedInit*>(LHS);
1067
1068   if (!LHSt) {
1069     throw TGError(CurRec->getLoc(), "!foreach requires typed variable\n");
1070   }
1071
1072   if ((MHSd && DagType) || (MHSl && ListType)) {
1073     if (MHSd) {
1074       const Init *Val = MHSd->getOperator();
1075       const Init *Result = EvaluateOperation(RHSo, LHS, Val,
1076                                        Type, CurRec, CurMultiClass);
1077       if (Result != 0) {
1078         Val = Result;
1079       }
1080
1081       std::vector<std::pair<const Init *, std::string> > args;
1082       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
1083         const Init *Arg;
1084         std::string ArgName;
1085         Arg = MHSd->getArg(i);
1086         ArgName = MHSd->getArgName(i);
1087
1088         // Process args
1089         const Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
1090                                          CurRec, CurMultiClass);
1091         if (Result != 0) {
1092           Arg = Result;
1093         }
1094
1095         // TODO: Process arg names
1096         args.push_back(std::make_pair(Arg, ArgName));
1097       }
1098
1099       return DagInit::get(Val, "", args);
1100     }
1101     if (MHSl) {
1102       std::vector<const Init *> NewOperands;
1103       std::vector<const Init *> NewList(MHSl->begin(), MHSl->end());
1104
1105       for (std::vector<const Init *>::iterator li = NewList.begin(),
1106              liend = NewList.end();
1107            li != liend;
1108            ++li) {
1109         const Init *Item = *li;
1110         NewOperands.clear();
1111         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
1112           // First, replace the foreach variable with the list item
1113           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
1114             NewOperands.push_back(Item);
1115           } else {
1116             NewOperands.push_back(RHSo->getOperand(i));
1117           }
1118         }
1119
1120         // Now run the operator and use its result as the new list item
1121         const OpInit *NewOp = RHSo->clone(NewOperands);
1122         const Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
1123         if (NewItem != NewOp)
1124           *li = NewItem;
1125       }
1126       return ListInit::get(NewList, MHSl->getType());
1127     }
1128   }
1129   return 0;
1130 }
1131
1132 const Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
1133   switch (getOpcode()) {
1134   default: assert(0 && "Unknown binop");
1135   case SUBST: {
1136     const DefInit *LHSd = dynamic_cast<const DefInit*>(LHS);
1137     const VarInit *LHSv = dynamic_cast<const VarInit*>(LHS);
1138     const StringInit *LHSs = dynamic_cast<const StringInit*>(LHS);
1139
1140     const DefInit *MHSd = dynamic_cast<const DefInit*>(MHS);
1141     const VarInit *MHSv = dynamic_cast<const VarInit*>(MHS);
1142     const StringInit *MHSs = dynamic_cast<const StringInit*>(MHS);
1143
1144     const DefInit *RHSd = dynamic_cast<const DefInit*>(RHS);
1145     const VarInit *RHSv = dynamic_cast<const VarInit*>(RHS);
1146     const StringInit *RHSs = dynamic_cast<const 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     const 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     const IntInit *LHSi = dynamic_cast<const IntInit*>(LHS);
1195     if (const Init *I = LHS->convertInitializerTo(IntRecTy::get()))
1196       LHSi = dynamic_cast<const 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 this;
1209 }
1210
1211 const Init *TernOpInit::resolveReferences(Record &R,
1212                                           const RecordVal *RV) const {
1213   const Init *lhs = LHS->resolveReferences(R, RV);
1214
1215   if (Opc == IF && lhs != LHS) {
1216     const IntInit *Value = dynamic_cast<const IntInit*>(lhs);
1217     if (const Init *I = lhs->convertInitializerTo(IntRecTy::get()))
1218       Value = dynamic_cast<const IntInit*>(I);
1219     if (Value != 0) {
1220       // Short-circuit
1221       if (Value->getValue()) {
1222         const Init *mhs = MHS->resolveReferences(R, RV);
1223         return (TernOpInit::get(getOpcode(), lhs, mhs,
1224                                 RHS, getType()))->Fold(&R, 0);
1225       } else {
1226         const Init *rhs = RHS->resolveReferences(R, RV);
1227         return (TernOpInit::get(getOpcode(), lhs, MHS,
1228                                 rhs, getType()))->Fold(&R, 0);
1229       }
1230     }
1231   }
1232
1233   const Init *mhs = MHS->resolveReferences(R, RV);
1234   const 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 const 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<const 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(this, Bits[i]);
1276   }
1277   return BitsInit::get(NewBits);
1278 }
1279
1280 const 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(this, Elements[0]);
1287
1288   std::vector<const Init*> ListInits;
1289   ListInits.reserve(Elements.size());
1290   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1291     ListInits.push_back(VarListElementInit::get(this, Elements[i]));
1292   return ListInit::get(ListInits, T);
1293 }
1294
1295
1296 const VarInit *VarInit::get(const std::string &VN, RecTy *T) {
1297   return new VarInit(VN, T);
1298 }
1299
1300 const Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1301                                          unsigned Bit) const {
1302   if (R.isTemplateArg(getName())) return 0;
1303   if (IRV && IRV->getName() != getName()) return 0;
1304
1305   RecordVal *RV = R.getValue(getName());
1306   assert(RV && "Reference to a non-existent variable?");
1307   assert(dynamic_cast<const BitsInit*>(RV->getValue()));
1308   const BitsInit *BI = (const BitsInit*)RV->getValue();
1309
1310   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1311   const Init *B = BI->getBit(Bit);
1312
1313   // If the bit is set to some value, or if we are resolving a reference to a
1314   // specific variable and that variable is explicitly unset, then replace the
1315   // VarBitInit with it.
1316   if (IRV || !dynamic_cast<const UnsetInit*>(B))
1317     return B;
1318   return 0;
1319 }
1320
1321 const Init *VarInit::resolveListElementReference(Record &R,
1322                                                  const RecordVal *IRV,
1323                                                  unsigned Elt) const {
1324   if (R.isTemplateArg(getName())) return 0;
1325   if (IRV && IRV->getName() != getName()) return 0;
1326
1327   RecordVal *RV = R.getValue(getName());
1328   assert(RV && "Reference to a non-existent variable?");
1329   const ListInit *LI = dynamic_cast<const ListInit*>(RV->getValue());
1330   if (!LI) {
1331     const VarInit *VI = dynamic_cast<const VarInit*>(RV->getValue());
1332     assert(VI && "Invalid list element!");
1333     return VarListElementInit::get(VI, Elt);
1334   }
1335
1336   if (Elt >= LI->getSize())
1337     return 0;  // Out of range reference.
1338   const Init *E = LI->getElement(Elt);
1339   // If the element is set to some value, or if we are resolving a reference
1340   // to a specific variable and that variable is explicitly unset, then
1341   // replace the VarListElementInit with it.
1342   if (IRV || !dynamic_cast<const UnsetInit*>(E))
1343     return E;
1344   return 0;
1345 }
1346
1347
1348 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1349   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1350     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1351       return RV->getType();
1352   return 0;
1353 }
1354
1355 const Init *VarInit::getFieldInit(Record &R, const RecordVal *RV,
1356                                   const std::string &FieldName) const {
1357   if (dynamic_cast<RecordRecTy*>(getType()))
1358     if (const RecordVal *Val = R.getValue(VarName)) {
1359       if (RV != Val && (RV || dynamic_cast<const UnsetInit*>(Val->getValue())))
1360         return 0;
1361       const Init *TheInit = Val->getValue();
1362       assert(TheInit != this && "Infinite loop detected!");
1363       if (const Init *I = TheInit->getFieldInit(R, RV, FieldName))
1364         return I;
1365       else
1366         return 0;
1367     }
1368   return 0;
1369 }
1370
1371 /// resolveReferences - This method is used by classes that refer to other
1372 /// variables which may not be defined at the time the expression is formed.
1373 /// If a value is set for the variable later, this method will be called on
1374 /// users of the value to allow the value to propagate out.
1375 ///
1376 const Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) const {
1377   if (RecordVal *Val = R.getValue(VarName))
1378     if (RV == Val || (RV == 0 && !dynamic_cast<const UnsetInit*>(Val->getValue())))
1379       return Val->getValue();
1380   return this;
1381 }
1382
1383 const VarBitInit *VarBitInit::get(const TypedInit *T, unsigned B) {
1384   return new VarBitInit(T, B);
1385 }
1386
1387 std::string VarBitInit::getAsString() const {
1388    return TI->getAsString() + "{" + utostr(Bit) + "}";
1389 }
1390
1391 const Init *VarBitInit::resolveReferences(Record &R,
1392                                           const RecordVal *RV) const {
1393   if (const Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1394     return I;
1395   return this;
1396 }
1397
1398 const VarListElementInit *VarListElementInit::get(const TypedInit *T,
1399                                                   unsigned E) {
1400   return new VarListElementInit(T, E);
1401 }
1402
1403 std::string VarListElementInit::getAsString() const {
1404   return TI->getAsString() + "[" + utostr(Element) + "]";
1405 }
1406
1407 const Init *VarListElementInit::resolveReferences(Record &R,
1408                                                   const RecordVal *RV) const {
1409   if (const Init *I = getVariable()->resolveListElementReference(R, RV,
1410                                                            getElementNum()))
1411     return I;
1412   return this;
1413 }
1414
1415 const Init *VarListElementInit::resolveBitReference(Record &R,
1416                                                     const RecordVal *RV,
1417                                                     unsigned Bit) const {
1418   // FIXME: This should be implemented, to support references like:
1419   // bit B = AA[0]{1};
1420   return 0;
1421 }
1422
1423 const Init *VarListElementInit::
1424 resolveListElementReference(Record &R, const RecordVal *RV,
1425                             unsigned Elt) const {
1426   // FIXME: This should be implemented, to support references like:
1427   // int B = AA[0][1];
1428   return 0;
1429 }
1430
1431 const DefInit *DefInit::get(Record *R) {
1432   return R->getDefInit();
1433 }
1434
1435 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1436   if (const RecordVal *RV = Def->getValue(FieldName))
1437     return RV->getType();
1438   return 0;
1439 }
1440
1441 const Init *DefInit::getFieldInit(Record &R, const RecordVal *RV,
1442                                   const std::string &FieldName) const {
1443   return Def->getValue(FieldName)->getValue();
1444 }
1445
1446
1447 std::string DefInit::getAsString() const {
1448   return Def->getName();
1449 }
1450
1451 const FieldInit *FieldInit::get(const Init *R, const std::string &FN) {
1452   return new FieldInit(R, FN);
1453 }
1454
1455 const Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1456                                            unsigned Bit) const {
1457   if (const Init *BitsVal = Rec->getFieldInit(R, RV, FieldName))
1458     if (const BitsInit *BI = dynamic_cast<const BitsInit*>(BitsVal)) {
1459       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1460       const Init *B = BI->getBit(Bit);
1461
1462       if (dynamic_cast<const BitInit*>(B))  // If the bit is set.
1463         return B;                     // Replace the VarBitInit with it.
1464     }
1465   return 0;
1466 }
1467
1468 const Init *FieldInit::resolveListElementReference(Record &R,
1469                                                    const RecordVal *RV,
1470                                                    unsigned Elt) const {
1471   if (const Init *ListVal = Rec->getFieldInit(R, RV, FieldName))
1472     if (const ListInit *LI = dynamic_cast<const ListInit*>(ListVal)) {
1473       if (Elt >= LI->getSize()) return 0;
1474       const Init *E = LI->getElement(Elt);
1475
1476       // If the element is set to some value, or if we are resolving a
1477       // reference to a specific variable and that variable is explicitly
1478       // unset, then replace the VarListElementInit with it.
1479       if (RV || !dynamic_cast<const UnsetInit*>(E))
1480         return E;
1481     }
1482   return 0;
1483 }
1484
1485 const Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) const {
1486   const Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1487
1488   const Init *BitsVal = NewRec->getFieldInit(R, RV, FieldName);
1489   if (BitsVal) {
1490     const Init *BVR = BitsVal->resolveReferences(R, RV);
1491     return BVR->isComplete() ? BVR : this;
1492   }
1493
1494   if (NewRec != Rec) {
1495     return FieldInit::get(NewRec, FieldName);
1496   }
1497   return this;
1498 }
1499
1500 const DagInit *
1501 DagInit::get(const Init *V, const std::string &VN,
1502              const std::vector<std::pair<const Init*, std::string> > &args) {
1503   typedef std::pair<const Init*, std::string> PairType;
1504
1505   std::vector<const Init *> Args;
1506   std::vector<std::string> Names;
1507
1508   for (std::vector<PairType>::const_iterator i = args.begin(),
1509          iend = args.end();
1510        i != iend;
1511        ++i) {
1512     Args.push_back(i->first);
1513     Names.push_back(i->second);
1514   }
1515
1516   return DagInit::get(V, VN, Args, Names);
1517 }
1518
1519 const DagInit *
1520 DagInit::get(const Init *V, const std::string &VN,
1521              const std::vector<const Init*> &args,
1522              const std::vector<std::string> &argNames) {
1523   return new DagInit(V, VN, args, argNames);
1524 }
1525
1526 const Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) const {
1527   std::vector<const Init*> NewArgs;
1528   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1529     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1530
1531   const Init *Op = Val->resolveReferences(R, RV);
1532
1533   if (Args != NewArgs || Op != Val)
1534     return DagInit::get(Op, ValName, NewArgs, ArgNames);
1535
1536   return this;
1537 }
1538
1539
1540 std::string DagInit::getAsString() const {
1541   std::string Result = "(" + Val->getAsString();
1542   if (!ValName.empty())
1543     Result += ":" + ValName;
1544   if (Args.size()) {
1545     Result += " " + Args[0]->getAsString();
1546     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1547     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1548       Result += ", " + Args[i]->getAsString();
1549       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1550     }
1551   }
1552   return Result + ")";
1553 }
1554
1555
1556 //===----------------------------------------------------------------------===//
1557 //    Other implementations
1558 //===----------------------------------------------------------------------===//
1559
1560 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1561   : Name(N), Ty(T), Prefix(P) {
1562   Value = Ty->convertValue(UnsetInit::get());
1563   assert(Value && "Cannot create unset value for current type!");
1564 }
1565
1566 void RecordVal::dump() const { errs() << *this; }
1567
1568 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
1569   if (getPrefix()) OS << "field ";
1570   OS << *getType() << " " << getName();
1571
1572   if (getValue())
1573     OS << " = " << *getValue();
1574
1575   if (PrintSem) OS << ";\n";
1576 }
1577
1578 unsigned Record::LastID = 0;
1579
1580 DefInit *Record::getDefInit() {
1581   if (!TheInit)
1582     TheInit = new DefInit(this, new RecordRecTy(this));
1583   return TheInit;
1584 }
1585
1586 void Record::setName(const std::string &Name) {
1587   if (TrackedRecords.getDef(getName()) == this) {
1588     TrackedRecords.removeDef(getName());
1589     this->Name = Name;
1590     TrackedRecords.addDef(this);
1591   } else {
1592     TrackedRecords.removeClass(getName());
1593     this->Name = Name;
1594     TrackedRecords.addClass(this);
1595   }
1596 }
1597
1598 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1599 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1600 /// references.
1601 void Record::resolveReferencesTo(const RecordVal *RV) {
1602   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1603     if (const Init *V = Values[i].getValue())
1604       Values[i].setValue(V->resolveReferences(*this, RV));
1605   }
1606 }
1607
1608 void Record::dump() const { errs() << *this; }
1609
1610 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
1611   OS << R.getName();
1612
1613   const std::vector<std::string> &TArgs = R.getTemplateArgs();
1614   if (!TArgs.empty()) {
1615     OS << "<";
1616     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1617       if (i) OS << ", ";
1618       const RecordVal *RV = R.getValue(TArgs[i]);
1619       assert(RV && "Template argument record not found??");
1620       RV->print(OS, false);
1621     }
1622     OS << ">";
1623   }
1624
1625   OS << " {";
1626   const std::vector<Record*> &SC = R.getSuperClasses();
1627   if (!SC.empty()) {
1628     OS << "\t//";
1629     for (unsigned i = 0, e = SC.size(); i != e; ++i)
1630       OS << " " << SC[i]->getName();
1631   }
1632   OS << "\n";
1633
1634   const std::vector<RecordVal> &Vals = R.getValues();
1635   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1636     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1637       OS << Vals[i];
1638   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1639     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1640       OS << Vals[i];
1641
1642   return OS << "}\n";
1643 }
1644
1645 /// getValueInit - Return the initializer for a value with the specified name,
1646 /// or throw an exception if the field does not exist.
1647 ///
1648 const Init *Record::getValueInit(StringRef FieldName) const {
1649   const RecordVal *R = getValue(FieldName);
1650   if (R == 0 || R->getValue() == 0)
1651     throw "Record `" + getName() + "' does not have a field named `" +
1652       FieldName.str() + "'!\n";
1653   return R->getValue();
1654 }
1655
1656
1657 /// getValueAsString - This method looks up the specified field and returns its
1658 /// value as a string, throwing an exception if the field does not exist or if
1659 /// the value is not a string.
1660 ///
1661 std::string Record::getValueAsString(StringRef FieldName) const {
1662   const RecordVal *R = getValue(FieldName);
1663   if (R == 0 || R->getValue() == 0)
1664     throw "Record `" + getName() + "' does not have a field named `" +
1665           FieldName.str() + "'!\n";
1666
1667   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
1668     return SI->getValue();
1669   throw "Record `" + getName() + "', field `" + FieldName.str() +
1670         "' does not have a string initializer!";
1671 }
1672
1673 /// getValueAsBitsInit - This method looks up the specified field and returns
1674 /// its value as a BitsInit, throwing an exception if the field does not exist
1675 /// or if the value is not the right type.
1676 ///
1677 const BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
1678   const RecordVal *R = getValue(FieldName);
1679   if (R == 0 || R->getValue() == 0)
1680     throw "Record `" + getName() + "' does not have a field named `" +
1681           FieldName.str() + "'!\n";
1682
1683   if (const BitsInit *BI = dynamic_cast<const BitsInit*>(R->getValue()))
1684     return BI;
1685   throw "Record `" + getName() + "', field `" + FieldName.str() +
1686         "' does not have a BitsInit initializer!";
1687 }
1688
1689 /// getValueAsListInit - This method looks up the specified field and returns
1690 /// its value as a ListInit, throwing an exception if the field does not exist
1691 /// or if the value is not the right type.
1692 ///
1693 const ListInit *Record::getValueAsListInit(StringRef FieldName) const {
1694   const RecordVal *R = getValue(FieldName);
1695   if (R == 0 || R->getValue() == 0)
1696     throw "Record `" + getName() + "' does not have a field named `" +
1697           FieldName.str() + "'!\n";
1698
1699   if (const ListInit *LI = dynamic_cast<const ListInit*>(R->getValue()))
1700     return LI;
1701   throw "Record `" + getName() + "', field `" + FieldName.str() +
1702         "' does not have a list initializer!";
1703 }
1704
1705 /// getValueAsListOfDefs - This method looks up the specified field and returns
1706 /// its value as a vector of records, throwing an exception if the field does
1707 /// not exist or if the value is not the right type.
1708 ///
1709 std::vector<Record*>
1710 Record::getValueAsListOfDefs(StringRef FieldName) const {
1711   const ListInit *List = getValueAsListInit(FieldName);
1712   std::vector<Record*> Defs;
1713   for (unsigned i = 0; i < List->getSize(); i++) {
1714     if (const DefInit *DI = dynamic_cast<const DefInit*>(List->getElement(i))) {
1715       Defs.push_back(DI->getDef());
1716     } else {
1717       throw "Record `" + getName() + "', field `" + FieldName.str() +
1718             "' list is not entirely DefInit!";
1719     }
1720   }
1721   return Defs;
1722 }
1723
1724 /// getValueAsInt - This method looks up the specified field and returns its
1725 /// value as an int64_t, throwing an exception if the field does not exist or if
1726 /// the value is not the right type.
1727 ///
1728 int64_t Record::getValueAsInt(StringRef FieldName) const {
1729   const RecordVal *R = getValue(FieldName);
1730   if (R == 0 || R->getValue() == 0)
1731     throw "Record `" + getName() + "' does not have a field named `" +
1732           FieldName.str() + "'!\n";
1733
1734   if (const IntInit *II = dynamic_cast<const IntInit*>(R->getValue()))
1735     return II->getValue();
1736   throw "Record `" + getName() + "', field `" + FieldName.str() +
1737         "' does not have an int initializer!";
1738 }
1739
1740 /// getValueAsListOfInts - This method looks up the specified field and returns
1741 /// its value as a vector of integers, throwing an exception if the field does
1742 /// not exist or if the value is not the right type.
1743 ///
1744 std::vector<int64_t>
1745 Record::getValueAsListOfInts(StringRef FieldName) const {
1746   const ListInit *List = getValueAsListInit(FieldName);
1747   std::vector<int64_t> Ints;
1748   for (unsigned i = 0; i < List->getSize(); i++) {
1749     if (const IntInit *II = dynamic_cast<const IntInit*>(List->getElement(i))) {
1750       Ints.push_back(II->getValue());
1751     } else {
1752       throw "Record `" + getName() + "', field `" + FieldName.str() +
1753             "' does not have a list of ints initializer!";
1754     }
1755   }
1756   return Ints;
1757 }
1758
1759 /// getValueAsListOfStrings - This method looks up the specified field and
1760 /// returns its value as a vector of strings, throwing an exception if the
1761 /// field does not exist or if the value is not the right type.
1762 ///
1763 std::vector<std::string>
1764 Record::getValueAsListOfStrings(StringRef FieldName) const {
1765   const ListInit *List = getValueAsListInit(FieldName);
1766   std::vector<std::string> Strings;
1767   for (unsigned i = 0; i < List->getSize(); i++) {
1768     if (const StringInit *II = dynamic_cast<const StringInit*>(List->getElement(i))) {
1769       Strings.push_back(II->getValue());
1770     } else {
1771       throw "Record `" + getName() + "', field `" + FieldName.str() +
1772             "' does not have a list of strings initializer!";
1773     }
1774   }
1775   return Strings;
1776 }
1777
1778 /// getValueAsDef - This method looks up the specified field and returns its
1779 /// value as a Record, throwing an exception if the field does not exist or if
1780 /// the value is not the right type.
1781 ///
1782 Record *Record::getValueAsDef(StringRef FieldName) const {
1783   const RecordVal *R = getValue(FieldName);
1784   if (R == 0 || R->getValue() == 0)
1785     throw "Record `" + getName() + "' does not have a field named `" +
1786       FieldName.str() + "'!\n";
1787
1788   if (const DefInit *DI = dynamic_cast<const DefInit*>(R->getValue()))
1789     return DI->getDef();
1790   throw "Record `" + getName() + "', field `" + FieldName.str() +
1791         "' does not have a def initializer!";
1792 }
1793
1794 /// getValueAsBit - This method looks up the specified field and returns its
1795 /// value as a bit, throwing an exception if the field does not exist or if
1796 /// the value is not the right type.
1797 ///
1798 bool Record::getValueAsBit(StringRef FieldName) const {
1799   const RecordVal *R = getValue(FieldName);
1800   if (R == 0 || R->getValue() == 0)
1801     throw "Record `" + getName() + "' does not have a field named `" +
1802       FieldName.str() + "'!\n";
1803
1804   if (const BitInit *BI = dynamic_cast<const BitInit*>(R->getValue()))
1805     return BI->getValue();
1806   throw "Record `" + getName() + "', field `" + FieldName.str() +
1807         "' does not have a bit initializer!";
1808 }
1809
1810 /// getValueAsDag - This method looks up the specified field and returns its
1811 /// value as an Dag, throwing an exception if the field does not exist or if
1812 /// the value is not the right type.
1813 ///
1814 const DagInit *Record::getValueAsDag(StringRef FieldName) const {
1815   const RecordVal *R = getValue(FieldName);
1816   if (R == 0 || R->getValue() == 0)
1817     throw "Record `" + getName() + "' does not have a field named `" +
1818       FieldName.str() + "'!\n";
1819
1820   if (const DagInit *DI = dynamic_cast<const DagInit*>(R->getValue()))
1821     return DI;
1822   throw "Record `" + getName() + "', field `" + FieldName.str() +
1823         "' does not have a dag initializer!";
1824 }
1825
1826 std::string Record::getValueAsCode(StringRef FieldName) const {
1827   const RecordVal *R = getValue(FieldName);
1828   if (R == 0 || R->getValue() == 0)
1829     throw "Record `" + getName() + "' does not have a field named `" +
1830       FieldName.str() + "'!\n";
1831
1832   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
1833     return CI->getValue();
1834   throw "Record `" + getName() + "', field `" + FieldName.str() +
1835     "' does not have a code initializer!";
1836 }
1837
1838
1839 void MultiClass::dump() const {
1840   errs() << "Record:\n";
1841   Rec.dump();
1842
1843   errs() << "Defs:\n";
1844   for (RecordVector::const_iterator r = DefPrototypes.begin(),
1845          rend = DefPrototypes.end();
1846        r != rend;
1847        ++r) {
1848     (*r)->dump();
1849   }
1850 }
1851
1852
1853 void RecordKeeper::dump() const { errs() << *this; }
1854
1855 raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
1856   OS << "------------- Classes -----------------\n";
1857   const std::map<std::string, Record*> &Classes = RK.getClasses();
1858   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1859          E = Classes.end(); I != E; ++I)
1860     OS << "class " << *I->second;
1861
1862   OS << "------------- Defs -----------------\n";
1863   const std::map<std::string, Record*> &Defs = RK.getDefs();
1864   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1865          E = Defs.end(); I != E; ++I)
1866     OS << "def " << *I->second;
1867   return OS;
1868 }
1869
1870
1871 /// getAllDerivedDefinitions - This method returns all concrete definitions
1872 /// that derive from the specified class name.  If a class with the specified
1873 /// name does not exist, an error is printed and true is returned.
1874 std::vector<Record*>
1875 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1876   Record *Class = getClass(ClassName);
1877   if (!Class)
1878     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1879
1880   std::vector<Record*> Defs;
1881   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1882          E = getDefs().end(); I != E; ++I)
1883     if (I->second->isSubClassOf(Class))
1884       Defs.push_back(I->second);
1885
1886   return Defs;
1887 }
1888