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