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