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