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