1b1c18b589ac9b00663b38db6e238a9acb2e42c6
[oota-llvm.git] / lib / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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 Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TGParser.h"
15 #include "llvm/TableGen/Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include <algorithm>
18 #include <sstream>
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
26
27 namespace llvm {
28 struct SubClassReference {
29   SMLoc RefLoc;
30   Record *Rec;
31   std::vector<Init*> TemplateArgs;
32   SubClassReference() : Rec(0) {}
33
34   bool isInvalid() const { return Rec == 0; }
35 };
36
37 struct SubMultiClassReference {
38   SMLoc RefLoc;
39   MultiClass *MC;
40   std::vector<Init*> TemplateArgs;
41   SubMultiClassReference() : MC(0) {}
42
43   bool isInvalid() const { return MC == 0; }
44   void dump() const;
45 };
46
47 void SubMultiClassReference::dump() const {
48   errs() << "Multiclass:\n";
49
50   MC->dump();
51
52   errs() << "Template args:\n";
53   for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54          iend = TemplateArgs.end();
55        i != iend;
56        ++i) {
57     (*i)->dump();
58   }
59 }
60
61 } // end namespace llvm
62
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64   if (CurRec == 0)
65     CurRec = &CurMultiClass->Rec;
66
67   if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68     // The value already exists in the class, treat this as a set.
69     if (ERV->setValue(RV.getValue()))
70       return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71                    RV.getType()->getAsString() + "' is incompatible with " +
72                    "previous definition of type '" +
73                    ERV->getType()->getAsString() + "'");
74   } else {
75     CurRec->addValue(RV);
76   }
77   return false;
78 }
79
80 /// SetValue -
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83                         const std::vector<unsigned> &BitList, Init *V) {
84   if (!V) return false;
85
86   if (CurRec == 0) CurRec = &CurMultiClass->Rec;
87
88   RecordVal *RV = CurRec->getValue(ValName);
89   if (RV == 0)
90     return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91                  + "' unknown!");
92
93   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
94   // in the resolution machinery.
95   if (BitList.empty())
96     if (VarInit *VI = dyn_cast<VarInit>(V))
97       if (VI->getNameInit() == ValName)
98         return false;
99
100   // If we are assigning to a subset of the bits in the value... then we must be
101   // assigning to a field of BitsRecTy, which must have a BitsInit
102   // initializer.
103   //
104   if (!BitList.empty()) {
105     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
106     if (CurVal == 0)
107       return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108                    + "' is not a bits type");
109
110     // Convert the incoming value to a bits type of the appropriate size...
111     Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
112     if (BI == 0) {
113       return Error(Loc, "Initializer is not compatible with bit range");
114     }
115
116     // We should have a BitsInit type now.
117     BitsInit *BInit = dyn_cast<BitsInit>(BI);
118     assert(BInit != 0);
119
120     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
121
122     // Loop over bits, assigning values as appropriate.
123     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124       unsigned Bit = BitList[i];
125       if (NewBits[Bit])
126         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127                      ValName->getAsUnquotedString() + "' more than once");
128       NewBits[Bit] = BInit->getBit(i);
129     }
130
131     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
132       if (NewBits[i] == 0)
133         NewBits[i] = CurVal->getBit(i);
134
135     V = BitsInit::get(NewBits);
136   }
137
138   if (RV->setValue(V))
139     return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140                  + RV->getType()->getAsString() +
141                  "' is incompatible with initializer '" + V->getAsString()
142                  + "'");
143   return false;
144 }
145
146 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147 /// args as SubClass's template arguments.
148 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149   Record *SC = SubClass.Rec;
150   // Add all of the values in the subclass into the current class.
151   const std::vector<RecordVal> &Vals = SC->getValues();
152   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
154       return true;
155
156   const std::vector<Init *> &TArgs = SC->getTemplateArgs();
157
158   // Ensure that an appropriate number of template arguments are specified.
159   if (TArgs.size() < SubClass.TemplateArgs.size())
160     return Error(SubClass.RefLoc, "More template args specified than expected");
161
162   // Loop over all of the template arguments, setting them to the specified
163   // value or leaving them as the default if necessary.
164   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
165     if (i < SubClass.TemplateArgs.size()) {
166       // If a value is specified for this template arg, set it now.
167       if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
168                    SubClass.TemplateArgs[i]))
169         return true;
170
171       // Resolve it next.
172       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
173
174       // Now remove it.
175       CurRec->removeValue(TArgs[i]);
176
177     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
178       return Error(SubClass.RefLoc,"Value not specified for template argument #"
179                    + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
180                    + ") of subclass '" + SC->getNameInitAsString() + "'!");
181     }
182   }
183
184   // Since everything went well, we can now set the "superclass" list for the
185   // current record.
186   const std::vector<Record*> &SCs = SC->getSuperClasses();
187   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
188     if (CurRec->isSubClassOf(SCs[i]))
189       return Error(SubClass.RefLoc,
190                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
191     CurRec->addSuperClass(SCs[i]);
192   }
193
194   if (CurRec->isSubClassOf(SC))
195     return Error(SubClass.RefLoc,
196                  "Already subclass of '" + SC->getName() + "'!\n");
197   CurRec->addSuperClass(SC);
198   return false;
199 }
200
201 /// AddSubMultiClass - Add SubMultiClass as a subclass to
202 /// CurMC, resolving its template args as SubMultiClass's
203 /// template arguments.
204 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
205                                 SubMultiClassReference &SubMultiClass) {
206   MultiClass *SMC = SubMultiClass.MC;
207   Record *CurRec = &CurMC->Rec;
208
209   const std::vector<RecordVal> &MCVals = CurRec->getValues();
210
211   // Add all of the values in the subclass into the current class.
212   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
213   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
214     if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
215       return true;
216
217   int newDefStart = CurMC->DefPrototypes.size();
218
219   // Add all of the defs in the subclass into the current multiclass.
220   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
221          iend = SMC->DefPrototypes.end();
222        i != iend;
223        ++i) {
224     // Clone the def and add it to the current multiclass
225     Record *NewDef = new Record(**i);
226
227     // Add all of the values in the superclass into the current def.
228     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
229       if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
230         return true;
231
232     CurMC->DefPrototypes.push_back(NewDef);
233   }
234
235   const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
236
237   // Ensure that an appropriate number of template arguments are
238   // specified.
239   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
240     return Error(SubMultiClass.RefLoc,
241                  "More template args specified than expected");
242
243   // Loop over all of the template arguments, setting them to the specified
244   // value or leaving them as the default if necessary.
245   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
246     if (i < SubMultiClass.TemplateArgs.size()) {
247       // If a value is specified for this template arg, set it in the
248       // superclass now.
249       if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
250                    std::vector<unsigned>(),
251                    SubMultiClass.TemplateArgs[i]))
252         return true;
253
254       // Resolve it next.
255       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
256
257       // Now remove it.
258       CurRec->removeValue(SMCTArgs[i]);
259
260       // If a value is specified for this template arg, set it in the
261       // new defs now.
262       for (MultiClass::RecordVector::iterator j =
263              CurMC->DefPrototypes.begin() + newDefStart,
264              jend = CurMC->DefPrototypes.end();
265            j != jend;
266            ++j) {
267         Record *Def = *j;
268
269         if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
270                      std::vector<unsigned>(),
271                      SubMultiClass.TemplateArgs[i]))
272           return true;
273
274         // Resolve it next.
275         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
276
277         // Now remove it
278         Def->removeValue(SMCTArgs[i]);
279       }
280     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
281       return Error(SubMultiClass.RefLoc,
282                    "Value not specified for template argument #"
283                    + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
284                    + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
285     }
286   }
287
288   return false;
289 }
290
291 /// ProcessForeachDefs - Given a record, apply all of the variable
292 /// values in all surrounding foreach loops, creating new records for
293 /// each combination of values.
294 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
295   if (Loops.empty())
296     return false;
297
298   // We want to instantiate a new copy of CurRec for each combination
299   // of nested loop iterator values.  We don't want top instantiate
300   // any copies until we have values for each loop iterator.
301   IterSet IterVals;
302   return ProcessForeachDefs(CurRec, Loc, IterVals);
303 }
304
305 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
306 /// apply each of the variable values in this loop and then process
307 /// subloops.
308 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
309   // Recursively build a tuple of iterator values.
310   if (IterVals.size() != Loops.size()) {
311     assert(IterVals.size() < Loops.size());
312     ForeachLoop &CurLoop = Loops[IterVals.size()];
313     ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
314     if (List == 0) {
315       Error(Loc, "Loop list is not a list");
316       return true;
317     }
318
319     // Process each value.
320     for (int64_t i = 0; i < List->getSize(); ++i) {
321       Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
322       IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
323       if (ProcessForeachDefs(CurRec, Loc, IterVals))
324         return true;
325       IterVals.pop_back();
326     }
327     return false;
328   }
329
330   // This is the bottom of the recursion. We have all of the iterator values
331   // for this point in the iteration space.  Instantiate a new record to
332   // reflect this combination of values.
333   Record *IterRec = new Record(*CurRec);
334
335   // Set the iterator values now.
336   for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
337     VarInit *IterVar = IterVals[i].IterVar;
338     TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
339     if (IVal == 0) {
340       Error(Loc, "foreach iterator value is untyped");
341       return true;
342     }
343
344     IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
345
346     if (SetValue(IterRec, Loc, IterVar->getName(),
347                  std::vector<unsigned>(), IVal)) {
348       Error(Loc, "when instantiating this def");
349       return true;
350     }
351
352     // Resolve it next.
353     IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
354
355     // Remove it.
356     IterRec->removeValue(IterVar->getName());
357   }
358
359   if (Records.getDef(IterRec->getNameInitAsString())) {
360     Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
361     return true;
362   }
363
364   Records.addDef(IterRec);
365   IterRec->resolveReferences();
366   return false;
367 }
368
369 //===----------------------------------------------------------------------===//
370 // Parser Code
371 //===----------------------------------------------------------------------===//
372
373 /// isObjectStart - Return true if this is a valid first token for an Object.
374 static bool isObjectStart(tgtok::TokKind K) {
375   return K == tgtok::Class || K == tgtok::Def ||
376          K == tgtok::Defm || K == tgtok::Let ||
377          K == tgtok::MultiClass || K == tgtok::Foreach;
378 }
379
380 static std::string GetNewAnonymousName() {
381   static unsigned AnonCounter = 0;
382   return "anonymous."+utostr(AnonCounter++);
383 }
384
385 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
386 /// return an anonymous name.
387 ///   ObjectName ::= Value [ '#' Value ]*
388 ///   ObjectName ::= /*empty*/
389 ///
390 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
391   switch (Lex.getCode()) {
392   case tgtok::colon:
393   case tgtok::semi:
394   case tgtok::l_brace:
395     // These are all of the tokens that can begin an object body.
396     // Some of these can also begin values but we disallow those cases
397     // because they are unlikely to be useful.
398     return StringInit::get(GetNewAnonymousName());
399   default:
400     break;
401   }
402
403   Record *CurRec = 0;
404   if (CurMultiClass)
405     CurRec = &CurMultiClass->Rec;
406
407   RecTy *Type = 0;
408   if (CurRec) {
409     const TypedInit *CurRecName =
410       dyn_cast<TypedInit>(CurRec->getNameInit());
411     if (!CurRecName) {
412       TokError("Record name is not typed!");
413       return 0;
414     }
415     Type = CurRecName->getType();
416   }
417
418   return ParseValue(CurRec, Type, ParseNameMode);
419 }
420
421 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
422 /// null on error.
423 ///
424 ///    ClassID ::= ID
425 ///
426 Record *TGParser::ParseClassID() {
427   if (Lex.getCode() != tgtok::Id) {
428     TokError("expected name for ClassID");
429     return 0;
430   }
431
432   Record *Result = Records.getClass(Lex.getCurStrVal());
433   if (Result == 0)
434     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
435
436   Lex.Lex();
437   return Result;
438 }
439
440 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
441 /// This returns null on error.
442 ///
443 ///    MultiClassID ::= ID
444 ///
445 MultiClass *TGParser::ParseMultiClassID() {
446   if (Lex.getCode() != tgtok::Id) {
447     TokError("expected name for ClassID");
448     return 0;
449   }
450
451   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
452   if (Result == 0)
453     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
454
455   Lex.Lex();
456   return Result;
457 }
458
459 Record *TGParser::ParseDefmID() {
460   if (Lex.getCode() != tgtok::Id) {
461     TokError("expected multiclass name");
462     return 0;
463   }
464
465   MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
466   if (MC == 0) {
467     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
468     return 0;
469   }
470
471   Lex.Lex();
472   return &MC->Rec;
473 }
474
475
476 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
477 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
478 ///
479 ///  SubClassRef ::= ClassID
480 ///  SubClassRef ::= ClassID '<' ValueList '>'
481 ///
482 SubClassReference TGParser::
483 ParseSubClassReference(Record *CurRec, bool isDefm) {
484   SubClassReference Result;
485   Result.RefLoc = Lex.getLoc();
486
487   if (isDefm)
488     Result.Rec = ParseDefmID();
489   else
490     Result.Rec = ParseClassID();
491   if (Result.Rec == 0) return Result;
492
493   // If there is no template arg list, we're done.
494   if (Lex.getCode() != tgtok::less)
495     return Result;
496   Lex.Lex();  // Eat the '<'
497
498   if (Lex.getCode() == tgtok::greater) {
499     TokError("subclass reference requires a non-empty list of template values");
500     Result.Rec = 0;
501     return Result;
502   }
503
504   Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
505   if (Result.TemplateArgs.empty()) {
506     Result.Rec = 0;   // Error parsing value list.
507     return Result;
508   }
509
510   if (Lex.getCode() != tgtok::greater) {
511     TokError("expected '>' in template value list");
512     Result.Rec = 0;
513     return Result;
514   }
515   Lex.Lex();
516
517   return Result;
518 }
519
520 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
521 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
522 /// Record* on error.
523 ///
524 ///  SubMultiClassRef ::= MultiClassID
525 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
526 ///
527 SubMultiClassReference TGParser::
528 ParseSubMultiClassReference(MultiClass *CurMC) {
529   SubMultiClassReference Result;
530   Result.RefLoc = Lex.getLoc();
531
532   Result.MC = ParseMultiClassID();
533   if (Result.MC == 0) return Result;
534
535   // If there is no template arg list, we're done.
536   if (Lex.getCode() != tgtok::less)
537     return Result;
538   Lex.Lex();  // Eat the '<'
539
540   if (Lex.getCode() == tgtok::greater) {
541     TokError("subclass reference requires a non-empty list of template values");
542     Result.MC = 0;
543     return Result;
544   }
545
546   Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
547   if (Result.TemplateArgs.empty()) {
548     Result.MC = 0;   // Error parsing value list.
549     return Result;
550   }
551
552   if (Lex.getCode() != tgtok::greater) {
553     TokError("expected '>' in template value list");
554     Result.MC = 0;
555     return Result;
556   }
557   Lex.Lex();
558
559   return Result;
560 }
561
562 /// ParseRangePiece - Parse a bit/value range.
563 ///   RangePiece ::= INTVAL
564 ///   RangePiece ::= INTVAL '-' INTVAL
565 ///   RangePiece ::= INTVAL INTVAL
566 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
567   if (Lex.getCode() != tgtok::IntVal) {
568     TokError("expected integer or bitrange");
569     return true;
570   }
571   int64_t Start = Lex.getCurIntVal();
572   int64_t End;
573
574   if (Start < 0)
575     return TokError("invalid range, cannot be negative");
576
577   switch (Lex.Lex()) {  // eat first character.
578   default:
579     Ranges.push_back(Start);
580     return false;
581   case tgtok::minus:
582     if (Lex.Lex() != tgtok::IntVal) {
583       TokError("expected integer value as end of range");
584       return true;
585     }
586     End = Lex.getCurIntVal();
587     break;
588   case tgtok::IntVal:
589     End = -Lex.getCurIntVal();
590     break;
591   }
592   if (End < 0)
593     return TokError("invalid range, cannot be negative");
594   Lex.Lex();
595
596   // Add to the range.
597   if (Start < End) {
598     for (; Start <= End; ++Start)
599       Ranges.push_back(Start);
600   } else {
601     for (; Start >= End; --Start)
602       Ranges.push_back(Start);
603   }
604   return false;
605 }
606
607 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
608 ///
609 ///   RangeList ::= RangePiece (',' RangePiece)*
610 ///
611 std::vector<unsigned> TGParser::ParseRangeList() {
612   std::vector<unsigned> Result;
613
614   // Parse the first piece.
615   if (ParseRangePiece(Result))
616     return std::vector<unsigned>();
617   while (Lex.getCode() == tgtok::comma) {
618     Lex.Lex();  // Eat the comma.
619
620     // Parse the next range piece.
621     if (ParseRangePiece(Result))
622       return std::vector<unsigned>();
623   }
624   return Result;
625 }
626
627 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
628 ///   OptionalRangeList ::= '<' RangeList '>'
629 ///   OptionalRangeList ::= /*empty*/
630 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
631   if (Lex.getCode() != tgtok::less)
632     return false;
633
634   SMLoc StartLoc = Lex.getLoc();
635   Lex.Lex(); // eat the '<'
636
637   // Parse the range list.
638   Ranges = ParseRangeList();
639   if (Ranges.empty()) return true;
640
641   if (Lex.getCode() != tgtok::greater) {
642     TokError("expected '>' at end of range list");
643     return Error(StartLoc, "to match this '<'");
644   }
645   Lex.Lex();   // eat the '>'.
646   return false;
647 }
648
649 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
650 ///   OptionalBitList ::= '{' RangeList '}'
651 ///   OptionalBitList ::= /*empty*/
652 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
653   if (Lex.getCode() != tgtok::l_brace)
654     return false;
655
656   SMLoc StartLoc = Lex.getLoc();
657   Lex.Lex(); // eat the '{'
658
659   // Parse the range list.
660   Ranges = ParseRangeList();
661   if (Ranges.empty()) return true;
662
663   if (Lex.getCode() != tgtok::r_brace) {
664     TokError("expected '}' at end of bit list");
665     return Error(StartLoc, "to match this '{'");
666   }
667   Lex.Lex();   // eat the '}'.
668   return false;
669 }
670
671
672 /// ParseType - Parse and return a tblgen type.  This returns null on error.
673 ///
674 ///   Type ::= STRING                       // string type
675 ///   Type ::= CODE                         // code type
676 ///   Type ::= BIT                          // bit type
677 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
678 ///   Type ::= INT                          // int type
679 ///   Type ::= LIST '<' Type '>'            // list<x> type
680 ///   Type ::= DAG                          // dag type
681 ///   Type ::= ClassID                      // Record Type
682 ///
683 RecTy *TGParser::ParseType() {
684   switch (Lex.getCode()) {
685   default: TokError("Unknown token when expecting a type"); return 0;
686   case tgtok::String: Lex.Lex(); return StringRecTy::get();
687   case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
688   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
689   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
690   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
691   case tgtok::Id:
692     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
693     return 0;
694   case tgtok::Bits: {
695     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
696       TokError("expected '<' after bits type");
697       return 0;
698     }
699     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
700       TokError("expected integer in bits<n> type");
701       return 0;
702     }
703     uint64_t Val = Lex.getCurIntVal();
704     if (Lex.Lex() != tgtok::greater) {  // Eat count.
705       TokError("expected '>' at end of bits<n> type");
706       return 0;
707     }
708     Lex.Lex();  // Eat '>'
709     return BitsRecTy::get(Val);
710   }
711   case tgtok::List: {
712     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
713       TokError("expected '<' after list type");
714       return 0;
715     }
716     Lex.Lex();  // Eat '<'
717     RecTy *SubType = ParseType();
718     if (SubType == 0) return 0;
719
720     if (Lex.getCode() != tgtok::greater) {
721       TokError("expected '>' at end of list<ty> type");
722       return 0;
723     }
724     Lex.Lex();  // Eat '>'
725     return ListRecTy::get(SubType);
726   }
727   }
728 }
729
730 /// ParseIDValue - Parse an ID as a value and decode what it means.
731 ///
732 ///  IDValue ::= ID [def local value]
733 ///  IDValue ::= ID [def template arg]
734 ///  IDValue ::= ID [multiclass local value]
735 ///  IDValue ::= ID [multiclass template argument]
736 ///  IDValue ::= ID [def name]
737 ///
738 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
739   assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
740   std::string Name = Lex.getCurStrVal();
741   SMLoc Loc = Lex.getLoc();
742   Lex.Lex();
743   return ParseIDValue(CurRec, Name, Loc);
744 }
745
746 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
747 /// has already been read.
748 Init *TGParser::ParseIDValue(Record *CurRec,
749                              const std::string &Name, SMLoc NameLoc,
750                              IDParseMode Mode) {
751   if (CurRec) {
752     if (const RecordVal *RV = CurRec->getValue(Name))
753       return VarInit::get(Name, RV->getType());
754
755     Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
756
757     if (CurMultiClass)
758       TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
759                                     "::");
760
761     if (CurRec->isTemplateArg(TemplateArgName)) {
762       const RecordVal *RV = CurRec->getValue(TemplateArgName);
763       assert(RV && "Template arg doesn't exist??");
764       return VarInit::get(TemplateArgName, RV->getType());
765     }
766   }
767
768   if (CurMultiClass) {
769     Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
770                                "::");
771
772     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
773       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
774       assert(RV && "Template arg doesn't exist??");
775       return VarInit::get(MCName, RV->getType());
776     }
777   }
778
779   // If this is in a foreach loop, make sure it's not a loop iterator
780   for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
781        i != iend;
782        ++i) {
783     VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
784     if (IterVar && IterVar->getName() == Name)
785       return IterVar;
786   }
787
788   if (Mode == ParseNameMode)
789     return StringInit::get(Name);
790
791   if (Record *D = Records.getDef(Name))
792     return DefInit::get(D);
793
794   if (Mode == ParseValueMode) {
795     Error(NameLoc, "Variable not defined: '" + Name + "'");
796     return 0;
797   }
798   
799   return StringInit::get(Name);
800 }
801
802 /// ParseOperation - Parse an operator.  This returns null on error.
803 ///
804 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
805 ///
806 Init *TGParser::ParseOperation(Record *CurRec) {
807   switch (Lex.getCode()) {
808   default:
809     TokError("unknown operation");
810     return 0;
811   case tgtok::XHead:
812   case tgtok::XTail:
813   case tgtok::XEmpty:
814   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
815     UnOpInit::UnaryOp Code;
816     RecTy *Type = 0;
817
818     switch (Lex.getCode()) {
819     default: llvm_unreachable("Unhandled code!");
820     case tgtok::XCast:
821       Lex.Lex();  // eat the operation
822       Code = UnOpInit::CAST;
823
824       Type = ParseOperatorType();
825
826       if (Type == 0) {
827         TokError("did not get type for unary operator");
828         return 0;
829       }
830
831       break;
832     case tgtok::XHead:
833       Lex.Lex();  // eat the operation
834       Code = UnOpInit::HEAD;
835       break;
836     case tgtok::XTail:
837       Lex.Lex();  // eat the operation
838       Code = UnOpInit::TAIL;
839       break;
840     case tgtok::XEmpty:
841       Lex.Lex();  // eat the operation
842       Code = UnOpInit::EMPTY;
843       Type = IntRecTy::get();
844       break;
845     }
846     if (Lex.getCode() != tgtok::l_paren) {
847       TokError("expected '(' after unary operator");
848       return 0;
849     }
850     Lex.Lex();  // eat the '('
851
852     Init *LHS = ParseValue(CurRec);
853     if (LHS == 0) return 0;
854
855     if (Code == UnOpInit::HEAD
856         || Code == UnOpInit::TAIL
857         || Code == UnOpInit::EMPTY) {
858       ListInit *LHSl = dyn_cast<ListInit>(LHS);
859       StringInit *LHSs = dyn_cast<StringInit>(LHS);
860       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
861       if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
862         TokError("expected list or string type argument in unary operator");
863         return 0;
864       }
865       if (LHSt) {
866         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
867         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
868         if (LType == 0 && SType == 0) {
869           TokError("expected list or string type argumnet in unary operator");
870           return 0;
871         }
872       }
873
874       if (Code == UnOpInit::HEAD
875           || Code == UnOpInit::TAIL) {
876         if (LHSl == 0 && LHSt == 0) {
877           TokError("expected list type argumnet in unary operator");
878           return 0;
879         }
880
881         if (LHSl && LHSl->getSize() == 0) {
882           TokError("empty list argument in unary operator");
883           return 0;
884         }
885         if (LHSl) {
886           Init *Item = LHSl->getElement(0);
887           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
888           if (Itemt == 0) {
889             TokError("untyped list element in unary operator");
890             return 0;
891           }
892           if (Code == UnOpInit::HEAD) {
893             Type = Itemt->getType();
894           } else {
895             Type = ListRecTy::get(Itemt->getType());
896           }
897         } else {
898           assert(LHSt && "expected list type argument in unary operator");
899           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
900           if (LType == 0) {
901             TokError("expected list type argumnet in unary operator");
902             return 0;
903           }
904           if (Code == UnOpInit::HEAD) {
905             Type = LType->getElementType();
906           } else {
907             Type = LType;
908           }
909         }
910       }
911     }
912
913     if (Lex.getCode() != tgtok::r_paren) {
914       TokError("expected ')' in unary operator");
915       return 0;
916     }
917     Lex.Lex();  // eat the ')'
918     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
919   }
920
921   case tgtok::XConcat:
922   case tgtok::XSRA:
923   case tgtok::XSRL:
924   case tgtok::XSHL:
925   case tgtok::XEq:
926   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
927     tgtok::TokKind OpTok = Lex.getCode();
928     SMLoc OpLoc = Lex.getLoc();
929     Lex.Lex();  // eat the operation
930
931     BinOpInit::BinaryOp Code;
932     RecTy *Type = 0;
933
934     switch (OpTok) {
935     default: llvm_unreachable("Unhandled code!");
936     case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
937     case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
938     case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
939     case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
940     case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
941     case tgtok::XStrConcat:
942       Code = BinOpInit::STRCONCAT;
943       Type = StringRecTy::get();
944       break;
945     }
946
947     if (Lex.getCode() != tgtok::l_paren) {
948       TokError("expected '(' after binary operator");
949       return 0;
950     }
951     Lex.Lex();  // eat the '('
952
953     SmallVector<Init*, 2> InitList;
954
955     InitList.push_back(ParseValue(CurRec));
956     if (InitList.back() == 0) return 0;
957
958     while (Lex.getCode() == tgtok::comma) {
959       Lex.Lex();  // eat the ','
960
961       InitList.push_back(ParseValue(CurRec));
962       if (InitList.back() == 0) return 0;
963     }
964
965     if (Lex.getCode() != tgtok::r_paren) {
966       TokError("expected ')' in operator");
967       return 0;
968     }
969     Lex.Lex();  // eat the ')'
970
971     // We allow multiple operands to associative operators like !strconcat as
972     // shorthand for nesting them.
973     if (Code == BinOpInit::STRCONCAT) {
974       while (InitList.size() > 2) {
975         Init *RHS = InitList.pop_back_val();
976         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
977                            ->Fold(CurRec, CurMultiClass);
978         InitList.back() = RHS;
979       }
980     }
981
982     if (InitList.size() == 2)
983       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
984         ->Fold(CurRec, CurMultiClass);
985
986     Error(OpLoc, "expected two operands to operator");
987     return 0;
988   }
989
990   case tgtok::XIf:
991   case tgtok::XForEach:
992   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
993     TernOpInit::TernaryOp Code;
994     RecTy *Type = 0;
995
996     tgtok::TokKind LexCode = Lex.getCode();
997     Lex.Lex();  // eat the operation
998     switch (LexCode) {
999     default: llvm_unreachable("Unhandled code!");
1000     case tgtok::XIf:
1001       Code = TernOpInit::IF;
1002       break;
1003     case tgtok::XForEach:
1004       Code = TernOpInit::FOREACH;
1005       break;
1006     case tgtok::XSubst:
1007       Code = TernOpInit::SUBST;
1008       break;
1009     }
1010     if (Lex.getCode() != tgtok::l_paren) {
1011       TokError("expected '(' after ternary operator");
1012       return 0;
1013     }
1014     Lex.Lex();  // eat the '('
1015
1016     Init *LHS = ParseValue(CurRec);
1017     if (LHS == 0) return 0;
1018
1019     if (Lex.getCode() != tgtok::comma) {
1020       TokError("expected ',' in ternary operator");
1021       return 0;
1022     }
1023     Lex.Lex();  // eat the ','
1024
1025     Init *MHS = ParseValue(CurRec);
1026     if (MHS == 0) return 0;
1027
1028     if (Lex.getCode() != tgtok::comma) {
1029       TokError("expected ',' in ternary operator");
1030       return 0;
1031     }
1032     Lex.Lex();  // eat the ','
1033
1034     Init *RHS = ParseValue(CurRec);
1035     if (RHS == 0) return 0;
1036
1037     if (Lex.getCode() != tgtok::r_paren) {
1038       TokError("expected ')' in binary operator");
1039       return 0;
1040     }
1041     Lex.Lex();  // eat the ')'
1042
1043     switch (LexCode) {
1044     default: llvm_unreachable("Unhandled code!");
1045     case tgtok::XIf: {
1046       RecTy *MHSTy = 0;
1047       RecTy *RHSTy = 0;
1048
1049       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1050         MHSTy = MHSt->getType();
1051       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1052         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1053       if (dyn_cast<BitInit>(MHS))
1054         MHSTy = BitRecTy::get();
1055
1056       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1057         RHSTy = RHSt->getType();
1058       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1059         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1060       if (dyn_cast<BitInit>(RHS))
1061         RHSTy = BitRecTy::get();
1062
1063       // For UnsetInit, it's typed from the other hand.
1064       if (dyn_cast<UnsetInit>(MHS))
1065         MHSTy = RHSTy;
1066       if (dyn_cast<UnsetInit>(RHS))
1067         RHSTy = MHSTy;
1068
1069       if (!MHSTy || !RHSTy) {
1070         TokError("could not get type for !if");
1071         return 0;
1072       }
1073
1074       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1075         Type = RHSTy;
1076       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1077         Type = MHSTy;
1078       } else {
1079         TokError("inconsistent types for !if");
1080         return 0;
1081       }
1082       break;
1083     }
1084     case tgtok::XForEach: {
1085       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1086       if (MHSt == 0) {
1087         TokError("could not get type for !foreach");
1088         return 0;
1089       }
1090       Type = MHSt->getType();
1091       break;
1092     }
1093     case tgtok::XSubst: {
1094       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1095       if (RHSt == 0) {
1096         TokError("could not get type for !subst");
1097         return 0;
1098       }
1099       Type = RHSt->getType();
1100       break;
1101     }
1102     }
1103     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1104                                                              CurMultiClass);
1105   }
1106   }
1107 }
1108
1109 /// ParseOperatorType - Parse a type for an operator.  This returns
1110 /// null on error.
1111 ///
1112 /// OperatorType ::= '<' Type '>'
1113 ///
1114 RecTy *TGParser::ParseOperatorType() {
1115   RecTy *Type = 0;
1116
1117   if (Lex.getCode() != tgtok::less) {
1118     TokError("expected type name for operator");
1119     return 0;
1120   }
1121   Lex.Lex();  // eat the <
1122
1123   Type = ParseType();
1124
1125   if (Type == 0) {
1126     TokError("expected type name for operator");
1127     return 0;
1128   }
1129
1130   if (Lex.getCode() != tgtok::greater) {
1131     TokError("expected type name for operator");
1132     return 0;
1133   }
1134   Lex.Lex();  // eat the >
1135
1136   return Type;
1137 }
1138
1139
1140 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1141 ///
1142 ///   SimpleValue ::= IDValue
1143 ///   SimpleValue ::= INTVAL
1144 ///   SimpleValue ::= STRVAL+
1145 ///   SimpleValue ::= CODEFRAGMENT
1146 ///   SimpleValue ::= '?'
1147 ///   SimpleValue ::= '{' ValueList '}'
1148 ///   SimpleValue ::= ID '<' ValueListNE '>'
1149 ///   SimpleValue ::= '[' ValueList ']'
1150 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1151 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1152 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1153 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1154 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1155 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1156 ///
1157 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1158                                  IDParseMode Mode) {
1159   Init *R = 0;
1160   switch (Lex.getCode()) {
1161   default: TokError("Unknown token when parsing a value"); break;
1162   case tgtok::paste:
1163     // This is a leading paste operation.  This is deprecated but
1164     // still exists in some .td files.  Ignore it.
1165     Lex.Lex();  // Skip '#'.
1166     return ParseSimpleValue(CurRec, ItemType, Mode);
1167   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1168   case tgtok::StrVal: {
1169     std::string Val = Lex.getCurStrVal();
1170     Lex.Lex();
1171
1172     // Handle multiple consecutive concatenated strings.
1173     while (Lex.getCode() == tgtok::StrVal) {
1174       Val += Lex.getCurStrVal();
1175       Lex.Lex();
1176     }
1177
1178     R = StringInit::get(Val);
1179     break;
1180   }
1181   case tgtok::CodeFragment:
1182     R = StringInit::get(Lex.getCurStrVal());
1183     Lex.Lex();
1184     break;
1185   case tgtok::question:
1186     R = UnsetInit::get();
1187     Lex.Lex();
1188     break;
1189   case tgtok::Id: {
1190     SMLoc NameLoc = Lex.getLoc();
1191     std::string Name = Lex.getCurStrVal();
1192     if (Lex.Lex() != tgtok::less)  // consume the Id.
1193       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1194
1195     // Value ::= ID '<' ValueListNE '>'
1196     if (Lex.Lex() == tgtok::greater) {
1197       TokError("expected non-empty value list");
1198       return 0;
1199     }
1200
1201     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1202     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1203     // body.
1204     Record *Class = Records.getClass(Name);
1205     if (!Class) {
1206       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1207       return 0;
1208     }
1209
1210     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1211     if (ValueList.empty()) return 0;
1212
1213     if (Lex.getCode() != tgtok::greater) {
1214       TokError("expected '>' at end of value list");
1215       return 0;
1216     }
1217     Lex.Lex();  // eat the '>'
1218
1219     // Create the new record, set it as CurRec temporarily.
1220     static unsigned AnonCounter = 0;
1221     Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1222                                 NameLoc,
1223                                 Records);
1224     SubClassReference SCRef;
1225     SCRef.RefLoc = NameLoc;
1226     SCRef.Rec = Class;
1227     SCRef.TemplateArgs = ValueList;
1228     // Add info about the subclass to NewRec.
1229     if (AddSubClass(NewRec, SCRef))
1230       return 0;
1231     NewRec->resolveReferences();
1232     Records.addDef(NewRec);
1233
1234     // The result of the expression is a reference to the new record.
1235     return DefInit::get(NewRec);
1236   }
1237   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1238     SMLoc BraceLoc = Lex.getLoc();
1239     Lex.Lex(); // eat the '{'
1240     std::vector<Init*> Vals;
1241
1242     if (Lex.getCode() != tgtok::r_brace) {
1243       Vals = ParseValueList(CurRec);
1244       if (Vals.empty()) return 0;
1245     }
1246     if (Lex.getCode() != tgtok::r_brace) {
1247       TokError("expected '}' at end of bit list value");
1248       return 0;
1249     }
1250     Lex.Lex();  // eat the '}'
1251
1252     SmallVector<Init *, 16> NewBits(Vals.size());
1253
1254     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1255       Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1256       if (Bit == 0) {
1257         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1258               ") is not convertable to a bit");
1259         return 0;
1260       }
1261       NewBits[Vals.size()-i-1] = Bit;
1262     }
1263     return BitsInit::get(NewBits);
1264   }
1265   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1266     Lex.Lex(); // eat the '['
1267     std::vector<Init*> Vals;
1268
1269     RecTy *DeducedEltTy = 0;
1270     ListRecTy *GivenListTy = 0;
1271
1272     if (ItemType != 0) {
1273       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1274       if (ListType == 0) {
1275         std::stringstream s;
1276         s << "Type mismatch for list, expected list type, got "
1277           << ItemType->getAsString();
1278         TokError(s.str());
1279         return 0;
1280       }
1281       GivenListTy = ListType;
1282     }
1283
1284     if (Lex.getCode() != tgtok::r_square) {
1285       Vals = ParseValueList(CurRec, 0,
1286                             GivenListTy ? GivenListTy->getElementType() : 0);
1287       if (Vals.empty()) return 0;
1288     }
1289     if (Lex.getCode() != tgtok::r_square) {
1290       TokError("expected ']' at end of list value");
1291       return 0;
1292     }
1293     Lex.Lex();  // eat the ']'
1294
1295     RecTy *GivenEltTy = 0;
1296     if (Lex.getCode() == tgtok::less) {
1297       // Optional list element type
1298       Lex.Lex();  // eat the '<'
1299
1300       GivenEltTy = ParseType();
1301       if (GivenEltTy == 0) {
1302         // Couldn't parse element type
1303         return 0;
1304       }
1305
1306       if (Lex.getCode() != tgtok::greater) {
1307         TokError("expected '>' at end of list element type");
1308         return 0;
1309       }
1310       Lex.Lex();  // eat the '>'
1311     }
1312
1313     // Check elements
1314     RecTy *EltTy = 0;
1315     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1316          i != ie;
1317          ++i) {
1318       TypedInit *TArg = dyn_cast<TypedInit>(*i);
1319       if (TArg == 0) {
1320         TokError("Untyped list element");
1321         return 0;
1322       }
1323       if (EltTy != 0) {
1324         EltTy = resolveTypes(EltTy, TArg->getType());
1325         if (EltTy == 0) {
1326           TokError("Incompatible types in list elements");
1327           return 0;
1328         }
1329       } else {
1330         EltTy = TArg->getType();
1331       }
1332     }
1333
1334     if (GivenEltTy != 0) {
1335       if (EltTy != 0) {
1336         // Verify consistency
1337         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1338           TokError("Incompatible types in list elements");
1339           return 0;
1340         }
1341       }
1342       EltTy = GivenEltTy;
1343     }
1344
1345     if (EltTy == 0) {
1346       if (ItemType == 0) {
1347         TokError("No type for list");
1348         return 0;
1349       }
1350       DeducedEltTy = GivenListTy->getElementType();
1351     } else {
1352       // Make sure the deduced type is compatible with the given type
1353       if (GivenListTy) {
1354         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1355           TokError("Element type mismatch for list");
1356           return 0;
1357         }
1358       }
1359       DeducedEltTy = EltTy;
1360     }
1361
1362     return ListInit::get(Vals, DeducedEltTy);
1363   }
1364   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1365     Lex.Lex();   // eat the '('
1366     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1367       TokError("expected identifier in dag init");
1368       return 0;
1369     }
1370
1371     Init *Operator = ParseValue(CurRec);
1372     if (Operator == 0) return 0;
1373
1374     // If the operator name is present, parse it.
1375     std::string OperatorName;
1376     if (Lex.getCode() == tgtok::colon) {
1377       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1378         TokError("expected variable name in dag operator");
1379         return 0;
1380       }
1381       OperatorName = Lex.getCurStrVal();
1382       Lex.Lex();  // eat the VarName.
1383     }
1384
1385     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1386     if (Lex.getCode() != tgtok::r_paren) {
1387       DagArgs = ParseDagArgList(CurRec);
1388       if (DagArgs.empty()) return 0;
1389     }
1390
1391     if (Lex.getCode() != tgtok::r_paren) {
1392       TokError("expected ')' in dag init");
1393       return 0;
1394     }
1395     Lex.Lex();  // eat the ')'
1396
1397     return DagInit::get(Operator, OperatorName, DagArgs);
1398   }
1399
1400   case tgtok::XHead:
1401   case tgtok::XTail:
1402   case tgtok::XEmpty:
1403   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1404   case tgtok::XConcat:
1405   case tgtok::XSRA:
1406   case tgtok::XSRL:
1407   case tgtok::XSHL:
1408   case tgtok::XEq:
1409   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1410   case tgtok::XIf:
1411   case tgtok::XForEach:
1412   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1413     return ParseOperation(CurRec);
1414   }
1415   }
1416
1417   return R;
1418 }
1419
1420 /// ParseValue - Parse a tblgen value.  This returns null on error.
1421 ///
1422 ///   Value       ::= SimpleValue ValueSuffix*
1423 ///   ValueSuffix ::= '{' BitList '}'
1424 ///   ValueSuffix ::= '[' BitList ']'
1425 ///   ValueSuffix ::= '.' ID
1426 ///
1427 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1428   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1429   if (Result == 0) return 0;
1430
1431   // Parse the suffixes now if present.
1432   while (1) {
1433     switch (Lex.getCode()) {
1434     default: return Result;
1435     case tgtok::l_brace: {
1436       if (Mode == ParseNameMode || Mode == ParseForeachMode)
1437         // This is the beginning of the object body.
1438         return Result;
1439
1440       SMLoc CurlyLoc = Lex.getLoc();
1441       Lex.Lex(); // eat the '{'
1442       std::vector<unsigned> Ranges = ParseRangeList();
1443       if (Ranges.empty()) return 0;
1444
1445       // Reverse the bitlist.
1446       std::reverse(Ranges.begin(), Ranges.end());
1447       Result = Result->convertInitializerBitRange(Ranges);
1448       if (Result == 0) {
1449         Error(CurlyLoc, "Invalid bit range for value");
1450         return 0;
1451       }
1452
1453       // Eat the '}'.
1454       if (Lex.getCode() != tgtok::r_brace) {
1455         TokError("expected '}' at end of bit range list");
1456         return 0;
1457       }
1458       Lex.Lex();
1459       break;
1460     }
1461     case tgtok::l_square: {
1462       SMLoc SquareLoc = Lex.getLoc();
1463       Lex.Lex(); // eat the '['
1464       std::vector<unsigned> Ranges = ParseRangeList();
1465       if (Ranges.empty()) return 0;
1466
1467       Result = Result->convertInitListSlice(Ranges);
1468       if (Result == 0) {
1469         Error(SquareLoc, "Invalid range for list slice");
1470         return 0;
1471       }
1472
1473       // Eat the ']'.
1474       if (Lex.getCode() != tgtok::r_square) {
1475         TokError("expected ']' at end of list slice");
1476         return 0;
1477       }
1478       Lex.Lex();
1479       break;
1480     }
1481     case tgtok::period:
1482       if (Lex.Lex() != tgtok::Id) {  // eat the .
1483         TokError("expected field identifier after '.'");
1484         return 0;
1485       }
1486       if (!Result->getFieldType(Lex.getCurStrVal())) {
1487         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1488                  Result->getAsString() + "'");
1489         return 0;
1490       }
1491       Result = FieldInit::get(Result, Lex.getCurStrVal());
1492       Lex.Lex();  // eat field name
1493       break;
1494
1495     case tgtok::paste:
1496       SMLoc PasteLoc = Lex.getLoc();
1497
1498       // Create a !strconcat() operation, first casting each operand to
1499       // a string if necessary.
1500
1501       TypedInit *LHS = dyn_cast<TypedInit>(Result);
1502       if (!LHS) {
1503         Error(PasteLoc, "LHS of paste is not typed!");
1504         return 0;
1505       }
1506   
1507       if (LHS->getType() != StringRecTy::get()) {
1508         LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1509       }
1510
1511       TypedInit *RHS = 0;
1512
1513       Lex.Lex();  // Eat the '#'.
1514       switch (Lex.getCode()) { 
1515       case tgtok::colon:
1516       case tgtok::semi:
1517       case tgtok::l_brace:
1518         // These are all of the tokens that can begin an object body.
1519         // Some of these can also begin values but we disallow those cases
1520         // because they are unlikely to be useful.
1521        
1522         // Trailing paste, concat with an empty string.
1523         RHS = StringInit::get("");
1524         break;
1525
1526       default:
1527         Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1528         RHS = dyn_cast<TypedInit>(RHSResult);
1529         if (!RHS) {
1530           Error(PasteLoc, "RHS of paste is not typed!");
1531           return 0;
1532         }
1533
1534         if (RHS->getType() != StringRecTy::get()) {
1535           RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1536         }
1537   
1538         break;
1539       }
1540
1541       Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1542                               StringRecTy::get())->Fold(CurRec, CurMultiClass);
1543       break;
1544     }
1545   }
1546 }
1547
1548 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1549 ///
1550 ///    ParseDagArgList ::= Value (':' VARNAME)?
1551 ///    ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1552 std::vector<std::pair<llvm::Init*, std::string> >
1553 TGParser::ParseDagArgList(Record *CurRec) {
1554   std::vector<std::pair<llvm::Init*, std::string> > Result;
1555
1556   while (1) {
1557     Init *Val = ParseValue(CurRec);
1558     if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1559
1560     // If the variable name is present, add it.
1561     std::string VarName;
1562     if (Lex.getCode() == tgtok::colon) {
1563       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1564         TokError("expected variable name in dag literal");
1565         return std::vector<std::pair<llvm::Init*, std::string> >();
1566       }
1567       VarName = Lex.getCurStrVal();
1568       Lex.Lex();  // eat the VarName.
1569     }
1570
1571     Result.push_back(std::make_pair(Val, VarName));
1572
1573     if (Lex.getCode() != tgtok::comma) break;
1574     Lex.Lex(); // eat the ','
1575   }
1576
1577   return Result;
1578 }
1579
1580
1581 /// ParseValueList - Parse a comma separated list of values, returning them as a
1582 /// vector.  Note that this always expects to be able to parse at least one
1583 /// value.  It returns an empty list if this is not possible.
1584 ///
1585 ///   ValueList ::= Value (',' Value)
1586 ///
1587 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1588                                             RecTy *EltTy) {
1589   std::vector<Init*> Result;
1590   RecTy *ItemType = EltTy;
1591   unsigned int ArgN = 0;
1592   if (ArgsRec != 0 && EltTy == 0) {
1593     const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1594     if (!TArgs.size()) {
1595       TokError("template argument provided to non-template class");
1596       return std::vector<Init*>();
1597     }
1598     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1599     if (!RV) {
1600       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1601         << ")\n";
1602     }
1603     assert(RV && "Template argument record not found??");
1604     ItemType = RV->getType();
1605     ++ArgN;
1606   }
1607   Result.push_back(ParseValue(CurRec, ItemType));
1608   if (Result.back() == 0) return std::vector<Init*>();
1609
1610   while (Lex.getCode() == tgtok::comma) {
1611     Lex.Lex();  // Eat the comma
1612
1613     if (ArgsRec != 0 && EltTy == 0) {
1614       const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1615       if (ArgN >= TArgs.size()) {
1616         TokError("too many template arguments");
1617         return std::vector<Init*>();
1618       }
1619       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1620       assert(RV && "Template argument record not found??");
1621       ItemType = RV->getType();
1622       ++ArgN;
1623     }
1624     Result.push_back(ParseValue(CurRec, ItemType));
1625     if (Result.back() == 0) return std::vector<Init*>();
1626   }
1627
1628   return Result;
1629 }
1630
1631
1632 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1633 /// empty string on error.  This can happen in a number of different context's,
1634 /// including within a def or in the template args for a def (which which case
1635 /// CurRec will be non-null) and within the template args for a multiclass (in
1636 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1637 /// also happen within a def that is within a multiclass, which will set both
1638 /// CurRec and CurMultiClass.
1639 ///
1640 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1641 ///
1642 Init *TGParser::ParseDeclaration(Record *CurRec,
1643                                        bool ParsingTemplateArgs) {
1644   // Read the field prefix if present.
1645   bool HasField = Lex.getCode() == tgtok::Field;
1646   if (HasField) Lex.Lex();
1647
1648   RecTy *Type = ParseType();
1649   if (Type == 0) return 0;
1650
1651   if (Lex.getCode() != tgtok::Id) {
1652     TokError("Expected identifier in declaration");
1653     return 0;
1654   }
1655
1656   SMLoc IdLoc = Lex.getLoc();
1657   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1658   Lex.Lex();
1659
1660   if (ParsingTemplateArgs) {
1661     if (CurRec) {
1662       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1663     } else {
1664       assert(CurMultiClass);
1665     }
1666     if (CurMultiClass)
1667       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1668                              "::");
1669   }
1670
1671   // Add the value.
1672   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1673     return 0;
1674
1675   // If a value is present, parse it.
1676   if (Lex.getCode() == tgtok::equal) {
1677     Lex.Lex();
1678     SMLoc ValLoc = Lex.getLoc();
1679     Init *Val = ParseValue(CurRec, Type);
1680     if (Val == 0 ||
1681         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1682       return 0;
1683   }
1684
1685   return DeclName;
1686 }
1687
1688 /// ParseForeachDeclaration - Read a foreach declaration, returning
1689 /// the name of the declared object or a NULL Init on error.  Return
1690 /// the name of the parsed initializer list through ForeachListName.
1691 ///
1692 ///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
1693 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
1694 ///  ForeachDeclaration ::= ID '=' RangePiece
1695 ///
1696 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1697   if (Lex.getCode() != tgtok::Id) {
1698     TokError("Expected identifier in foreach declaration");
1699     return 0;
1700   }
1701
1702   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1703   Lex.Lex();
1704
1705   // If a value is present, parse it.
1706   if (Lex.getCode() != tgtok::equal) {
1707     TokError("Expected '=' in foreach declaration");
1708     return 0;
1709   }
1710   Lex.Lex();  // Eat the '='
1711
1712   RecTy *IterType = 0;
1713   std::vector<unsigned> Ranges;
1714
1715   switch (Lex.getCode()) {
1716   default: TokError("Unknown token when expecting a range list"); return 0;
1717   case tgtok::l_square: { // '[' ValueList ']'
1718     Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1719     ForeachListValue = dyn_cast<ListInit>(List);
1720     if (ForeachListValue == 0) {
1721       TokError("Expected a Value list");
1722       return 0;
1723     }
1724     RecTy *ValueType = ForeachListValue->getType();
1725     ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1726     if (ListType == 0) {
1727       TokError("Value list is not of list type");
1728       return 0;
1729     }
1730     IterType = ListType->getElementType();
1731     break;
1732   }
1733
1734   case tgtok::IntVal: { // RangePiece.
1735     if (ParseRangePiece(Ranges))
1736       return 0;
1737     break;
1738   }
1739
1740   case tgtok::l_brace: { // '{' RangeList '}'
1741     Lex.Lex(); // eat the '{'
1742     Ranges = ParseRangeList();
1743     if (Lex.getCode() != tgtok::r_brace) {
1744       TokError("expected '}' at end of bit range list");
1745       return 0;
1746     }
1747     Lex.Lex();
1748     break;
1749   }
1750   }
1751
1752   if (!Ranges.empty()) {
1753     assert(!IterType && "Type already initialized?");
1754     IterType = IntRecTy::get();
1755     std::vector<Init*> Values;
1756     for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1757       Values.push_back(IntInit::get(Ranges[i]));
1758     ForeachListValue = ListInit::get(Values, IterType);
1759   }
1760
1761   if (!IterType)
1762     return 0;
1763
1764   return VarInit::get(DeclName, IterType);
1765 }
1766
1767 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1768 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1769 /// template args for a def, which may or may not be in a multiclass.  If null,
1770 /// these are the template args for a multiclass.
1771 ///
1772 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1773 ///
1774 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1775   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1776   Lex.Lex(); // eat the '<'
1777
1778   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1779
1780   // Read the first declaration.
1781   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1782   if (TemplArg == 0)
1783     return true;
1784
1785   TheRecToAddTo->addTemplateArg(TemplArg);
1786
1787   while (Lex.getCode() == tgtok::comma) {
1788     Lex.Lex(); // eat the ','
1789
1790     // Read the following declarations.
1791     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1792     if (TemplArg == 0)
1793       return true;
1794     TheRecToAddTo->addTemplateArg(TemplArg);
1795   }
1796
1797   if (Lex.getCode() != tgtok::greater)
1798     return TokError("expected '>' at end of template argument list");
1799   Lex.Lex(); // eat the '>'.
1800   return false;
1801 }
1802
1803
1804 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1805 ///
1806 ///   BodyItem ::= Declaration ';'
1807 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1808 bool TGParser::ParseBodyItem(Record *CurRec) {
1809   if (Lex.getCode() != tgtok::Let) {
1810     if (ParseDeclaration(CurRec, false) == 0)
1811       return true;
1812
1813     if (Lex.getCode() != tgtok::semi)
1814       return TokError("expected ';' after declaration");
1815     Lex.Lex();
1816     return false;
1817   }
1818
1819   // LET ID OptionalRangeList '=' Value ';'
1820   if (Lex.Lex() != tgtok::Id)
1821     return TokError("expected field identifier after let");
1822
1823   SMLoc IdLoc = Lex.getLoc();
1824   std::string FieldName = Lex.getCurStrVal();
1825   Lex.Lex();  // eat the field name.
1826
1827   std::vector<unsigned> BitList;
1828   if (ParseOptionalBitList(BitList))
1829     return true;
1830   std::reverse(BitList.begin(), BitList.end());
1831
1832   if (Lex.getCode() != tgtok::equal)
1833     return TokError("expected '=' in let expression");
1834   Lex.Lex();  // eat the '='.
1835
1836   RecordVal *Field = CurRec->getValue(FieldName);
1837   if (Field == 0)
1838     return TokError("Value '" + FieldName + "' unknown!");
1839
1840   RecTy *Type = Field->getType();
1841
1842   Init *Val = ParseValue(CurRec, Type);
1843   if (Val == 0) return true;
1844
1845   if (Lex.getCode() != tgtok::semi)
1846     return TokError("expected ';' after let expression");
1847   Lex.Lex();
1848
1849   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1850 }
1851
1852 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1853 /// success.
1854 ///
1855 ///   Body     ::= ';'
1856 ///   Body     ::= '{' BodyList '}'
1857 ///   BodyList BodyItem*
1858 ///
1859 bool TGParser::ParseBody(Record *CurRec) {
1860   // If this is a null definition, just eat the semi and return.
1861   if (Lex.getCode() == tgtok::semi) {
1862     Lex.Lex();
1863     return false;
1864   }
1865
1866   if (Lex.getCode() != tgtok::l_brace)
1867     return TokError("Expected ';' or '{' to start body");
1868   // Eat the '{'.
1869   Lex.Lex();
1870
1871   while (Lex.getCode() != tgtok::r_brace)
1872     if (ParseBodyItem(CurRec))
1873       return true;
1874
1875   // Eat the '}'.
1876   Lex.Lex();
1877   return false;
1878 }
1879
1880 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1881 /// optional ClassList followed by a Body.  CurRec is the current def or class
1882 /// that is being parsed.
1883 ///
1884 ///   ObjectBody      ::= BaseClassList Body
1885 ///   BaseClassList   ::= /*empty*/
1886 ///   BaseClassList   ::= ':' BaseClassListNE
1887 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1888 ///
1889 bool TGParser::ParseObjectBody(Record *CurRec) {
1890   // If there is a baseclass list, read it.
1891   if (Lex.getCode() == tgtok::colon) {
1892     Lex.Lex();
1893
1894     // Read all of the subclasses.
1895     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1896     while (1) {
1897       // Check for error.
1898       if (SubClass.Rec == 0) return true;
1899
1900       // Add it.
1901       if (AddSubClass(CurRec, SubClass))
1902         return true;
1903
1904       if (Lex.getCode() != tgtok::comma) break;
1905       Lex.Lex(); // eat ','.
1906       SubClass = ParseSubClassReference(CurRec, false);
1907     }
1908   }
1909
1910   // Process any variables on the let stack.
1911   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1912     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1913       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1914                    LetStack[i][j].Bits, LetStack[i][j].Value))
1915         return true;
1916
1917   return ParseBody(CurRec);
1918 }
1919
1920 /// ParseDef - Parse and return a top level or multiclass def, return the record
1921 /// corresponding to it.  This returns null on error.
1922 ///
1923 ///   DefInst ::= DEF ObjectName ObjectBody
1924 ///
1925 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1926   SMLoc DefLoc = Lex.getLoc();
1927   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1928   Lex.Lex();  // Eat the 'def' token.
1929
1930   // Parse ObjectName and make a record for it.
1931   Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1932
1933   if (!CurMultiClass && Loops.empty()) {
1934     // Top-level def definition.
1935
1936     // Ensure redefinition doesn't happen.
1937     if (Records.getDef(CurRec->getNameInitAsString())) {
1938       Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1939             + "' already defined");
1940       return true;
1941     }
1942     Records.addDef(CurRec);
1943   } else if (CurMultiClass) {
1944     // Otherwise, a def inside a multiclass, add it to the multiclass.
1945     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1946       if (CurMultiClass->DefPrototypes[i]->getNameInit()
1947           == CurRec->getNameInit()) {
1948         Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1949               "' already defined in this multiclass!");
1950         return true;
1951       }
1952     CurMultiClass->DefPrototypes.push_back(CurRec);
1953   }
1954
1955   if (ParseObjectBody(CurRec))
1956     return true;
1957
1958   if (CurMultiClass == 0)  // Def's in multiclasses aren't really defs.
1959     // See Record::setName().  This resolve step will see any new name
1960     // for the def that might have been created when resolving
1961     // inheritance, values and arguments above.
1962     CurRec->resolveReferences();
1963
1964   // If ObjectBody has template arguments, it's an error.
1965   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1966
1967   if (CurMultiClass) {
1968     // Copy the template arguments for the multiclass into the def.
1969     const std::vector<Init *> &TArgs =
1970                                 CurMultiClass->Rec.getTemplateArgs();
1971
1972     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1973       const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1974       assert(RV && "Template arg doesn't exist?");
1975       CurRec->addValue(*RV);
1976     }
1977   }
1978
1979   if (ProcessForeachDefs(CurRec, DefLoc)) {
1980     Error(DefLoc,
1981           "Could not process loops for def" + CurRec->getNameInitAsString());
1982     return true;
1983   }
1984
1985   return false;
1986 }
1987
1988 /// ParseForeach - Parse a for statement.  Return the record corresponding
1989 /// to it.  This returns true on error.
1990 ///
1991 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1992 ///   Foreach ::= FOREACH Declaration IN Object
1993 ///
1994 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1995   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1996   Lex.Lex();  // Eat the 'for' token.
1997
1998   // Make a temporary object to record items associated with the for
1999   // loop.
2000   ListInit *ListValue = 0;
2001   VarInit *IterName = ParseForeachDeclaration(ListValue);
2002   if (IterName == 0)
2003     return TokError("expected declaration in for");
2004
2005   if (Lex.getCode() != tgtok::In)
2006     return TokError("Unknown tok");
2007   Lex.Lex();  // Eat the in
2008
2009   // Create a loop object and remember it.
2010   Loops.push_back(ForeachLoop(IterName, ListValue));
2011
2012   if (Lex.getCode() != tgtok::l_brace) {
2013     // FOREACH Declaration IN Object
2014     if (ParseObject(CurMultiClass))
2015       return true;
2016   }
2017   else {
2018     SMLoc BraceLoc = Lex.getLoc();
2019     // Otherwise, this is a group foreach.
2020     Lex.Lex();  // eat the '{'.
2021
2022     // Parse the object list.
2023     if (ParseObjectList(CurMultiClass))
2024       return true;
2025
2026     if (Lex.getCode() != tgtok::r_brace) {
2027       TokError("expected '}' at end of foreach command");
2028       return Error(BraceLoc, "to match this '{'");
2029     }
2030     Lex.Lex();  // Eat the }
2031   }
2032
2033   // We've processed everything in this loop.
2034   Loops.pop_back();
2035
2036   return false;
2037 }
2038
2039 /// ParseClass - Parse a tblgen class definition.
2040 ///
2041 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2042 ///
2043 bool TGParser::ParseClass() {
2044   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2045   Lex.Lex();
2046
2047   if (Lex.getCode() != tgtok::Id)
2048     return TokError("expected class name after 'class' keyword");
2049
2050   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2051   if (CurRec) {
2052     // If the body was previously defined, this is an error.
2053     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
2054         !CurRec->getSuperClasses().empty() ||
2055         !CurRec->getTemplateArgs().empty())
2056       return TokError("Class '" + CurRec->getNameInitAsString()
2057                       + "' already defined");
2058   } else {
2059     // If this is the first reference to this class, create and add it.
2060     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2061     Records.addClass(CurRec);
2062   }
2063   Lex.Lex(); // eat the name.
2064
2065   // If there are template args, parse them.
2066   if (Lex.getCode() == tgtok::less)
2067     if (ParseTemplateArgList(CurRec))
2068       return true;
2069
2070   // Finally, parse the object body.
2071   return ParseObjectBody(CurRec);
2072 }
2073
2074 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2075 /// of LetRecords.
2076 ///
2077 ///   LetList ::= LetItem (',' LetItem)*
2078 ///   LetItem ::= ID OptionalRangeList '=' Value
2079 ///
2080 std::vector<LetRecord> TGParser::ParseLetList() {
2081   std::vector<LetRecord> Result;
2082
2083   while (1) {
2084     if (Lex.getCode() != tgtok::Id) {
2085       TokError("expected identifier in let definition");
2086       return std::vector<LetRecord>();
2087     }
2088     std::string Name = Lex.getCurStrVal();
2089     SMLoc NameLoc = Lex.getLoc();
2090     Lex.Lex();  // Eat the identifier.
2091
2092     // Check for an optional RangeList.
2093     std::vector<unsigned> Bits;
2094     if (ParseOptionalRangeList(Bits))
2095       return std::vector<LetRecord>();
2096     std::reverse(Bits.begin(), Bits.end());
2097
2098     if (Lex.getCode() != tgtok::equal) {
2099       TokError("expected '=' in let expression");
2100       return std::vector<LetRecord>();
2101     }
2102     Lex.Lex();  // eat the '='.
2103
2104     Init *Val = ParseValue(0);
2105     if (Val == 0) return std::vector<LetRecord>();
2106
2107     // Now that we have everything, add the record.
2108     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2109
2110     if (Lex.getCode() != tgtok::comma)
2111       return Result;
2112     Lex.Lex();  // eat the comma.
2113   }
2114 }
2115
2116 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2117 /// different related productions. This works inside multiclasses too.
2118 ///
2119 ///   Object ::= LET LetList IN '{' ObjectList '}'
2120 ///   Object ::= LET LetList IN Object
2121 ///
2122 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2123   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2124   Lex.Lex();
2125
2126   // Add this entry to the let stack.
2127   std::vector<LetRecord> LetInfo = ParseLetList();
2128   if (LetInfo.empty()) return true;
2129   LetStack.push_back(LetInfo);
2130
2131   if (Lex.getCode() != tgtok::In)
2132     return TokError("expected 'in' at end of top-level 'let'");
2133   Lex.Lex();
2134
2135   // If this is a scalar let, just handle it now
2136   if (Lex.getCode() != tgtok::l_brace) {
2137     // LET LetList IN Object
2138     if (ParseObject(CurMultiClass))
2139       return true;
2140   } else {   // Object ::= LETCommand '{' ObjectList '}'
2141     SMLoc BraceLoc = Lex.getLoc();
2142     // Otherwise, this is a group let.
2143     Lex.Lex();  // eat the '{'.
2144
2145     // Parse the object list.
2146     if (ParseObjectList(CurMultiClass))
2147       return true;
2148
2149     if (Lex.getCode() != tgtok::r_brace) {
2150       TokError("expected '}' at end of top level let command");
2151       return Error(BraceLoc, "to match this '{'");
2152     }
2153     Lex.Lex();
2154   }
2155
2156   // Outside this let scope, this let block is not active.
2157   LetStack.pop_back();
2158   return false;
2159 }
2160
2161 /// ParseMultiClass - Parse a multiclass definition.
2162 ///
2163 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2164 ///                     ':' BaseMultiClassList '{' MultiClassDef+ '}'
2165 ///
2166 bool TGParser::ParseMultiClass() {
2167   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2168   Lex.Lex();  // Eat the multiclass token.
2169
2170   if (Lex.getCode() != tgtok::Id)
2171     return TokError("expected identifier after multiclass for name");
2172   std::string Name = Lex.getCurStrVal();
2173
2174   if (MultiClasses.count(Name))
2175     return TokError("multiclass '" + Name + "' already defined");
2176
2177   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 
2178                                                       Lex.getLoc(), Records);
2179   Lex.Lex();  // Eat the identifier.
2180
2181   // If there are template args, parse them.
2182   if (Lex.getCode() == tgtok::less)
2183     if (ParseTemplateArgList(0))
2184       return true;
2185
2186   bool inherits = false;
2187
2188   // If there are submulticlasses, parse them.
2189   if (Lex.getCode() == tgtok::colon) {
2190     inherits = true;
2191
2192     Lex.Lex();
2193
2194     // Read all of the submulticlasses.
2195     SubMultiClassReference SubMultiClass =
2196       ParseSubMultiClassReference(CurMultiClass);
2197     while (1) {
2198       // Check for error.
2199       if (SubMultiClass.MC == 0) return true;
2200
2201       // Add it.
2202       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2203         return true;
2204
2205       if (Lex.getCode() != tgtok::comma) break;
2206       Lex.Lex(); // eat ','.
2207       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2208     }
2209   }
2210
2211   if (Lex.getCode() != tgtok::l_brace) {
2212     if (!inherits)
2213       return TokError("expected '{' in multiclass definition");
2214     else if (Lex.getCode() != tgtok::semi)
2215       return TokError("expected ';' in multiclass definition");
2216     else
2217       Lex.Lex();  // eat the ';'.
2218   } else {
2219     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2220       return TokError("multiclass must contain at least one def");
2221
2222     while (Lex.getCode() != tgtok::r_brace) {
2223       switch (Lex.getCode()) {
2224         default:
2225           return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2226         case tgtok::Let:
2227         case tgtok::Def:
2228         case tgtok::Defm:
2229         case tgtok::Foreach:
2230           if (ParseObject(CurMultiClass))
2231             return true;
2232          break;
2233       }
2234     }
2235     Lex.Lex();  // eat the '}'.
2236   }
2237
2238   CurMultiClass = 0;
2239   return false;
2240 }
2241
2242 Record *TGParser::
2243 InstantiateMulticlassDef(MultiClass &MC,
2244                          Record *DefProto,
2245                          Init *DefmPrefix,
2246                          SMLoc DefmPrefixLoc) {
2247   // We need to preserve DefProto so it can be reused for later
2248   // instantiations, so create a new Record to inherit from it.
2249
2250   // Add in the defm name.  If the defm prefix is empty, give each
2251   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
2252   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
2253   // as a prefix.
2254
2255   if (DefmPrefix == 0)
2256     DefmPrefix = StringInit::get(GetNewAnonymousName());
2257
2258   Init *DefName = DefProto->getNameInit();
2259
2260   StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2261
2262   if (DefNameString != 0) {
2263     // We have a fully expanded string so there are no operators to
2264     // resolve.  We should concatenate the given prefix and name.
2265     DefName =
2266       BinOpInit::get(BinOpInit::STRCONCAT,
2267                      UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2268                                    StringRecTy::get())->Fold(DefProto, &MC),
2269                      DefName, StringRecTy::get())->Fold(DefProto, &MC);
2270   }
2271
2272   // Make a trail of SMLocs from the multiclass instantiations.
2273   SmallVector<SMLoc, 4> Locs(1, DefmPrefixLoc);
2274   Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2275   Record *CurRec = new Record(DefName, Locs, Records);
2276
2277   SubClassReference Ref;
2278   Ref.RefLoc = DefmPrefixLoc;
2279   Ref.Rec = DefProto;
2280   AddSubClass(CurRec, Ref);
2281
2282   // Set the value for NAME. We don't resolve references to it 'til later,
2283   // though, so that uses in nested multiclass names don't get
2284   // confused.
2285   if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2286                DefmPrefix)) {
2287     Error(DefmPrefixLoc, "Could not resolve "
2288           + CurRec->getNameInitAsString() + ":NAME to '"
2289           + DefmPrefix->getAsUnquotedString() + "'");
2290     return 0;
2291   }
2292
2293   // If the DefNameString didn't resolve, we probably have a reference to
2294   // NAME and need to replace it. We need to do at least this much greedily,
2295   // otherwise nested multiclasses will end up with incorrect NAME expansions.
2296   if (DefNameString == 0) {
2297     RecordVal *DefNameRV = CurRec->getValue("NAME");
2298     CurRec->resolveReferencesTo(DefNameRV);
2299   }
2300
2301   if (!CurMultiClass) {
2302     // Now that we're at the top level, resolve all NAME references
2303     // in the resultant defs that weren't in the def names themselves.
2304     RecordVal *DefNameRV = CurRec->getValue("NAME");
2305     CurRec->resolveReferencesTo(DefNameRV);
2306
2307     // Now that NAME references are resolved and we're at the top level of
2308     // any multiclass expansions, add the record to the RecordKeeper. If we are
2309     // currently in a multiclass, it means this defm appears inside a
2310     // multiclass and its name won't be fully resolvable until we see
2311     // the top-level defm.  Therefore, we don't add this to the
2312     // RecordKeeper at this point.  If we did we could get duplicate
2313     // defs as more than one probably refers to NAME or some other
2314     // common internal placeholder.
2315
2316     // Ensure redefinition doesn't happen.
2317     if (Records.getDef(CurRec->getNameInitAsString())) {
2318       Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() + 
2319             "' already defined, instantiating defm with subdef '" + 
2320             DefProto->getNameInitAsString() + "'");
2321       return 0;
2322     }
2323
2324     Records.addDef(CurRec);
2325   }
2326
2327   return CurRec;
2328 }
2329
2330 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2331                                         Record *CurRec,
2332                                         SMLoc DefmPrefixLoc,
2333                                         SMLoc SubClassLoc,
2334                                         const std::vector<Init *> &TArgs,
2335                                         std::vector<Init *> &TemplateVals,
2336                                         bool DeleteArgs) {
2337   // Loop over all of the template arguments, setting them to the specified
2338   // value or leaving them as the default if necessary.
2339   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2340     // Check if a value is specified for this temp-arg.
2341     if (i < TemplateVals.size()) {
2342       // Set it now.
2343       if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2344                    TemplateVals[i]))
2345         return true;
2346         
2347       // Resolve it next.
2348       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2349
2350       if (DeleteArgs)
2351         // Now remove it.
2352         CurRec->removeValue(TArgs[i]);
2353         
2354     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2355       return Error(SubClassLoc, "value not specified for template argument #"+
2356                    utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2357                    + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2358                    + "'");
2359     }
2360   }
2361   return false;
2362 }
2363
2364 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2365                                     Record *CurRec,
2366                                     Record *DefProto,
2367                                     SMLoc DefmPrefixLoc) {
2368   // If the mdef is inside a 'let' expression, add to each def.
2369   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2370     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2371       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2372                    LetStack[i][j].Bits, LetStack[i][j].Value))
2373         return Error(DefmPrefixLoc, "when instantiating this defm");
2374
2375   // Don't create a top level definition for defm inside multiclasses,
2376   // instead, only update the prototypes and bind the template args
2377   // with the new created definition.
2378   if (CurMultiClass) {
2379     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2380          i != e; ++i)
2381       if (CurMultiClass->DefPrototypes[i]->getNameInit()
2382           == CurRec->getNameInit())
2383         return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2384                      "' already defined in this multiclass!");
2385     CurMultiClass->DefPrototypes.push_back(CurRec);
2386
2387     // Copy the template arguments for the multiclass into the new def.
2388     const std::vector<Init *> &TA =
2389       CurMultiClass->Rec.getTemplateArgs();
2390
2391     for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2392       const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2393       assert(RV && "Template arg doesn't exist?");
2394       CurRec->addValue(*RV);
2395     }
2396   }
2397
2398   return false;
2399 }
2400
2401 /// ParseDefm - Parse the instantiation of a multiclass.
2402 ///
2403 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2404 ///
2405 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2406   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2407
2408   Init *DefmPrefix = 0;
2409
2410   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
2411     DefmPrefix = ParseObjectName(CurMultiClass);
2412   }
2413
2414   SMLoc DefmPrefixLoc = Lex.getLoc();
2415   if (Lex.getCode() != tgtok::colon)
2416     return TokError("expected ':' after defm identifier");
2417
2418   // Keep track of the new generated record definitions.
2419   std::vector<Record*> NewRecDefs;
2420
2421   // This record also inherits from a regular class (non-multiclass)?
2422   bool InheritFromClass = false;
2423
2424   // eat the colon.
2425   Lex.Lex();
2426
2427   SMLoc SubClassLoc = Lex.getLoc();
2428   SubClassReference Ref = ParseSubClassReference(0, true);
2429
2430   while (1) {
2431     if (Ref.Rec == 0) return true;
2432
2433     // To instantiate a multiclass, we need to first get the multiclass, then
2434     // instantiate each def contained in the multiclass with the SubClassRef
2435     // template parameters.
2436     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2437     assert(MC && "Didn't lookup multiclass correctly?");
2438     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2439
2440     // Verify that the correct number of template arguments were specified.
2441     const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2442     if (TArgs.size() < TemplateVals.size())
2443       return Error(SubClassLoc,
2444                    "more template args specified than multiclass expects");
2445
2446     // Loop over all the def's in the multiclass, instantiating each one.
2447     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2448       Record *DefProto = MC->DefPrototypes[i];
2449
2450       Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2451       if (!CurRec)
2452         return true;
2453
2454       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2455                                    TArgs, TemplateVals, true/*Delete args*/))
2456         return Error(SubClassLoc, "could not instantiate def");
2457
2458       if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2459         return Error(SubClassLoc, "could not instantiate def");
2460
2461       NewRecDefs.push_back(CurRec);
2462     }
2463
2464
2465     if (Lex.getCode() != tgtok::comma) break;
2466     Lex.Lex(); // eat ','.
2467
2468     SubClassLoc = Lex.getLoc();
2469
2470     // A defm can inherit from regular classes (non-multiclass) as
2471     // long as they come in the end of the inheritance list.
2472     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2473
2474     if (InheritFromClass)
2475       break;
2476
2477     Ref = ParseSubClassReference(0, true);
2478   }
2479
2480   if (InheritFromClass) {
2481     // Process all the classes to inherit as if they were part of a
2482     // regular 'def' and inherit all record values.
2483     SubClassReference SubClass = ParseSubClassReference(0, false);
2484     while (1) {
2485       // Check for error.
2486       if (SubClass.Rec == 0) return true;
2487
2488       // Get the expanded definition prototypes and teach them about
2489       // the record values the current class to inherit has
2490       for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2491         Record *CurRec = NewRecDefs[i];
2492
2493         // Add it.
2494         if (AddSubClass(CurRec, SubClass))
2495           return true;
2496
2497         // Process any variables on the let stack.
2498         for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2499           for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2500             if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2501                          LetStack[i][j].Bits, LetStack[i][j].Value))
2502               return true;
2503       }
2504
2505       if (Lex.getCode() != tgtok::comma) break;
2506       Lex.Lex(); // eat ','.
2507       SubClass = ParseSubClassReference(0, false);
2508     }
2509   }
2510
2511   if (!CurMultiClass)
2512     for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2513       // See Record::setName().  This resolve step will see any new
2514       // name for the def that might have been created when resolving
2515       // inheritance, values and arguments above.
2516       NewRecDefs[i]->resolveReferences();
2517
2518   if (Lex.getCode() != tgtok::semi)
2519     return TokError("expected ';' at end of defm");
2520   Lex.Lex();
2521
2522   return false;
2523 }
2524
2525 /// ParseObject
2526 ///   Object ::= ClassInst
2527 ///   Object ::= DefInst
2528 ///   Object ::= MultiClassInst
2529 ///   Object ::= DefMInst
2530 ///   Object ::= LETCommand '{' ObjectList '}'
2531 ///   Object ::= LETCommand Object
2532 bool TGParser::ParseObject(MultiClass *MC) {
2533   switch (Lex.getCode()) {
2534   default:
2535     return TokError("Expected class, def, defm, multiclass or let definition");
2536   case tgtok::Let:   return ParseTopLevelLet(MC);
2537   case tgtok::Def:   return ParseDef(MC);
2538   case tgtok::Foreach:   return ParseForeach(MC);
2539   case tgtok::Defm:  return ParseDefm(MC);
2540   case tgtok::Class: return ParseClass();
2541   case tgtok::MultiClass: return ParseMultiClass();
2542   }
2543 }
2544
2545 /// ParseObjectList
2546 ///   ObjectList :== Object*
2547 bool TGParser::ParseObjectList(MultiClass *MC) {
2548   while (isObjectStart(Lex.getCode())) {
2549     if (ParseObject(MC))
2550       return true;
2551   }
2552   return false;
2553 }
2554
2555 bool TGParser::ParseFile() {
2556   Lex.Lex(); // Prime the lexer.
2557   if (ParseObjectList()) return true;
2558
2559   // If we have unread input at the end of the file, report it.
2560   if (Lex.getCode() == tgtok::Eof)
2561     return false;
2562
2563   return TokError("Unexpected input at top level");
2564 }
2565