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