ade17026fbfb2203fb6474a833c3451bed042e24
[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   }
524   return this;
525 }
526
527 Init *UnOpInit::resolveReferences(Record &R, const RecordVal *RV) {
528   Init *lhs = LHS->resolveReferences(R, RV);
529   
530   if (LHS != lhs)
531     return (new UnOpInit(getOpcode(), lhs, getType()))->Fold(&R, 0);
532   return Fold(&R, 0);
533 }
534
535 std::string UnOpInit::getAsString() const {
536   std::string Result;
537   switch (Opc) {
538   case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
539   }
540   return Result + "(" + LHS->getAsString() + ")";
541 }
542
543 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
544   switch (getOpcode()) {
545   default: assert(0 && "Unknown binop");
546   case CONCAT: {
547     DagInit *LHSs = dynamic_cast<DagInit*>(LHS);
548     DagInit *RHSs = dynamic_cast<DagInit*>(RHS);
549     if (LHSs && RHSs) {
550       DefInit *LOp = dynamic_cast<DefInit*>(LHSs->getOperator());
551       DefInit *ROp = dynamic_cast<DefInit*>(RHSs->getOperator());
552       if (LOp->getDef() != ROp->getDef()) {
553         bool LIsOps =
554           LOp->getDef()->getName() == "outs" ||
555           LOp->getDef()->getName() != "ins" ||
556           LOp->getDef()->getName() != "defs";
557         bool RIsOps =
558           ROp->getDef()->getName() == "outs" ||
559           ROp->getDef()->getName() != "ins" ||
560           ROp->getDef()->getName() != "defs";
561         if (!LIsOps || !RIsOps)
562           throw "Concated Dag operators do not match!";
563       }
564       std::vector<Init*> Args;
565       std::vector<std::string> ArgNames;
566       for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
567         Args.push_back(LHSs->getArg(i));
568         ArgNames.push_back(LHSs->getArgName(i));
569       }
570       for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
571         Args.push_back(RHSs->getArg(i));
572         ArgNames.push_back(RHSs->getArgName(i));
573       }
574       return new DagInit(LHSs->getOperator(), "", Args, ArgNames);
575     }
576     break;
577   }
578   case STRCONCAT: {
579     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
580     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
581     if (LHSs && RHSs)
582       return new StringInit(LHSs->getValue() + RHSs->getValue());
583     break;
584   }
585   case NAMECONCAT: {
586     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
587     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
588     if (LHSs && RHSs) {
589       std::string Name(LHSs->getValue() + RHSs->getValue());
590
591       // From TGParser::ParseIDValue
592       if (CurRec) {
593         if (const RecordVal *RV = CurRec->getValue(Name)) {
594           if (RV->getType() != getType()) {
595             throw "type mismatch in nameconcat";
596           }
597           return new VarInit(Name, RV->getType());
598         }
599         
600         std::string TemplateArgName = CurRec->getName()+":"+Name;
601         if (CurRec->isTemplateArg(TemplateArgName)) {
602           const RecordVal *RV = CurRec->getValue(TemplateArgName);
603           assert(RV && "Template arg doesn't exist??");
604
605           if (RV->getType() != getType()) {
606             throw "type mismatch in nameconcat";
607           }
608
609           return new VarInit(TemplateArgName, RV->getType());
610         }
611       }
612
613       if (CurMultiClass) {
614         std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
615         if (CurMultiClass->Rec.isTemplateArg(MCName)) {
616           const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
617           assert(RV && "Template arg doesn't exist??");
618
619           if (RV->getType() != getType()) {
620             throw "type mismatch in nameconcat";
621           }
622           
623           return new VarInit(MCName, RV->getType());
624         }
625       }
626
627       if (Record *D = Records.getDef(Name))
628         return new DefInit(D);
629
630       cerr << "Variable not defined: '" + Name + "'\n";
631       assert(0 && "Variable not found");
632       return 0;
633     }
634     break;
635   }
636   case SHL:
637   case SRA:
638   case SRL: {
639     IntInit *LHSi = dynamic_cast<IntInit*>(LHS);
640     IntInit *RHSi = dynamic_cast<IntInit*>(RHS);
641     if (LHSi && RHSi) {
642       int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
643       int64_t Result;
644       switch (getOpcode()) {
645       default: assert(0 && "Bad opcode!");
646       case SHL: Result = LHSv << RHSv; break;
647       case SRA: Result = LHSv >> RHSv; break;
648       case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
649       }
650       return new IntInit(Result);
651     }
652     break;
653   }
654   }
655   return this;
656 }
657
658 Init *BinOpInit::resolveReferences(Record &R, const RecordVal *RV) {
659   Init *lhs = LHS->resolveReferences(R, RV);
660   Init *rhs = RHS->resolveReferences(R, RV);
661   
662   if (LHS != lhs || RHS != rhs)
663     return (new BinOpInit(getOpcode(), lhs, rhs, getType()))->Fold(&R, 0);
664   return Fold(&R, 0);
665 }
666
667 std::string BinOpInit::getAsString() const {
668   std::string Result;
669   switch (Opc) {
670   case CONCAT: Result = "!con"; break;
671   case SHL: Result = "!shl"; break;
672   case SRA: Result = "!sra"; break;
673   case SRL: Result = "!srl"; break;
674   case STRCONCAT: Result = "!strconcat"; break;
675   case NAMECONCAT: 
676     Result = "!nameconcat<" + getType()->getAsString() + ">"; break;
677   }
678   return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
679 }
680
681 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
682                            Record *CurRec, MultiClass *CurMultiClass);
683
684 static Init *EvaluateOperation(OpInit *RHSo, Init *LHS, Init *Arg,
685                                RecTy *Type, Record *CurRec,
686                                MultiClass *CurMultiClass) {
687   std::vector<Init *> NewOperands;
688
689   TypedInit *TArg = dynamic_cast<TypedInit*>(Arg);
690
691   // If this is a dag, recurse
692   if (TArg && TArg->getType()->getAsString() == "dag") {
693     Init *Result = ForeachHelper(LHS, Arg, RHSo, Type,
694                                  CurRec, CurMultiClass);
695     if (Result != 0) {
696       return Result;
697     }
698     else {
699       return 0;
700     }
701   }
702
703   for (int i = 0; i < RHSo->getNumOperands(); ++i) {
704     OpInit *RHSoo = dynamic_cast<OpInit*>(RHSo->getOperand(i));
705
706     if (RHSoo) {
707       Init *Result = EvaluateOperation(RHSoo, LHS, Arg,
708                                        Type, CurRec, CurMultiClass);
709       if (Result != 0) {
710         NewOperands.push_back(Result);
711       }
712       else {
713         NewOperands.push_back(Arg);
714       }
715     }
716     else if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
717       NewOperands.push_back(Arg);
718     }
719     else {
720       NewOperands.push_back(RHSo->getOperand(i));
721     }
722   }
723
724   // Now run the operator and use its result as the new leaf
725   OpInit *NewOp = RHSo->clone(NewOperands);
726   Init *NewVal = NewOp->Fold(CurRec, CurMultiClass);
727   if (NewVal != NewOp) {
728     delete NewOp;
729     return NewVal;
730   }
731   return 0;
732 }
733
734 static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
735                            Record *CurRec, MultiClass *CurMultiClass) {
736   DagInit *MHSd = dynamic_cast<DagInit*>(MHS);
737   ListInit *MHSl = dynamic_cast<ListInit*>(MHS);
738
739   DagRecTy *DagType = dynamic_cast<DagRecTy*>(Type);
740   ListRecTy *ListType = dynamic_cast<ListRecTy*>(Type);
741
742   OpInit *RHSo = dynamic_cast<OpInit*>(RHS);
743
744   if (!RHSo) {
745     cerr << "!foreach requires an operator\n";
746     assert(0 && "No operator for !foreach");
747   }
748
749   TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
750
751   if (!LHSt) {
752     cerr << "!foreach requires typed variable\n";
753     assert(0 && "No typed variable for !foreach");
754   }
755
756   if (MHSd && DagType || MHSl && ListType) {
757     if (MHSd) {
758       Init *Val = MHSd->getOperator();
759       Init *Result = EvaluateOperation(RHSo, LHS, Val,
760                                        Type, CurRec, CurMultiClass);
761       if (Result != 0) {
762         Val = Result;
763       }
764
765       std::vector<std::pair<Init *, std::string> > args;
766       for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
767         Init *Arg;
768         std::string ArgName;
769         Arg = MHSd->getArg(i);
770         ArgName = MHSd->getArgName(i);
771
772         // Process args
773         Init *Result = EvaluateOperation(RHSo, LHS, Arg, Type,
774                                          CurRec, CurMultiClass);
775         if (Result != 0) {
776           Arg = Result;
777         }
778
779         // TODO: Process arg names
780         args.push_back(std::make_pair(Arg, ArgName));
781       }
782
783       return new DagInit(Val, "", args);
784     }
785     if (MHSl) {
786       std::vector<Init *> NewOperands;
787       std::vector<Init *> NewList(MHSl->begin(), MHSl->end());
788
789       for (ListInit::iterator li = NewList.begin(),
790              liend = NewList.end();
791            li != liend;
792            ++li) {
793         Init *Item = *li;
794         NewOperands.clear();
795         for(int i = 0; i < RHSo->getNumOperands(); ++i) {
796           // First, replace the foreach variable with the list item
797           if (LHS->getAsString() == RHSo->getOperand(i)->getAsString()) {
798             NewOperands.push_back(Item);
799           }
800           else {
801             NewOperands.push_back(RHSo->getOperand(i));
802           }
803         }
804
805         // Now run the operator and use its result as the new list item
806         OpInit *NewOp = RHSo->clone(NewOperands);
807         Init *NewItem = NewOp->Fold(CurRec, CurMultiClass);
808         if (NewItem != NewOp) {
809           *li = NewItem;
810           delete NewOp;
811         }
812       }
813       return new ListInit(NewList);
814     }
815   }
816   return 0;
817 }
818
819 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) {
820   switch (getOpcode()) {
821   default: assert(0 && "Unknown binop");
822   case SUBST: {
823     DefInit *LHSd = dynamic_cast<DefInit*>(LHS);
824     VarInit *LHSv = dynamic_cast<VarInit*>(LHS);
825     StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
826
827     DefInit *MHSd = dynamic_cast<DefInit*>(MHS);
828     VarInit *MHSv = dynamic_cast<VarInit*>(MHS);
829     StringInit *MHSs = dynamic_cast<StringInit*>(MHS);
830
831     DefInit *RHSd = dynamic_cast<DefInit*>(RHS);
832     VarInit *RHSv = dynamic_cast<VarInit*>(RHS);
833     StringInit *RHSs = dynamic_cast<StringInit*>(RHS);
834
835     if ((LHSd && MHSd && RHSd)
836         || (LHSv && MHSv && RHSv)
837         || (LHSs && MHSs && RHSs)) {
838       if (RHSd) {
839         Record *Val = RHSd->getDef();
840         if (LHSd->getAsString() == RHSd->getAsString()) {
841           Val = MHSd->getDef();
842         }
843         return new DefInit(Val);
844       }
845       if (RHSv) {
846         std::string Val = RHSv->getName();
847         if (LHSv->getAsString() == RHSv->getAsString()) {
848           Val = MHSv->getName();
849         }
850         return new VarInit(Val, getType());
851       }
852       if (RHSs) {
853         std::string Val = RHSs->getValue();
854
855         std::string::size_type found;
856         do {
857           found = Val.find(LHSs->getValue());
858           if (found != std::string::npos) {
859             Val.replace(found, LHSs->getValue().size(), MHSs->getValue());
860           }
861         } while (found != std::string::npos);
862
863         return new StringInit(Val);
864       }
865     }
866     break;
867   }  
868
869   case FOREACH: {
870     Init *Result = ForeachHelper(LHS, MHS, RHS, getType(),
871                                  CurRec, CurMultiClass);
872     if (Result != 0) {
873       return Result;
874     }
875     break;
876   }
877   }
878
879   return this;
880 }
881
882 Init *TernOpInit::resolveReferences(Record &R, const RecordVal *RV) {
883   Init *lhs = LHS->resolveReferences(R, RV);
884   Init *mhs = MHS->resolveReferences(R, RV);
885   Init *rhs = RHS->resolveReferences(R, RV);
886   
887   if (LHS != lhs || MHS != mhs || RHS != rhs)
888     return (new TernOpInit(getOpcode(), lhs, mhs, rhs, getType()))->Fold(&R, 0);
889   return Fold(&R, 0);
890 }
891
892 std::string TernOpInit::getAsString() const {
893   std::string Result;
894   switch (Opc) {
895   case SUBST: Result = "!subst"; break;
896   case FOREACH: Result = "!foreach"; break; 
897  }
898   return Result + "(" + LHS->getAsString() + ", " + MHS->getAsString() + ", " 
899     + RHS->getAsString() + ")";
900 }
901
902 Init *TypedInit::convertInitializerBitRange(const std::vector<unsigned> &Bits) {
903   BitsRecTy *T = dynamic_cast<BitsRecTy*>(getType());
904   if (T == 0) return 0;  // Cannot subscript a non-bits variable...
905   unsigned NumBits = T->getNumBits();
906
907   BitsInit *BI = new BitsInit(Bits.size());
908   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
909     if (Bits[i] >= NumBits) {
910       delete BI;
911       return 0;
912     }
913     BI->setBit(i, new VarBitInit(this, Bits[i]));
914   }
915   return BI;
916 }
917
918 Init *TypedInit::convertInitListSlice(const std::vector<unsigned> &Elements) {
919   ListRecTy *T = dynamic_cast<ListRecTy*>(getType());
920   if (T == 0) return 0;  // Cannot subscript a non-list variable...
921
922   if (Elements.size() == 1)
923     return new VarListElementInit(this, Elements[0]);
924
925   std::vector<Init*> ListInits;
926   ListInits.reserve(Elements.size());
927   for (unsigned i = 0, e = Elements.size(); i != e; ++i)
928     ListInits.push_back(new VarListElementInit(this, Elements[i]));
929   return new ListInit(ListInits);
930 }
931
932
933 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
934                                    unsigned Bit) {
935   if (R.isTemplateArg(getName())) return 0;
936   if (IRV && IRV->getName() != getName()) return 0;
937
938   RecordVal *RV = R.getValue(getName());
939   assert(RV && "Reference to a non-existant variable?");
940   assert(dynamic_cast<BitsInit*>(RV->getValue()));
941   BitsInit *BI = (BitsInit*)RV->getValue();
942
943   assert(Bit < BI->getNumBits() && "Bit reference out of range!");
944   Init *B = BI->getBit(Bit);
945
946   if (!dynamic_cast<UnsetInit*>(B))  // If the bit is not set...
947     return B;                        // Replace the VarBitInit with it.
948   return 0;
949 }
950
951 Init *VarInit::resolveListElementReference(Record &R, const RecordVal *IRV,
952                                            unsigned Elt) {
953   if (R.isTemplateArg(getName())) return 0;
954   if (IRV && IRV->getName() != getName()) return 0;
955
956   RecordVal *RV = R.getValue(getName());
957   assert(RV && "Reference to a non-existant variable?");
958   ListInit *LI = dynamic_cast<ListInit*>(RV->getValue());
959   if (!LI) {
960     VarInit *VI = dynamic_cast<VarInit*>(RV->getValue());
961     assert(VI && "Invalid list element!");
962     return new VarListElementInit(VI, Elt);
963   }
964   
965   if (Elt >= LI->getSize())
966     return 0;  // Out of range reference.
967   Init *E = LI->getElement(Elt);
968   if (!dynamic_cast<UnsetInit*>(E))  // If the element is set
969     return E;                        // Replace the VarListElementInit with it.
970   return 0;
971 }
972
973
974 RecTy *VarInit::getFieldType(const std::string &FieldName) const {
975   if (RecordRecTy *RTy = dynamic_cast<RecordRecTy*>(getType()))
976     if (const RecordVal *RV = RTy->getRecord()->getValue(FieldName))
977       return RV->getType();
978   return 0;
979 }
980
981 Init *VarInit::getFieldInit(Record &R, const std::string &FieldName) const {
982   if (dynamic_cast<RecordRecTy*>(getType()))
983     if (const RecordVal *RV = R.getValue(VarName)) {
984       Init *TheInit = RV->getValue();
985       assert(TheInit != this && "Infinite loop detected!");
986       if (Init *I = TheInit->getFieldInit(R, FieldName))
987         return I;
988       else
989         return 0;
990     }
991   return 0;
992 }
993
994 /// resolveReferences - This method is used by classes that refer to other
995 /// variables which may not be defined at the time they expression is formed.
996 /// If a value is set for the variable later, this method will be called on
997 /// users of the value to allow the value to propagate out.
998 ///
999 Init *VarInit::resolveReferences(Record &R, const RecordVal *RV) {
1000   if (RecordVal *Val = R.getValue(VarName))
1001     if (RV == Val || (RV == 0 && !dynamic_cast<UnsetInit*>(Val->getValue())))
1002       return Val->getValue();
1003   return this;
1004 }
1005
1006 std::string VarBitInit::getAsString() const {
1007    return TI->getAsString() + "{" + utostr(Bit) + "}";
1008 }
1009
1010 Init *VarBitInit::resolveReferences(Record &R, const RecordVal *RV) {
1011   if (Init *I = getVariable()->resolveBitReference(R, RV, getBitNum()))
1012     return I;
1013   return this;
1014 }
1015
1016 std::string VarListElementInit::getAsString() const {
1017   return TI->getAsString() + "[" + utostr(Element) + "]";
1018 }
1019
1020 Init *VarListElementInit::resolveReferences(Record &R, const RecordVal *RV) {
1021   if (Init *I = getVariable()->resolveListElementReference(R, RV,
1022                                                            getElementNum()))
1023     return I;
1024   return this;
1025 }
1026
1027 Init *VarListElementInit::resolveBitReference(Record &R, const RecordVal *RV,
1028                                               unsigned Bit) {
1029   // FIXME: This should be implemented, to support references like:
1030   // bit B = AA[0]{1};
1031   return 0;
1032 }
1033
1034 Init *VarListElementInit::
1035 resolveListElementReference(Record &R, const RecordVal *RV, unsigned Elt) {
1036   // FIXME: This should be implemented, to support references like:
1037   // int B = AA[0][1];
1038   return 0;
1039 }
1040
1041 RecTy *DefInit::getFieldType(const std::string &FieldName) const {
1042   if (const RecordVal *RV = Def->getValue(FieldName))
1043     return RV->getType();
1044   return 0;
1045 }
1046
1047 Init *DefInit::getFieldInit(Record &R, const std::string &FieldName) const {
1048   return Def->getValue(FieldName)->getValue();
1049 }
1050
1051
1052 std::string DefInit::getAsString() const {
1053   return Def->getName();
1054 }
1055
1056 Init *FieldInit::resolveBitReference(Record &R, const RecordVal *RV,
1057                                      unsigned Bit) {
1058   if (Init *BitsVal = Rec->getFieldInit(R, FieldName))
1059     if (BitsInit *BI = dynamic_cast<BitsInit*>(BitsVal)) {
1060       assert(Bit < BI->getNumBits() && "Bit reference out of range!");
1061       Init *B = BI->getBit(Bit);
1062
1063       if (dynamic_cast<BitInit*>(B))  // If the bit is set...
1064         return B;                     // Replace the VarBitInit with it.
1065     }
1066   return 0;
1067 }
1068
1069 Init *FieldInit::resolveListElementReference(Record &R, const RecordVal *RV,
1070                                              unsigned Elt) {
1071   if (Init *ListVal = Rec->getFieldInit(R, FieldName))
1072     if (ListInit *LI = dynamic_cast<ListInit*>(ListVal)) {
1073       if (Elt >= LI->getSize()) return 0;
1074       Init *E = LI->getElement(Elt);
1075
1076       if (!dynamic_cast<UnsetInit*>(E))  // If the bit is set...
1077         return E;                  // Replace the VarListElementInit with it.
1078     }
1079   return 0;
1080 }
1081
1082 Init *FieldInit::resolveReferences(Record &R, const RecordVal *RV) {
1083   Init *NewRec = RV ? Rec->resolveReferences(R, RV) : Rec;
1084
1085   Init *BitsVal = NewRec->getFieldInit(R, FieldName);
1086   if (BitsVal) {
1087     Init *BVR = BitsVal->resolveReferences(R, RV);
1088     return BVR->isComplete() ? BVR : this;
1089   }
1090
1091   if (NewRec != Rec) {
1092     return new FieldInit(NewRec, FieldName);
1093   }
1094   return this;
1095 }
1096
1097 Init *DagInit::resolveReferences(Record &R, const RecordVal *RV) {
1098   std::vector<Init*> NewArgs;
1099   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1100     NewArgs.push_back(Args[i]->resolveReferences(R, RV));
1101   
1102   Init *Op = Val->resolveReferences(R, RV);
1103   
1104   if (Args != NewArgs || Op != Val)
1105     return new DagInit(Op, "", NewArgs, ArgNames);
1106     
1107   return this;
1108 }
1109
1110
1111 std::string DagInit::getAsString() const {
1112   std::string Result = "(" + Val->getAsString();
1113   if (!ValName.empty())
1114     Result += ":" + ValName;
1115   if (Args.size()) {
1116     Result += " " + Args[0]->getAsString();
1117     if (!ArgNames[0].empty()) Result += ":$" + ArgNames[0];
1118     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
1119       Result += ", " + Args[i]->getAsString();
1120       if (!ArgNames[i].empty()) Result += ":$" + ArgNames[i];
1121     }
1122   }
1123   return Result + ")";
1124 }
1125
1126
1127 //===----------------------------------------------------------------------===//
1128 //    Other implementations
1129 //===----------------------------------------------------------------------===//
1130
1131 RecordVal::RecordVal(const std::string &N, RecTy *T, unsigned P)
1132   : Name(N), Ty(T), Prefix(P) {
1133   Value = Ty->convertValue(new UnsetInit());
1134   assert(Value && "Cannot create unset value for current type!");
1135 }
1136
1137 void RecordVal::dump() const { cerr << *this; }
1138
1139 void RecordVal::print(std::ostream &OS, bool PrintSem) const {
1140   if (getPrefix()) OS << "field ";
1141   OS << *getType() << " " << getName();
1142
1143   if (getValue())
1144     OS << " = " << *getValue();
1145
1146   if (PrintSem) OS << ";\n";
1147 }
1148
1149 void Record::setName(const std::string &Name) {
1150   if (Records.getDef(getName()) == this) {
1151     Records.removeDef(getName());
1152     this->Name = Name;
1153     Records.addDef(this);
1154   } else {
1155     Records.removeClass(getName());
1156     this->Name = Name;
1157     Records.addClass(this);
1158   }
1159 }
1160
1161 /// resolveReferencesTo - If anything in this record refers to RV, replace the
1162 /// reference to RV with the RHS of RV.  If RV is null, we resolve all possible
1163 /// references.
1164 void Record::resolveReferencesTo(const RecordVal *RV) {
1165   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1166     if (Init *V = Values[i].getValue())
1167       Values[i].setValue(V->resolveReferences(*this, RV));
1168   }
1169 }
1170
1171
1172 void Record::dump() const { cerr << *this; }
1173
1174 std::ostream &llvm::operator<<(std::ostream &OS, const Record &R) {
1175   OS << R.getName();
1176
1177   const std::vector<std::string> &TArgs = R.getTemplateArgs();
1178   if (!TArgs.empty()) {
1179     OS << "<";
1180     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1181       if (i) OS << ", ";
1182       const RecordVal *RV = R.getValue(TArgs[i]);
1183       assert(RV && "Template argument record not found??");
1184       RV->print(OS, false);
1185     }
1186     OS << ">";
1187   }
1188
1189   OS << " {";
1190   const std::vector<Record*> &SC = R.getSuperClasses();
1191   if (!SC.empty()) {
1192     OS << "\t//";
1193     for (unsigned i = 0, e = SC.size(); i != e; ++i)
1194       OS << " " << SC[i]->getName();
1195   }
1196   OS << "\n";
1197
1198   const std::vector<RecordVal> &Vals = R.getValues();
1199   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1200     if (Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1201       OS << Vals[i];
1202   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
1203     if (!Vals[i].getPrefix() && !R.isTemplateArg(Vals[i].getName()))
1204       OS << Vals[i];
1205
1206   return OS << "}\n";
1207 }
1208
1209 /// getValueInit - Return the initializer for a value with the specified name,
1210 /// or throw an exception if the field does not exist.
1211 ///
1212 Init *Record::getValueInit(const std::string &FieldName) const {
1213   const RecordVal *R = getValue(FieldName);
1214   if (R == 0 || R->getValue() == 0)
1215     throw "Record `" + getName() + "' does not have a field named `" +
1216       FieldName + "'!\n";
1217   return R->getValue();
1218 }
1219
1220
1221 /// getValueAsString - This method looks up the specified field and returns its
1222 /// value as a string, throwing an exception if the field does not exist or if
1223 /// the value is not a string.
1224 ///
1225 std::string Record::getValueAsString(const std::string &FieldName) const {
1226   const RecordVal *R = getValue(FieldName);
1227   if (R == 0 || R->getValue() == 0)
1228     throw "Record `" + getName() + "' does not have a field named `" +
1229           FieldName + "'!\n";
1230
1231   if (const StringInit *SI = dynamic_cast<const StringInit*>(R->getValue()))
1232     return SI->getValue();
1233   throw "Record `" + getName() + "', field `" + FieldName +
1234         "' does not have a string initializer!";
1235 }
1236
1237 /// getValueAsBitsInit - This method looks up the specified field and returns
1238 /// its value as a BitsInit, throwing an exception if the field does not exist
1239 /// or if the value is not the right type.
1240 ///
1241 BitsInit *Record::getValueAsBitsInit(const std::string &FieldName) const {
1242   const RecordVal *R = getValue(FieldName);
1243   if (R == 0 || R->getValue() == 0)
1244     throw "Record `" + getName() + "' does not have a field named `" +
1245           FieldName + "'!\n";
1246
1247   if (BitsInit *BI = dynamic_cast<BitsInit*>(R->getValue()))
1248     return BI;
1249   throw "Record `" + getName() + "', field `" + FieldName +
1250         "' does not have a BitsInit initializer!";
1251 }
1252
1253 /// getValueAsListInit - This method looks up the specified field and returns
1254 /// its value as a ListInit, throwing an exception if the field does not exist
1255 /// or if the value is not the right type.
1256 ///
1257 ListInit *Record::getValueAsListInit(const std::string &FieldName) const {
1258   const RecordVal *R = getValue(FieldName);
1259   if (R == 0 || R->getValue() == 0)
1260     throw "Record `" + getName() + "' does not have a field named `" +
1261           FieldName + "'!\n";
1262
1263   if (ListInit *LI = dynamic_cast<ListInit*>(R->getValue()))
1264     return LI;
1265   throw "Record `" + getName() + "', field `" + FieldName +
1266         "' does not have a list initializer!";
1267 }
1268
1269 /// getValueAsListOfDefs - This method looks up the specified field and returns
1270 /// its value as a vector of records, throwing an exception if the field does
1271 /// not exist or if the value is not the right type.
1272 ///
1273 std::vector<Record*> 
1274 Record::getValueAsListOfDefs(const std::string &FieldName) const {
1275   ListInit *List = getValueAsListInit(FieldName);
1276   std::vector<Record*> Defs;
1277   for (unsigned i = 0; i < List->getSize(); i++) {
1278     if (DefInit *DI = dynamic_cast<DefInit*>(List->getElement(i))) {
1279       Defs.push_back(DI->getDef());
1280     } else {
1281       throw "Record `" + getName() + "', field `" + FieldName +
1282             "' list is not entirely DefInit!";
1283     }
1284   }
1285   return Defs;
1286 }
1287
1288 /// getValueAsInt - This method looks up the specified field and returns its
1289 /// value as an int64_t, throwing an exception if the field does not exist or if
1290 /// the value is not the right type.
1291 ///
1292 int64_t Record::getValueAsInt(const std::string &FieldName) const {
1293   const RecordVal *R = getValue(FieldName);
1294   if (R == 0 || R->getValue() == 0)
1295     throw "Record `" + getName() + "' does not have a field named `" +
1296           FieldName + "'!\n";
1297
1298   if (IntInit *II = dynamic_cast<IntInit*>(R->getValue()))
1299     return II->getValue();
1300   throw "Record `" + getName() + "', field `" + FieldName +
1301         "' does not have an int initializer!";
1302 }
1303
1304 /// getValueAsListOfInts - This method looks up the specified field and returns
1305 /// its value as a vector of integers, throwing an exception if the field does
1306 /// not exist or if the value is not the right type.
1307 ///
1308 std::vector<int64_t> 
1309 Record::getValueAsListOfInts(const std::string &FieldName) const {
1310   ListInit *List = getValueAsListInit(FieldName);
1311   std::vector<int64_t> Ints;
1312   for (unsigned i = 0; i < List->getSize(); i++) {
1313     if (IntInit *II = dynamic_cast<IntInit*>(List->getElement(i))) {
1314       Ints.push_back(II->getValue());
1315     } else {
1316       throw "Record `" + getName() + "', field `" + FieldName +
1317             "' does not have a list of ints initializer!";
1318     }
1319   }
1320   return Ints;
1321 }
1322
1323 /// getValueAsDef - This method looks up the specified field and returns its
1324 /// value as a Record, throwing an exception if the field does not exist or if
1325 /// the value is not the right type.
1326 ///
1327 Record *Record::getValueAsDef(const std::string &FieldName) const {
1328   const RecordVal *R = getValue(FieldName);
1329   if (R == 0 || R->getValue() == 0)
1330     throw "Record `" + getName() + "' does not have a field named `" +
1331       FieldName + "'!\n";
1332
1333   if (DefInit *DI = dynamic_cast<DefInit*>(R->getValue()))
1334     return DI->getDef();
1335   throw "Record `" + getName() + "', field `" + FieldName +
1336         "' does not have a def initializer!";
1337 }
1338
1339 /// getValueAsBit - This method looks up the specified field and returns its
1340 /// value as a bit, throwing an exception if the field does not exist or if
1341 /// the value is not the right type.
1342 ///
1343 bool Record::getValueAsBit(const std::string &FieldName) const {
1344   const RecordVal *R = getValue(FieldName);
1345   if (R == 0 || R->getValue() == 0)
1346     throw "Record `" + getName() + "' does not have a field named `" +
1347       FieldName + "'!\n";
1348
1349   if (BitInit *BI = dynamic_cast<BitInit*>(R->getValue()))
1350     return BI->getValue();
1351   throw "Record `" + getName() + "', field `" + FieldName +
1352         "' does not have a bit initializer!";
1353 }
1354
1355 /// getValueAsDag - This method looks up the specified field and returns its
1356 /// value as an Dag, throwing an exception if the field does not exist or if
1357 /// the value is not the right type.
1358 ///
1359 DagInit *Record::getValueAsDag(const std::string &FieldName) const {
1360   const RecordVal *R = getValue(FieldName);
1361   if (R == 0 || R->getValue() == 0)
1362     throw "Record `" + getName() + "' does not have a field named `" +
1363       FieldName + "'!\n";
1364
1365   if (DagInit *DI = dynamic_cast<DagInit*>(R->getValue()))
1366     return DI;
1367   throw "Record `" + getName() + "', field `" + FieldName +
1368         "' does not have a dag initializer!";
1369 }
1370
1371 std::string Record::getValueAsCode(const std::string &FieldName) const {
1372   const RecordVal *R = getValue(FieldName);
1373   if (R == 0 || R->getValue() == 0)
1374     throw "Record `" + getName() + "' does not have a field named `" +
1375       FieldName + "'!\n";
1376   
1377   if (const CodeInit *CI = dynamic_cast<const CodeInit*>(R->getValue()))
1378     return CI->getValue();
1379   throw "Record `" + getName() + "', field `" + FieldName +
1380     "' does not have a code initializer!";
1381 }
1382
1383
1384 void MultiClass::dump() const {
1385   cerr << "Record:\n";
1386   Rec.dump();
1387   
1388   cerr << "Defs:\n";
1389   for (RecordVector::const_iterator r = DefPrototypes.begin(),
1390          rend = DefPrototypes.end();
1391        r != rend;
1392        ++r) {
1393     (*r)->dump();
1394   }
1395 }
1396
1397
1398 void RecordKeeper::dump() const { cerr << *this; }
1399
1400 std::ostream &llvm::operator<<(std::ostream &OS, const RecordKeeper &RK) {
1401   OS << "------------- Classes -----------------\n";
1402   const std::map<std::string, Record*> &Classes = RK.getClasses();
1403   for (std::map<std::string, Record*>::const_iterator I = Classes.begin(),
1404          E = Classes.end(); I != E; ++I)
1405     OS << "class " << *I->second;
1406
1407   OS << "------------- Defs -----------------\n";
1408   const std::map<std::string, Record*> &Defs = RK.getDefs();
1409   for (std::map<std::string, Record*>::const_iterator I = Defs.begin(),
1410          E = Defs.end(); I != E; ++I)
1411     OS << "def " << *I->second;
1412   return OS;
1413 }
1414
1415
1416 /// getAllDerivedDefinitions - This method returns all concrete definitions
1417 /// that derive from the specified class name.  If a class with the specified
1418 /// name does not exist, an error is printed and true is returned.
1419 std::vector<Record*>
1420 RecordKeeper::getAllDerivedDefinitions(const std::string &ClassName) const {
1421   Record *Class = Records.getClass(ClassName);
1422   if (!Class)
1423     throw "ERROR: Couldn't find the `" + ClassName + "' class!\n";
1424
1425   std::vector<Record*> Defs;
1426   for (std::map<std::string, Record*>::const_iterator I = getDefs().begin(),
1427          E = getDefs().end(); I != E; ++I)
1428     if (I->second->isSubClassOf(Class))
1429       Defs.push_back(I->second);
1430
1431   return Defs;
1432 }
1433