fa10799622cd421fdc630e5fdd0d884d29388e87
[oota-llvm.git] / utils / TableGen / Record.cpp
1 //===- Record.cpp - Record implementation ---------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the tablegen record classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Record.h"
15 #include "llvm/Support/DataTypes.h"
16 #include "llvm/Support/Streams.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include <ios>
19 #include <sys/types.h>
20 #include <regex.h>
21
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 //    Type implementations
26 //===----------------------------------------------------------------------===//
27
28 void RecTy::dump() const { print(*cerr.stream()); }
29
30 Init *BitRecTy::convertValue(BitsInit *BI) {
31   if (BI->getNumBits() != 1) return 0; // Only accept if just one bit!
32   return BI->getBit(0);
33 }
34
35 bool BitRecTy::baseClassOf(const BitsRecTy *RHS) const {
36   return RHS->getNumBits() == 1;
37 }
38
39 Init *BitRecTy::convertValue(IntInit *II) {
40   int64_t Val = II->getValue();
41   if (Val != 0 && Val != 1) return 0;  // Only accept 0 or 1 for a bit!
42
43   return new BitInit(Val != 0);
44 }
45
46 Init *BitRecTy::convertValue(TypedInit *VI) {
47   if (dynamic_cast<BitRecTy*>(VI->getType()))
48     return VI;  // Accept variable if it is already of bit type!
49   return 0;
50 }
51
52 std::string BitsRecTy::getAsString() const {
53   return "bits<" + utostr(Size) + ">";
54 }
55
56 Init *BitsRecTy::convertValue(UnsetInit *UI) {
57   BitsInit *Ret = new BitsInit(Size);
58
59   for (unsigned i = 0; i != Size; ++i)
60     Ret->setBit(i, new UnsetInit());
61   return Ret;
62 }
63
64 Init *BitsRecTy::convertValue(BitInit *UI) {
65   if (Size != 1) return 0;  // Can only convert single bit...
66   BitsInit *Ret = new BitsInit(1);
67   Ret->setBit(0, UI);
68   return Ret;
69 }
70
71 // convertValue from Int initializer to bits type: Split the integer up into the
72 // appropriate bits...
73 //
74 Init *BitsRecTy::convertValue(IntInit *II) {
75   int64_t Value = II->getValue();
76   // Make sure this bitfield is large enough to hold the integer value...
77   if (Value >= 0) {
78     if (Value & ~((1LL << Size)-1))
79       return 0;
80   } else {
81     if ((Value >> Size) != -1 || ((Value & (1LL << (Size-1))) == 0))
82       return 0;
83   }
84
85   BitsInit *Ret = new BitsInit(Size);
86   for (unsigned i = 0; i != Size; ++i)
87     Ret->setBit(i, new BitInit(Value & (1LL << i)));
88
89   return Ret;
90 }
91
92 Init *BitsRecTy::convertValue(BitsInit *BI) {
93   // If the number of bits is right, return it.  Otherwise we need to expand or
94   // truncate...
95   if (BI->getNumBits() == Size) return BI;
96   return 0;
97 }
98
99 Init *BitsRecTy::convertValue(TypedInit *VI) {
100   if (BitsRecTy *BRT = dynamic_cast<BitsRecTy*>(VI->getType()))
101     if (BRT->Size == Size) {
102       BitsInit *Ret = new BitsInit(Size);
103       for (unsigned i = 0; i != Size; ++i)
104         Ret->setBit(i, new VarBitInit(VI, i));
105       return Ret;
106     }
107   if (Size == 1 && dynamic_cast<BitRecTy*>(VI->getType())) {
108     BitsInit *Ret = new BitsInit(1);
109     Ret->setBit(0, VI);
110     return Ret;
111   }
112
113   return 0;
114 }
115
116 Init *IntRecTy::convertValue(BitInit *BI) {
117   return new IntInit(BI->getValue());
118 }
119
120 Init *IntRecTy::convertValue(BitsInit *BI) {
121   int64_t Result = 0;
122   for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
123     if (BitInit *Bit = dynamic_cast<BitInit*>(BI->getBit(i))) {
124       Result |= Bit->getValue() << i;
125     } else {
126       return 0;
127     }
128   return new IntInit(Result);
129 }
130
131 Init *IntRecTy::convertValue(TypedInit *TI) {
132   if (TI->getType()->typeIsConvertibleTo(this))
133     return TI;  // Accept variable if already of the right type!
134   return 0;
135 }
136
137 Init *StringRecTy::convertValue(UnOpInit *BO) {
138   if (BO->getOpcode() == UnOpInit::CAST) {
139     Init *L = BO->getOperand()->convertInitializerTo(this);
140     if (L == 0) return 0;
141     if (L != BO->getOperand())
142       return new UnOpInit(UnOpInit::CAST, L, new StringRecTy);
143     return BO;
144   }
145
146   return convertValue((TypedInit*)BO);
147 }
148
149 Init *StringRecTy::convertValue(BinOpInit *BO) {
150   if (BO->getOpcode() == BinOpInit::STRCONCAT) {
151     Init *L = BO->getLHS()->convertInitializerTo(this);
152     Init *R = BO->getRHS()->convertInitializerTo(this);
153     if (L == 0 || R == 0) return 0;
154     if (L != BO->getLHS() || R != BO->getRHS())
155       return new BinOpInit(BinOpInit::STRCONCAT, L, R, new StringRecTy);
156     return BO;
157   }
158   if (BO->getOpcode() == BinOpInit::NAMECONCAT) {
159     if (BO->getType()->getAsString() == getAsString()) {
160       Init *L = BO->getLHS()->convertInitializerTo(this);
161       Init *R = BO->getRHS()->convertInitializerTo(this);
162       if (L == 0 || R == 0) return 0;
163       if (L != BO->getLHS() || R != BO->getRHS())
164         return new BinOpInit(BinOpInit::NAMECONCAT, L, R, new StringRecTy);
165       return BO;
166     }
167   }
168
169   return convertValue((TypedInit*)BO);
170 }
171
172
173 Init *StringRecTy::convertValue(TypedInit *TI) {
174   if (dynamic_cast<StringRecTy*>(TI->getType()))
175     return TI;  // Accept variable if already of the right type!
176   return 0;
177 }
178
179 std::string ListRecTy::getAsString() const {
180   return "list<" + Ty->getAsString() + ">";
181 }
182
183 Init *ListRecTy::convertValue(ListInit *LI) {
184   std::vector<Init*> Elements;
185
186   // Verify that all of the elements of the list are subclasses of the
187   // appropriate class!
188   for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
189     if (Init *CI = LI->getElement(i)->convertInitializerTo(Ty))
190       Elements.push_back(CI);
191     else
192       return 0;
193
194   ListRecTy *LType = dynamic_cast<ListRecTy*>(LI->getType());
195   if (LType == 0) {
196     return 0;
197   }
198
199   return new ListInit(Elements, new ListRecTy(Ty));
200 }
201
202 Init *ListRecTy::convertValue(TypedInit *TI) {
203   // Ensure that TI is compatible with our class.
204   if (ListRecTy *LRT = dynamic_cast<ListRecTy*>(TI->getType()))
205     if (LRT->getElementType()->typeIsConvertibleTo(getElementType()))
206       return TI;
207   return 0;
208 }
209
210 Init *CodeRecTy::convertValue(TypedInit *TI) {
211   if (TI->getType()->typeIsConvertibleTo(this))
212     return TI;
213   return 0;
214 }
215
216 Init *DagRecTy::convertValue(TypedInit *TI) {
217   if (TI->getType()->typeIsConvertibleTo(this))
218     return TI;
219   return 0;
220 }
221
222 Init *DagRecTy::convertValue(UnOpInit *BO) {
223   if (BO->getOpcode() == UnOpInit::CAST) {
224     Init *L = BO->getOperand()->convertInitializerTo(this);
225     if (L == 0) return 0;
226     if (L != BO->getOperand())
227       return new UnOpInit(UnOpInit::CAST, L, new DagRecTy);
228     return BO;
229   }
230   return 0;
231 }
232
233 Init *DagRecTy::convertValue(BinOpInit *BO) {
234   if (BO->getOpcode() == BinOpInit::CONCAT) {
235     Init *L = BO->getLHS()->convertInitializerTo(this);
236     Init *R = BO->getRHS()->convertInitializerTo(this);
237     if (L == 0 || R == 0) return 0;
238     if (L != BO->getLHS() || R != BO->getRHS())
239       return new BinOpInit(BinOpInit::CONCAT, L, R, new DagRecTy);
240     return BO;
241   }
242   if (BO->getOpcode() == BinOpInit::NAMECONCAT) {
243     if (BO->getType()->getAsString() == getAsString()) {
244       Init *L = BO->getLHS()->convertInitializerTo(this);
245       Init *R = BO->getRHS()->convertInitializerTo(this);
246       if (L == 0 || R == 0) return 0;
247       if (L != BO->getLHS() || R != BO->getRHS())
248         return new BinOpInit(BinOpInit::CONCAT, L, R, new DagRecTy);
249       return BO;
250     }
251   }
252   return 0;
253 }
254
255 std::string RecordRecTy::getAsString() const {
256   return Rec->getName();
257 }
258
259 Init *RecordRecTy::convertValue(DefInit *DI) {
260   // Ensure that DI is a subclass of Rec.
261   if (!DI->getDef()->isSubClassOf(Rec))
262     return 0;
263   return DI;
264 }
265
266 Init *RecordRecTy::convertValue(TypedInit *TI) {
267   // Ensure that TI is compatible with Rec.
268   if (RecordRecTy *RRT = dynamic_cast<RecordRecTy*>(TI->getType()))
269     if (RRT->getRecord()->isSubClassOf(getRecord()) ||
270         RRT->getRecord() == getRecord())
271       return TI;
272   return 0;
273 }
274
275 bool RecordRecTy::baseClassOf(const RecordRecTy *RHS) const {
276   return Rec == RHS->getRecord() || RHS->getRecord()->isSubClassOf(Rec);
277 }
278
279
280 /// resolveTypes - Find a common type that T1 and T2 convert to.  
281 /// Return 0 if no such type exists.
282 ///
283 RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
284   if (!T1->typeIsConvertibleTo(T2)) {
285     if (!T2->typeIsConvertibleTo(T1)) {
286       // If one is a Record type, check superclasses
287       RecordRecTy *RecTy1 = dynamic_cast<RecordRecTy*>(T1);
288       if (RecTy1) {
289         // See if T2 inherits from a type T1 also inherits from
290         const std::vector<Record *> &T1SuperClasses = RecTy1->getRecord()->getSuperClasses();
291         for(std::vector<Record *>::const_iterator i = T1SuperClasses.begin(),
292               iend = T1SuperClasses.end();
293             i != iend;
294             ++i) {
295           RecordRecTy *SuperRecTy1 = new RecordRecTy(*i);
296           RecTy *NewType1 = resolveTypes(SuperRecTy1, T2);
297           if (NewType1 != 0) {
298             if (NewType1 != SuperRecTy1) {
299               delete SuperRecTy1;
300             }
301             return NewType1;
302           }
303         }
304       }
305       RecordRecTy *RecTy2 = dynamic_cast<RecordRecTy*>(T2);
306       if (RecTy2) {
307         // See if T1 inherits from a type T2 also inherits from
308         const std::vector<Record *> &T2SuperClasses = RecTy2->getRecord()->getSuperClasses();
309         for(std::vector<Record *>::const_iterator i = T2SuperClasses.begin(),
310               iend = T2SuperClasses.end();
311             i != iend;
312             ++i) {
313           RecordRecTy *SuperRecTy2 = new RecordRecTy(*i);
314           RecTy *NewType2 = resolveTypes(T1, SuperRecTy2);
315           if (NewType2 != 0) {
316             if (NewType2 != SuperRecTy2) {
317               delete SuperRecTy2;
318             }
319             return NewType2;
320           }
321         }
322       }
323       return 0;
324     }
325     return T2;
326   }
327   return T1;
328 }
329
330
331 //===----------------------------------------------------------------------===//
332 //    Initializer implementations
333 //===----------------------------------------------------------------------===//
334
335 void Init::dump() const { return print(*cerr.stream()); }
336
337 Init *BitsInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
338   BitsInit *BI = new BitsInit(Bits.size());
339   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
340     if (Bits[i] >= getNumBits()) {
341       delete BI;
342       return 0;
343     }
344     BI->setBit(i, getBit(Bits[i]));
345   }
346   return BI;
347 }
348
349 std::string BitsInit::getAsString() const {
350   //if (!printInHex(OS)) return;
351   //if (!printAsVariable(OS)) return;
352   //if (!printAsUnset(OS)) return;
353
354   std::string Result = "{ ";
355   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
356     if (i) Result += ", ";
357     if (Init *Bit = getBit(e-i-1))
358       Result += Bit->getAsString();
359     else
360       Result += "*";
361   }
362   return Result + " }";
363 }
364
365 bool BitsInit::printInHex(std::ostream &OS) const {
366   // First, attempt to convert the value into an integer value...
367   int64_t Result = 0;
368   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
369     if (BitInit *Bit = dynamic_cast<BitInit*>(getBit(i))) {
370       Result |= Bit->getValue() << i;
371     } else {
372       return true;
373     }
374
375   OS << "0x" << std::hex << Result << std::dec;
376   return false;
377 }
378
379 bool BitsInit::printAsVariable(std::ostream &OS) const {
380   // Get the variable that we may be set equal to...
381   assert(getNumBits() != 0);
382   VarBitInit *FirstBit = dynamic_cast<VarBitInit*>(getBit(0));
383   if (FirstBit == 0) return true;
384   TypedInit *Var = FirstBit->getVariable();
385
386   // Check to make sure the types are compatible.
387   BitsRecTy *Ty = dynamic_cast<BitsRecTy*>(FirstBit->getVariable()->getType());
388   if (Ty == 0) return true;
389   if (Ty->getNumBits() != getNumBits()) return true; // Incompatible types!
390
391   // Check to make sure all bits are referring to the right bits in the variable
392   for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
393     VarBitInit *Bit = dynamic_cast<VarBitInit*>(getBit(i));
394     if (Bit == 0 || Bit->getVariable() != Var || Bit->getBitNum() != i)
395       return true;
396   }
397
398   Var->print(OS);
399   return false;
400 }
401
402 bool BitsInit::printAsUnset(std::ostream &OS) const {
403   for (unsigned i = 0, e = getNumBits(); i != e; ++i)
404     if (!dynamic_cast<UnsetInit*>(getBit(i)))
405       return true;
406   OS << "?";
407   return false;
408 }
409
410 // resolveReferences - If there are any field references that refer to fields
411 // that have been filled in, we can propagate the values now.
412 //
413 Init *BitsInit::resolveReferences(Record &R, const RecordVal *RV) {
414   bool Changed = false;
415   BitsInit *New = new BitsInit(getNumBits());
416
417   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
418     Init *B;
419     Init *CurBit = getBit(i);
420
421     do {
422       B = CurBit;
423       CurBit = CurBit->resolveReferences(R, RV);
424       Changed |= B != CurBit;
425     } while (B != CurBit);
426     New->setBit(i, CurBit);
427   }
428
429   if (Changed)
430     return New;
431   delete New;
432   return this;
433 }
434
435 std::string IntInit::getAsString() const {
436   return itostr(Value);
437 }
438
439 Init *IntInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
440   BitsInit *BI = new BitsInit(Bits.size());
441
442   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
443     if (Bits[i] >= 64) {
444       delete BI;
445       return 0;
446     }
447     BI->setBit(i, new BitInit(Value & (INT64_C(1) << Bits[i])));
448   }
449   return BI;
450 }
451
452 Init *ListInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
453   std::vector<Init*> Vals;
454   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
455     if (Elements[i] >= getSize())
456       return 0;
457     Vals.push_back(getElement(Elements[i]));
458   }
459   return new ListInit(Vals, getType());
460 }
461
462 Record *ListInit::getElementAsRecord(unsigned i) const {
463   assert(i < Values.size() && "List element index out of range!");
464   DefInit *DI = dynamic_cast<DefInit*>(Values[i]);
465   if (DI == 0) throw "Expected record in list!";
466   return DI->getDef();
467 }
468
469 Init *ListInit::resolveReferences(Record &R, const RecordVal *RV) {
470   std::vector<Init*> Resolved;
471   Resolved.reserve(getSize());
472   bool Changed = false;
473
474   for (unsigned i = 0, e = getSize(); i != e; ++i) {
475     Init *E;
476     Init *CurElt = getElement(i);
477
478     do {
479       E = CurElt;
480       CurElt = CurElt->resolveReferences(R, RV);
481       Changed |= E != CurElt;
482     } while (E != CurElt);
483     Resolved.push_back(E);
484   }
485
486   if (Changed)
487     return new ListInit(Resolved, getType());
488   return this;
489 }
490
491 Init *ListInit::resolveListElementReference(Record &R, const RecordVal *IRV,
492                                            unsigned Elt) {
493   if (Elt >= getSize())
494     return 0;  // Out of range reference.
495   Init *E = getElement(Elt);
496   if (!dynamic_cast<UnsetInit*>(E))  // If the element is set
497     return E;                        // Replace the VarListElementInit with it.
498   return 0;
499 }
500
501 std::string ListInit::getAsString() const {
502   std::string Result = "[";
503   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
504     if (i) Result += ", ";
505     Result += Values[i]->getAsString();
506   }
507   return Result + "]";
508 }
509
510 Init *OpInit::resolveBitReference(Record &R, const RecordVal *IRV,
511                                    unsigned Bit) {
512   Init *Folded = Fold(&R, 0);
513
514   if (Folded != this) {
515     TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
516     if (Typed) {
517       return Typed->resolveBitReference(R, IRV, Bit);
518     }    
519   }
520   
521   return 0;
522 }
523
524 Init *OpInit::resolveListElementReference(Record &R, const RecordVal *IRV,
525                                            unsigned Elt) {
526   Init *Folded = Fold(&R, 0);
527
528   if (Folded != this) {
529     TypedInit *Typed = dynamic_cast<TypedInit *>(Folded);
530     if (Typed) {
531       return Typed->resolveListElementReference(R, IRV, Elt);
532     }    
533   }
534   
535   return 0;
536 }
537
538 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
539   switch (getOpcode()) {
540   default: assert(0 && "Unknown unop");
541   case CAST: {
542     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
543     if (LHSs) {
544       std::string Name = LHSs->getValue();
545
546       // From TGParser::ParseIDValue
547       if (CurRec) {
548         if (const RecordVal *RV = CurRec->getValue(Name)) {
549           if (RV->getType() != getType()) {
550             throw "type mismatch in nameconcat";
551           }
552           return new VarInit(Name, RV->getType());
553         }
554         
555         std::string TemplateArgName = CurRec->getName()+":"+Name;
556         if (CurRec->isTemplateArg(TemplateArgName)) {
557           const RecordVal *RV = CurRec->getValue(TemplateArgName);
558           assert(RV && "Template arg doesn't exist??");
559
560           if (RV->getType() != getType()) {
561             throw "type mismatch in nameconcat";
562           }
563
564           return new VarInit(TemplateArgName, RV->getType());
565         }
566       }
567
568       if (CurMultiClass) {
569         std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
570         if (CurMultiClass->Rec.isTemplateArg(MCName)) {
571           const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
572           assert(RV && "Template arg doesn't exist??");
573
574           if (RV->getType() != getType()) {
575             throw "type mismatch in nameconcat";
576           }
577           
578           return new VarInit(MCName, RV->getType());
579         }
580       }
581
582       if (Record *D = Records.getDef(Name))
583         return new DefInit(D);
584
585       cerr << "Variable not defined: '" + Name + "'\n";
586       assert(0 && "Variable not found");
587       return 0;
588     }
589     break;
590   }
591   case CAR: {
592     ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
593     if (LHSl) {
594       if (LHSl->getSize() == 0) {
595         assert(0 && "Empty list in car");
596         return 0;
597       }
598       return LHSl->getElement(0);
599     }
600     break;
601   }
602   case CDR: {
603     ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
604     if (LHSl) {
605       if (LHSl->getSize() == 0) {
606         assert(0 && "Empty list in cdr");
607         return 0;
608       }
609       ListInit *Result = new ListInit(LHSl->begin()+1, LHSl->end(), LHSl->getType());
610       return Result;
611     }
612     break;
613   }
614   case LNULL: {
615     ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
616     if (LHSl) {
617       if (LHSl->getSize() == 0) {
618         return new IntInit(1);
619       }
620       else {
621         return new IntInit(0);
622       }
623     }
624     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
625     if (LHSs) {
626       if (LHSs->getValue().empty()) {
627         return new IntInit(1);
628       }
629       else {
630         return new IntInit(0);
631       }
632     }
633     
634     break;
635   }
636   }
637   return this;
638 }
639
640 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) {
641   Init *lhs = LHS->resolveReferences(R, RV);
642   
643   if (LHS != lhs)
644     return (new UnOpInit(getOpcode(), lhs, getType()))->Fold(&R, 0);
645   return Fold(&R, 0);
646 }
647
648 std::string UnOpInit::getAsString() const {
649   std::string Result;
650   switch (Opc) {
651   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
652   case CAR: Result = "!car"; break;
653   case CDR: Result = "!cdr"; break;
654   case LNULL: Result = "!null"; break;
655   }
656   return Result + "(" + LHS->getAsString() + ")";
657 }
658
659 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
660   switch (getOpcode()) {
661   default: assert(0 && "Unknown binop");
662   case CONCAT: {
663     DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
664     DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
665     if (LHSs && RHSs) {
666       DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
667       DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
668       if (LOp->getDef() != ROp->getDef()) {
669         bool LIsOps =
670           LOp->getDef()->getName() == "outs" ||
671           LOp->getDef()->getName() != "ins" ||
672           LOp->getDef()->getName() != "defs";
673         bool RIsOps =
674           ROp->getDef()->getName() == "outs" ||
675           ROp->getDef()->getName() != "ins" ||
676           ROp->getDef()->getName() != "defs";
677         if (!LIsOps || !RIsOps)
678           throw "Concated Dag operators do not match!";
679       }
680       std::vector<Init*> Args;
681       std::vector<std::string> ArgNames;
682       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
683         Args.push_back(LHSs->getArg(i));
684         ArgNames.push_back(LHSs->getArgName(i));
685       }
686       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
687         Args.push_back(RHSs->getArg(i));
688         ArgNames.push_back(RHSs->getArgName(i));
689       }
690       return new DagInit(LHSs->getOperator(), "", Args, ArgNames);
691     }
692     break;
693   }
694   case STRCONCAT: {
695     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
696     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
697     if (LHSs && RHSs)
698       return new StringInit(LHSs->getValue() + RHSs->getValue());
699     break;
700   }
701   case NAMECONCAT: {
702     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
703     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
704     if (LHSs && RHSs) {
705       std::string Name(LHSs->getValue() + RHSs->getValue());
706
707       // From TGParser::ParseIDValue
708       if (CurRec) {
709         if (const RecordVal *RV = CurRec->getValue(Name)) {
710           if (RV->getType() != getType()) {
711             throw "type mismatch in nameconcat";
712           }
713           return new VarInit(Name, RV->getType());
714         }
715         
716         std::string TemplateArgName = CurRec->getName()+":"+Name;
717         if (CurRec->isTemplateArg(TemplateArgName)) {
718           const RecordVal *RV = CurRec->getValue(TemplateArgName);
719           assert(RV && "Template arg doesn't exist??");
720
721           if (RV->getType() != getType()) {
722             throw "type mismatch in nameconcat";
723           }
724
725           return new VarInit(TemplateArgName, RV->getType());
726         }
727       }
728
729       if (CurMultiClass) {
730         std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
731         if (CurMultiClass->Rec.isTemplateArg(MCName)) {
732           const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
733           assert(RV && "Template arg doesn't exist??");
734
735           if (RV->getType() != getType()) {
736             throw "type mismatch in nameconcat";
737           }
738           
739           return new VarInit(MCName, RV->getType());
740         }
741       }
742
743       if (Record *D = Records.getDef(Name))
744         return new DefInit(D);
745
746       cerr << "Variable not defined in !nameconcat: '" + Name + "'\n";
747       assert(0 && "Variable not found in !nameconcat");
748       return 0;
749     }
750     break;
751   }
752   case REGMATCH: {
753     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
754     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
755     if (LHSs && RHSs) {
756       regex_t compiled;
757       int err = regcomp (&compiled, LHSs->getValue().c_str(), REG_EXTENDED);
758       if (err != 0) {
759         size_t length = regerror (err, &compiled, NULL, 0);
760         char *buffer = new char[length];
761         (void) regerror (err, &compiled, buffer, length);
762         std::string errmsg = buffer;
763         delete[] buffer;
764         regfree(&compiled);
765         throw errmsg;
766       }
767       int result = regexec(&compiled, RHSs->getValue().c_str(), 0, NULL, 0);
768       if (result == REG_ESPACE) {
769         size_t length = regerror (err, &compiled, NULL, 0);
770         char *buffer = new char[length];
771         (void) regerror (err, &compiled, buffer, length);
772         std::string errmsg = buffer;
773         delete[] buffer;
774         regfree(&compiled);
775         throw errmsg;
776       }
777       regfree(&compiled);
778       return new IntInit(result == 0);
779     }    
780     break;
781   }
782   case SHL:
783   case SRA:
784   case SRL: {
785     IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
786     IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
787     if (LHSi && RHSi) {
788       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
789       int64_t Result;
790       switch (getOpcode()) {
791       default: assert(0 && "Bad opcode!");
792       case SHL: Result = LHSv << RHSv; break;
793       case SRA: Result = LHSv >> RHSv; break;
794       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
795       }
796       return new IntInit(Result);
797     }
798     break;
799   }
800   }
801   return this;
802 }
803
804 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) {
805   Init *lhs = LHS->resolveReferences(R, RV);
806   Init *rhs = RHS->resolveReferences(R, RV);
807   
808   if (LHS != lhs || RHS != rhs)
809     return (new BinOpInit(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
810   return Fold(&R, 0);
811 }
812
813 std::string BinOpInit::getAsString() const {
814   std::string Result;
815   switch (Opc) {
816   case CONCAT: Result = "!con"; break;
817   case SHL: Result = "!shl"; break;
818   case SRA: Result = "!sra"; break;
819   case SRL: Result = "!srl"; break;
820   case STRCONCAT: Result = "!strconcat"; break;
821   case REGMATCH: Result = "!regmatch"; break;
822   case NAMECONCAT: 
823     Result = "!nameconcat<" + getType()->getAsString() + ">"; break;
824   }
825   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
826 }
827
828 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
829                            Record *CurRec, MultiClass *CurMultiClass);
830
831 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
832                                RecTy *Type, Record *CurRec,
833                                MultiClass *CurMultiClass) {
834   std::vector<Init *> NewOperands;
835
836   TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
837
838   // If this is a dag, recurse
839   if (TArg && TArg->getType()->getAsString() == "dag") {
840     Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
841                                  CurRec, CurMultiClass);
842     if (Result != 0) {
843       return Result;
844     }
845     else {
846       return 0;
847     }
848   }
849
850   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
851     OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
852
853     if (RHSoo) {
854       Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
855                                        Type, CurRec, CurMultiClass);
856       if (Result != 0) {
857         NewOperands.push_back(Result);
858       }
859       else {
860         NewOperands.push_back(Arg);
861       }
862     }
863     else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
864       NewOperands.push_back(Arg);
865     }
866     else {
867       NewOperands.push_back(RHSo->getOperand(i));
868     }
869   }
870
871   // Now run the operator and use its result as the new leaf
872   OpInit *NewOp = RHSo->clone(NewOperands);
873   Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
874   if (NewVal != NewOp) {
875     delete NewOp;
876     return NewVal;
877   }
878   return 0;
879 }
880
881 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
882                            Record *CurRec, MultiClass *CurMultiClass) {
883   DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
884   ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
885
886   DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
887   ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
888
889   OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
890
891   if (!RHSo) {
892     cerr << "!foreach requires an operator\n";
893     assert(0 && "No operator for !foreach");
894   }
895
896   TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
897
898   if (!LHSt) {
899     cerr << "!foreach requires typed variable\n";
900     assert(0 && "No typed variable for !foreach");
901   }
902
903   if ((MHSd && DagType) || (MHSl && ListType)) {
904     if (MHSd) {
905       Init *Val = MHSd->getOperator();
906       Init *Result = EvaluateOperation(RHSo, LHS, Val,
907                                        Type, CurRec, CurMultiClass);
908       if (Result != 0) {
909         Val = Result;
910       }
911
912       std::vector<std::pair<Init *, std::string> > args;
913       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
914         Init *Arg;
915         std::string ArgName;
916         Arg = MHSd->getArg(i);
917         ArgName = MHSd->getArgName(i);
918
919         // Process args
920         Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
921                                          CurRec, CurMultiClass);
922         if (Result != 0) {
923           Arg = Result;
924         }
925
926         // TODO: Process arg names
927         args.push_back(std::make_pair(Arg, ArgName));
928       }
929
930       return new DagInit(Val, "", args);
931     }
932     if (MHSl) {
933       std::vector<Init *> NewOperands;
934       std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
935
936       for (ListInit::iterator li = NewList.begin(),
937              liend = NewList.end();
938            li != liend;
939            ++li) {
940         Init *Item = *li;
941         NewOperands.clear();
942         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
943           // First, replace the foreach variable with the list item
944           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
945             NewOperands.push_back(Item);
946           }
947           else {
948             NewOperands.push_back(RHSo->getOperand(i));
949           }
950         }
951
952         // Now run the operator and use its result as the new list item
953         OpInit *NewOp = RHSo->clone(NewOperands);
954         Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
955         if (NewItem != NewOp) {
956           *li = NewItem;
957           delete NewOp;
958         }
959       }
960       return new ListInit(NewList, MHSl->getType());
961     }
962   }
963   return 0;
964 }
965
966 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
967   switch (getOpcode()) {
968   default: assert(0 && "Unknown binop");
969   case SUBST: {
970     DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
971     VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
972     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
973
974     DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
975     VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
976     StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
977
978     DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
979     VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
980     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
981
982     if ((LHSd && MHSd && RHSd)
983         || (LHSv && MHSv && RHSv)
984         || (LHSs && MHSs && RHSs)) {
985       if (RHSd) {
986         Record *Val = RHSd->getDef();
987         if (LHSd->getAsString() == RHSd->getAsString()) {
988           Val = MHSd->getDef();
989         }
990         return new DefInit(Val);
991       }
992       if (RHSv) {
993         std::string Val = RHSv->getName();
994         if (LHSv->getAsString() == RHSv->getAsString()) {
995           Val = MHSv->getName();
996         }
997         return new VarInit(Val, getType());
998       }
999       if (RHSs) {
1000         std::string Val = RHSs->getValue();
1001
1002         std::string::size_type found;
1003         do {
1004           found = Val.find(LHSs->getValue());
1005           if (found != std::string::npos) {
1006             Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
1007           }
1008         } while (found != std::string::npos);
1009
1010         return new StringInit(Val);
1011       }
1012     }
1013     break;
1014   }  
1015
1016   case FOREACH: {
1017     Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
1018                                  CurRec, CurMultiClass);
1019     if (Result != 0) {
1020       return Result;
1021     }
1022     break;
1023   }
1024
1025   case IF: {
1026     IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
1027     if (LHSi) {
1028       if (LHSi->getValue()) {
1029         return MHS;
1030       }
1031       else {
1032         return RHS;
1033       }
1034     }
1035     break;
1036   }
1037   }
1038
1039   return this;
1040 }
1041
1042 Init *TernOpInit::resolveReferences(Record &R, const RecordVal *RV) {
1043   Init *lhs = LHS->resolveReferences(R, RV);
1044
1045   if (Opc == IF && lhs != LHS) {
1046     IntInit *Value = dynamic_cast<IntInit*>(lhs);
1047     if (Value != 0) {
1048       // Short-circuit
1049       if (Value->getValue()) {
1050         Init *mhs = MHS->resolveReferences(R, RV);
1051         return (new TernOpInit(getOpcode(), lhs, mhs, RHS, getType()))->Fold(&R, 0);
1052       }
1053       else {
1054         Init *rhs = RHS->resolveReferences(R, RV);
1055         return (new TernOpInit(getOpcode(), lhs, MHS, rhs, getType()))->Fold(&R, 0);
1056       }
1057     }
1058   }
1059   
1060   Init *mhs = MHS->resolveReferences(R, RV);
1061   Init *rhs = RHS->resolveReferences(R, RV);
1062
1063   if (LHS != lhs || MHS != mhs || RHS != rhs)
1064     return (new TernOpInit(getOpcode(), lhs, mhs, rhs, getType()))->Fold(&R, 0);
1065   return Fold(&R, 0);
1066 }
1067
1068 std::string TernOpInit::getAsString() const {
1069   std::string Result;
1070   switch (Opc) {
1071   case SUBST: Result = "!subst"; break;
1072   case FOREACH: Result = "!foreach"; break; 
1073   case IF: Result = "!if"; break; 
1074  }
1075   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " 
1076     + RHS->getAsString() + ")";
1077 }
1078
1079 Init *TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
1080   BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
1081   if (T == 0) return 0;  // Cannot subscript a non-bits variable...
1082   unsigned NumBits = T->getNumBits();
1083
1084   BitsInit *BI = new BitsInit(Bits.size());
1085   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
1086     if (Bits[i] >= NumBits) {
1087       delete BI;
1088       return 0;
1089     }
1090     BI->setBit(i, new VarBitInit(this, Bits[i]));
1091   }
1092   return BI;
1093 }
1094
1095 Init *TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
1096   ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
1097   if (T == 0) return 0;  // Cannot subscript a non-list variable...
1098
1099   if (Elements.size() == 1)
1100     return new VarListElementInit(this, Elements[0]);
1101
1102   std::vector<Init*> ListInits;
1103   ListInits.reserve(Elements.size());
1104   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
1105     ListInits.push_back(new VarListElementInit(this, Elements[i]));
1106   return new ListInit(ListInits, T);
1107 }
1108
1109
1110 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
1111                                    unsigned Bit) {
1112   if (R.isTemplateArg(getName())) return 0;
1113   if (IRV && IRV->getName() != getName()) return 0;
1114
1115   RecordVal *RV = R.getValue(getName());
1116   assert(RV && "Reference to a non-existant variable?");
1117   assert(dynamic_cast<BitsInit*>(RV->getValue()));
1118   BitsInit *BI = (BitsInit*)RV->getValue();
1119
1120   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1121   Init *B = BI->getBit(Bit);
1122
1123   if (!dynamic_cast<UnsetInit*>(B))  // If the bit is not set...
1124     return B;                        // Replace the VarBitInit with it.
1125   return 0;
1126 }
1127
1128 Init *VarInit::resolveListElementReference(Record &R, const RecordVal *IRV,
1129                                            unsigned Elt) {
1130   if (R.isTemplateArg(getName())) return 0;
1131   if (IRV && IRV->getName() != getName()) return 0;
1132
1133   RecordVal *RV = R.getValue(getName());
1134   assert(RV && "Reference to a non-existant variable?");
1135   ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
1136   if (!LI) {
1137     VarInit *VI = dynamic_cast<VarInit*>(RV->getValue());
1138     assert(VI && "Invalid list element!");
1139     return new VarListElementInit(VI, Elt);
1140   }
1141   
1142   if (Elt >= LI->getSize())
1143     return 0;  // Out of range reference.
1144   Init *E = LI->getElement(Elt);
1145   if (!dynamic_cast<UnsetInit*>(E))  // If the element is set
1146     return E;                        // Replace the VarListElementInit with it.
1147   return 0;
1148 }
1149
1150
1151 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
1152   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
1153     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
1154       return RV->getType();
1155   return 0;
1156 }
1157
1158 Init *VarInit::getFieldInit(Record &R, const std::string &FieldName) const {
1159   if (dynamic_cast<RecordRecTy*>(getType()))
1160     if (const RecordVal *RV = R.getValue(VarName)) {
1161       Init *TheInit = RV->getValue();
1162       assert(TheInit != this && "Infinite loop detected!");
1163       if (Init *I = TheInit->getFieldInit(R, FieldName))
1164         return I;
1165       else
1166         return 0;
1167     }
1168   return 0;
1169 }
1170
1171 /// resolveReferences - This method is used by classes that refer to other
1172 /// variables which may not be defined at the time they expression is formed.
1173 /// If a value is set for the variable later, this method will be called on
1174 /// users of the value to allow the value to propagate out.
1175 ///
1176 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) {
1177   if (RecordVal *Val = R.getValue(VarName))
1178     if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1179       return Val->getValue();
1180   return this;
1181 }
1182
1183 std::string VarBitInit::getAsString() const {
1184    return TI->getAsString() + "{" + utostr(Bit) + "}";
1185 }
1186
1187 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) {
1188   if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1189     return I;
1190   return this;
1191 }
1192
1193 std::string VarListElementInit::getAsString() const {
1194   return TI->getAsString() + "[" + utostr(Element) + "]";
1195 }
1196
1197 Init *VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) {
1198   if (Init *I = getVariable()->resolveListElementReference(R, RV,
1199                                                            getElementNum()))
1200     return I;
1201   return this;
1202 }
1203
1204 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
1205                                               unsigned Bit) {
1206   // FIXME: This should be implemented, to support references like:
1207   // bit B = AA[0]{1};
1208   return 0;
1209 }
1210
1211 Init *VarListElementInit::
1212 resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) {
1213   // FIXME: This should be implemented, to support references like:
1214   // int B = AA[0][1];
1215   return 0;
1216 }
1217
1218 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1219   if (const RecordVal *RV = Def->getValue(FieldName))
1220     return RV->getType();
1221   return 0;
1222 }
1223
1224 Init *DefInit::getFieldInit(Record &R, const std::string &FieldName) const {
1225   return Def->getValue(FieldName)->getValue();
1226 }
1227
1228
1229 std::string DefInit::getAsString() const {
1230   return Def->getName();
1231 }
1232
1233 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1234                                      unsigned Bit) {
1235   if (Init *BitsVal = Rec->getFieldInit(R, FieldName))
1236     if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
1237       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1238       Init *B = BI->getBit(Bit);
1239
1240       if (dynamic_cast<BitInit*>(B))  // If the bit is set...
1241         return B;                     // Replace the VarBitInit with it.
1242     }
1243   return 0;
1244 }
1245
1246 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1247                                              unsigned Elt) {
1248   if (Init *ListVal = Rec->getFieldInit(R, FieldName))
1249     if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1250       if (Elt >= LI->getSize()) return 0;
1251       Init *E = LI->getElement(Elt);
1252
1253       if (!dynamic_cast<UnsetInit*>(E))  // If the bit is set...
1254         return E;                  // Replace the VarListElementInit with it.
1255     }
1256   return 0;
1257 }
1258
1259 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) {
1260   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1261
1262   Init *BitsVal = NewRec->getFieldInit(R, FieldName);
1263   if (BitsVal) {
1264     Init *BVR = BitsVal->resolveReferences(R, RV);
1265     return BVR->isComplete() ? BVR : this;
1266   }
1267
1268   if (NewRec != Rec) {
1269     return new FieldInit(NewRec, FieldName);
1270   }
1271   return this;
1272 }
1273
1274 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) {
1275   std::vector<Init*> NewArgs;
1276   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1277     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1278   
1279   Init *Op = Val->resolveReferences(R, RV);
1280   
1281   if (Args != NewArgs || Op != Val)
1282     return new DagInit(Op, "", NewArgs, ArgNames);
1283     
1284   return this;
1285 }
1286
1287
1288 std::string DagInit::getAsString() const {
1289   std::string Result = "(" + Val->getAsString();
1290   if (!ValName.empty())
1291     Result += ":" + ValName;
1292   if (Args.size()) {
1293     Result += " " + Args[0]->getAsString();
1294     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1295     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1296       Result += ", " + Args[i]->getAsString();
1297       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1298     }
1299   }
1300   return Result + ")";
1301 }
1302
1303
1304 //===----------------------------------------------------------------------===//
1305 //    Other implementations
1306 //===----------------------------------------------------------------------===//
1307
1308 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1309   : Name(N), Ty(T), Prefix(P) {
1310   Value = Ty->convertValue(new UnsetInit());
1311   assert(Value && "Cannot create unset value for current type!");
1312 }
1313
1314 void RecordVal::dump() const { cerr << *this; }
1315
1316 void RecordVal::print(std::ostream &OS, bool PrintSem) const {
1317   if (getPrefix()) OS << "field ";
1318   OS << *getType() << " " << getName();
1319
1320   if (getValue())
1321     OS << " = " << *getValue();
1322
1323   if (PrintSem) OS << ";\n";
1324 }
1325
1326 void Record::setName(const std::string &Name) {
1327   if (Records.getDef(getName()) == this) {
1328     Records.removeDef(getName());
1329     this->Name = Name;
1330     Records.addDef(this);
1331   } else {
1332     Records.removeClass(getName());
1333     this->Name = Name;
1334     Records.addClass(this);
1335   }
1336 }
1337
1338 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1339 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1340 /// references.
1341 void Record::resolveReferencesTo(const RecordVal *RV) {
1342   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1343     if (Init *V = Values[i].getValue())
1344       Values[i].setValue(V->resolveReferences(*this, RV));
1345   }
1346 }
1347
1348
1349 void Record::dump() const { cerr << *this; }
1350
1351 std::ostream &llvm::operator<<(std::ostream &OS, const Record &R) {
1352   OS << R.getName();
1353
1354   const std::vector<std::string> &TArgs = R.getTemplateArgs();
1355   if (!TArgs.empty()) {
1356     OS << "<";
1357     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1358       if (i) OS << ", ";
1359       const RecordVal *RV = R.getValue(TArgs[i]);
1360       assert(RV && "Template argument record not found??");
1361       RV->print(OS, false);
1362     }
1363     OS << ">";
1364   }
1365
1366   OS << " {";
1367   const std::vector<Record*> &SC = R.getSuperClasses();
1368   if (!SC.empty()) {
1369     OS << "\t//";
1370     for (unsigned i = 0, e = SC.size(); i != e; ++i)
1371       OS << " " << SC[i]->getName();
1372   }
1373   OS << "\n";
1374
1375   const std::vector<RecordVal> &Vals = R.getValues();
1376   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1377     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1378       OS << Vals[i];
1379   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1380     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1381       OS << Vals[i];
1382
1383   return OS << "}\n";
1384 }
1385
1386 /// getValueInit - Return the initializer for a value with the specified name,
1387 /// or throw an exception if the field does not exist.
1388 ///
1389 Init *Record::getValueInit(const std::string &FieldName) const {
1390   const RecordVal *R = getValue(FieldName);
1391   if (R == 0 || R->getValue() == 0)
1392     throw "Record `" + getName() + "' does not have a field named `" +
1393       FieldName + "'!\n";
1394   return R->getValue();
1395 }
1396
1397
1398 /// getValueAsString - This method looks up the specified field and returns its
1399 /// value as a string, throwing an exception if the field does not exist or if
1400 /// the value is not a string.
1401 ///
1402 std::string Record::getValueAsString(const std::string &FieldName) const {
1403   const RecordVal *R = getValue(FieldName);
1404   if (R == 0 || R->getValue() == 0)
1405     throw "Record `" + getName() + "' does not have a field named `" +
1406           FieldName + "'!\n";
1407
1408   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
1409     return SI->getValue();
1410   throw "Record `" + getName() + "', field `" + FieldName +
1411         "' does not have a string initializer!";
1412 }
1413
1414 /// getValueAsBitsInit - This method looks up the specified field and returns
1415 /// its value as a BitsInit, throwing an exception if the field does not exist
1416 /// or if the value is not the right type.
1417 ///
1418 BitsInit *Record::getValueAsBitsInit(const std::string &FieldName) const {
1419   const RecordVal *R = getValue(FieldName);
1420   if (R == 0 || R->getValue() == 0)
1421     throw "Record `" + getName() + "' does not have a field named `" +
1422           FieldName + "'!\n";
1423
1424   if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1425     return BI;
1426   throw "Record `" + getName() + "', field `" + FieldName +
1427         "' does not have a BitsInit initializer!";
1428 }
1429
1430 /// getValueAsListInit - This method looks up the specified field and returns
1431 /// its value as a ListInit, throwing an exception if the field does not exist
1432 /// or if the value is not the right type.
1433 ///
1434 ListInit *Record::getValueAsListInit(const std::string &FieldName) const {
1435   const RecordVal *R = getValue(FieldName);
1436   if (R == 0 || R->getValue() == 0)
1437     throw "Record `" + getName() + "' does not have a field named `" +
1438           FieldName + "'!\n";
1439
1440   if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1441     return LI;
1442   throw "Record `" + getName() + "', field `" + FieldName +
1443         "' does not have a list initializer!";
1444 }
1445
1446 /// getValueAsListOfDefs - This method looks up the specified field and returns
1447 /// its value as a vector of records, throwing an exception if the field does
1448 /// not exist or if the value is not the right type.
1449 ///
1450 std::vector<Record*> 
1451 Record::getValueAsListOfDefs(const std::string &FieldName) const {
1452   ListInit *List = getValueAsListInit(FieldName);
1453   std::vector<Record*> Defs;
1454   for (unsigned i = 0; i < List->getSize(); i++) {
1455     if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1456       Defs.push_back(DI->getDef());
1457     } else {
1458       throw "Record `" + getName() + "', field `" + FieldName +
1459             "' list is not entirely DefInit!";
1460     }
1461   }
1462   return Defs;
1463 }
1464
1465 /// getValueAsInt - This method looks up the specified field and returns its
1466 /// value as an int64_t, throwing an exception if the field does not exist or if
1467 /// the value is not the right type.
1468 ///
1469 int64_t Record::getValueAsInt(const std::string &FieldName) const {
1470   const RecordVal *R = getValue(FieldName);
1471   if (R == 0 || R->getValue() == 0)
1472     throw "Record `" + getName() + "' does not have a field named `" +
1473           FieldName + "'!\n";
1474
1475   if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1476     return II->getValue();
1477   throw "Record `" + getName() + "', field `" + FieldName +
1478         "' does not have an int initializer!";
1479 }
1480
1481 /// getValueAsListOfInts - This method looks up the specified field and returns
1482 /// its value as a vector of integers, throwing an exception if the field does
1483 /// not exist or if the value is not the right type.
1484 ///
1485 std::vector<int64_t> 
1486 Record::getValueAsListOfInts(const std::string &FieldName) const {
1487   ListInit *List = getValueAsListInit(FieldName);
1488   std::vector<int64_t> Ints;
1489   for (unsigned i = 0; i < List->getSize(); i++) {
1490     if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1491       Ints.push_back(II->getValue());
1492     } else {
1493       throw "Record `" + getName() + "', field `" + FieldName +
1494             "' does not have a list of ints initializer!";
1495     }
1496   }
1497   return Ints;
1498 }
1499
1500 /// getValueAsDef - This method looks up the specified field and returns its
1501 /// value as a Record, throwing an exception if the field does not exist or if
1502 /// the value is not the right type.
1503 ///
1504 Record *Record::getValueAsDef(const std::string &FieldName) const {
1505   const RecordVal *R = getValue(FieldName);
1506   if (R == 0 || R->getValue() == 0)
1507     throw "Record `" + getName() + "' does not have a field named `" +
1508       FieldName + "'!\n";
1509
1510   if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1511     return DI->getDef();
1512   throw "Record `" + getName() + "', field `" + FieldName +
1513         "' does not have a def initializer!";
1514 }
1515
1516 /// getValueAsBit - This method looks up the specified field and returns its
1517 /// value as a bit, throwing an exception if the field does not exist or if
1518 /// the value is not the right type.
1519 ///
1520 bool Record::getValueAsBit(const std::string &FieldName) const {
1521   const RecordVal *R = getValue(FieldName);
1522   if (R == 0 || R->getValue() == 0)
1523     throw "Record `" + getName() + "' does not have a field named `" +
1524       FieldName + "'!\n";
1525
1526   if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1527     return BI->getValue();
1528   throw "Record `" + getName() + "', field `" + FieldName +
1529         "' does not have a bit initializer!";
1530 }
1531
1532 /// getValueAsDag - This method looks up the specified field and returns its
1533 /// value as an Dag, throwing an exception if the field does not exist or if
1534 /// the value is not the right type.
1535 ///
1536 DagInit *Record::getValueAsDag(const std::string &FieldName) const {
1537   const RecordVal *R = getValue(FieldName);
1538   if (R == 0 || R->getValue() == 0)
1539     throw "Record `" + getName() + "' does not have a field named `" +
1540       FieldName + "'!\n";
1541
1542   if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1543     return DI;
1544   throw "Record `" + getName() + "', field `" + FieldName +
1545         "' does not have a dag initializer!";
1546 }
1547
1548 std::string Record::getValueAsCode(const std::string &FieldName) const {
1549   const RecordVal *R = getValue(FieldName);
1550   if (R == 0 || R->getValue() == 0)
1551     throw "Record `" + getName() + "' does not have a field named `" +
1552       FieldName + "'!\n";
1553   
1554   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
1555     return CI->getValue();
1556   throw "Record `" + getName() + "', field `" + FieldName +
1557     "' does not have a code initializer!";
1558 }
1559
1560
1561 void MultiClass::dump() const {
1562   cerr << "Record:\n";
1563   Rec.dump();
1564   
1565   cerr << "Defs:\n";
1566   for (RecordVector::const_iterator r = DefPrototypes.begin(),
1567          rend = DefPrototypes.end();
1568        r != rend;
1569        ++r) {
1570     (*r)->dump();
1571   }
1572 }
1573
1574
1575 void RecordKeeper::dump() const { cerr << *this; }
1576
1577 std::ostream &llvm::operator<<(std::ostream &OS, const RecordKeeper &RK) {
1578   OS << "------------- Classes -----------------\n";
1579   const std::map<std::string, Record*> &Classes = RK.getClasses();
1580   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1581          E = Classes.end(); I != E; ++I)
1582     OS << "class " << *I->second;
1583
1584   OS << "------------- Defs -----------------\n";
1585   const std::map<std::string, Record*> &Defs = RK.getDefs();
1586   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1587          E = Defs.end(); I != E; ++I)
1588     OS << "def " << *I->second;
1589   return OS;
1590 }
1591
1592
1593 /// getAllDerivedDefinitions - This method returns all concrete definitions
1594 /// that derive from the specified class name.  If a class with the specified
1595 /// name does not exist, an error is printed and true is returned.
1596 std::vector<Record*>
1597 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1598   Record *Class = Records.getClass(ClassName);
1599   if (!Class)
1600     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1601
1602   std::vector<Record*> Defs;
1603   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1604          E = getDefs().end(); I != E; ++I)
1605     if (I->second->isSubClassOf(Class))
1606       Defs.push_back(I->second);
1607
1608   return Defs;
1609 }
1610