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