LLParser.cpp revision 5316bf0252ce9797e90a233645b6580695403837
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
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//  This file defines the parser class for .ll files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LLParser.h"
15#include "llvm/AutoUpgrade.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/InlineAsm.h"
20#include "llvm/Instructions.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Metadata.h"
23#include "llvm/Module.h"
24#include "llvm/Operator.h"
25#include "llvm/ValueSymbolTable.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32namespace llvm {
33  /// ValID - Represents a reference of a definition of some sort with no type.
34  /// There are several cases where we have to parse the value but where the
35  /// type can depend on later context.  This may either be a numeric reference
36  /// or a symbolic (%var) reference.  This is just a discriminated union.
37  struct ValID {
38    enum {
39      t_LocalID, t_GlobalID,      // ID in UIntVal.
40      t_LocalName, t_GlobalName,  // Name in StrVal.
41      t_APSInt, t_APFloat,        // Value in APSIntVal/APFloatVal.
42      t_Null, t_Undef, t_Zero,    // No value.
43      t_EmptyArray,               // No value:  []
44      t_Constant,                 // Value in ConstantVal.
45      t_InlineAsm,                // Value in StrVal/StrVal2/UIntVal.
46      t_Metadata                  // Value in MetadataVal.
47    } Kind;
48
49    LLParser::LocTy Loc;
50    unsigned UIntVal;
51    std::string StrVal, StrVal2;
52    APSInt APSIntVal;
53    APFloat APFloatVal;
54    Constant *ConstantVal;
55    MetadataBase *MetadataVal;
56    ValID() : APFloatVal(0.0) {}
57  };
58}
59
60/// Run: module ::= toplevelentity*
61bool LLParser::Run() {
62  // Prime the lexer.
63  Lex.Lex();
64
65  return ParseTopLevelEntities() ||
66         ValidateEndOfModule();
67}
68
69/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
70/// module.
71bool LLParser::ValidateEndOfModule() {
72  if (!ForwardRefTypes.empty())
73    return Error(ForwardRefTypes.begin()->second.second,
74                 "use of undefined type named '" +
75                 ForwardRefTypes.begin()->first + "'");
76  if (!ForwardRefTypeIDs.empty())
77    return Error(ForwardRefTypeIDs.begin()->second.second,
78                 "use of undefined type '%" +
79                 utostr(ForwardRefTypeIDs.begin()->first) + "'");
80
81  if (!ForwardRefVals.empty())
82    return Error(ForwardRefVals.begin()->second.second,
83                 "use of undefined value '@" + ForwardRefVals.begin()->first +
84                 "'");
85
86  if (!ForwardRefValIDs.empty())
87    return Error(ForwardRefValIDs.begin()->second.second,
88                 "use of undefined value '@" +
89                 utostr(ForwardRefValIDs.begin()->first) + "'");
90
91  if (!ForwardRefMDNodes.empty())
92    return Error(ForwardRefMDNodes.begin()->second.second,
93                 "use of undefined metadata '!" +
94                 utostr(ForwardRefMDNodes.begin()->first) + "'");
95
96
97  // Look for intrinsic functions and CallInst that need to be upgraded
98  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
100
101  return false;
102}
103
104//===----------------------------------------------------------------------===//
105// Top-Level Entities
106//===----------------------------------------------------------------------===//
107
108bool LLParser::ParseTopLevelEntities() {
109  while (1) {
110    switch (Lex.getKind()) {
111    default:         return TokError("expected top-level entity");
112    case lltok::Eof: return false;
113    //case lltok::kw_define:
114    case lltok::kw_declare: if (ParseDeclare()) return true; break;
115    case lltok::kw_define:  if (ParseDefine()) return true; break;
116    case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
117    case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
118    case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119    case lltok::kw_type:    if (ParseUnnamedType()) return true; break;
120    case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
121    case lltok::LocalVar:   if (ParseNamedType()) return true; break;
122    case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
123    case lltok::Metadata:   if (ParseStandaloneMetadata()) return true; break;
124    case lltok::NamedMD:    if (ParseNamedMetadata()) return true; break;
125
126    // The Global variable production with no name can have many different
127    // optional leading prefixes, the production is:
128    // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
129    //               OptionalAddrSpace ('constant'|'global') ...
130    case lltok::kw_private :       // OptionalLinkage
131    case lltok::kw_linker_private: // OptionalLinkage
132    case lltok::kw_internal:       // OptionalLinkage
133    case lltok::kw_weak:           // OptionalLinkage
134    case lltok::kw_weak_odr:       // OptionalLinkage
135    case lltok::kw_linkonce:       // OptionalLinkage
136    case lltok::kw_linkonce_odr:   // OptionalLinkage
137    case lltok::kw_appending:      // OptionalLinkage
138    case lltok::kw_dllexport:      // OptionalLinkage
139    case lltok::kw_common:         // OptionalLinkage
140    case lltok::kw_dllimport:      // OptionalLinkage
141    case lltok::kw_extern_weak:    // OptionalLinkage
142    case lltok::kw_external: {     // OptionalLinkage
143      unsigned Linkage, Visibility;
144      if (ParseOptionalLinkage(Linkage) ||
145          ParseOptionalVisibility(Visibility) ||
146          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
147        return true;
148      break;
149    }
150    case lltok::kw_default:       // OptionalVisibility
151    case lltok::kw_hidden:        // OptionalVisibility
152    case lltok::kw_protected: {   // OptionalVisibility
153      unsigned Visibility;
154      if (ParseOptionalVisibility(Visibility) ||
155          ParseGlobal("", SMLoc(), 0, false, Visibility))
156        return true;
157      break;
158    }
159
160    case lltok::kw_thread_local:  // OptionalThreadLocal
161    case lltok::kw_addrspace:     // OptionalAddrSpace
162    case lltok::kw_constant:      // GlobalType
163    case lltok::kw_global:        // GlobalType
164      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
165      break;
166    }
167  }
168}
169
170
171/// toplevelentity
172///   ::= 'module' 'asm' STRINGCONSTANT
173bool LLParser::ParseModuleAsm() {
174  assert(Lex.getKind() == lltok::kw_module);
175  Lex.Lex();
176
177  std::string AsmStr;
178  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
179      ParseStringConstant(AsmStr)) return true;
180
181  const std::string &AsmSoFar = M->getModuleInlineAsm();
182  if (AsmSoFar.empty())
183    M->setModuleInlineAsm(AsmStr);
184  else
185    M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
186  return false;
187}
188
189/// toplevelentity
190///   ::= 'target' 'triple' '=' STRINGCONSTANT
191///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
192bool LLParser::ParseTargetDefinition() {
193  assert(Lex.getKind() == lltok::kw_target);
194  std::string Str;
195  switch (Lex.Lex()) {
196  default: return TokError("unknown target property");
197  case lltok::kw_triple:
198    Lex.Lex();
199    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
200        ParseStringConstant(Str))
201      return true;
202    M->setTargetTriple(Str);
203    return false;
204  case lltok::kw_datalayout:
205    Lex.Lex();
206    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
207        ParseStringConstant(Str))
208      return true;
209    M->setDataLayout(Str);
210    return false;
211  }
212}
213
214/// toplevelentity
215///   ::= 'deplibs' '=' '[' ']'
216///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
217bool LLParser::ParseDepLibs() {
218  assert(Lex.getKind() == lltok::kw_deplibs);
219  Lex.Lex();
220  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
221      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
222    return true;
223
224  if (EatIfPresent(lltok::rsquare))
225    return false;
226
227  std::string Str;
228  if (ParseStringConstant(Str)) return true;
229  M->addLibrary(Str);
230
231  while (EatIfPresent(lltok::comma)) {
232    if (ParseStringConstant(Str)) return true;
233    M->addLibrary(Str);
234  }
235
236  return ParseToken(lltok::rsquare, "expected ']' at end of list");
237}
238
239/// toplevelentity
240///   ::= 'type' type
241bool LLParser::ParseUnnamedType() {
242  assert(Lex.getKind() == lltok::kw_type);
243  LocTy TypeLoc = Lex.getLoc();
244  Lex.Lex(); // eat kw_type
245
246  PATypeHolder Ty(Type::VoidTy);
247  if (ParseType(Ty)) return true;
248
249  unsigned TypeID = NumberedTypes.size();
250
251  // See if this type was previously referenced.
252  std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
253    FI = ForwardRefTypeIDs.find(TypeID);
254  if (FI != ForwardRefTypeIDs.end()) {
255    if (FI->second.first.get() == Ty)
256      return Error(TypeLoc, "self referential type is invalid");
257
258    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
259    Ty = FI->second.first.get();
260    ForwardRefTypeIDs.erase(FI);
261  }
262
263  NumberedTypes.push_back(Ty);
264
265  return false;
266}
267
268/// toplevelentity
269///   ::= LocalVar '=' 'type' type
270bool LLParser::ParseNamedType() {
271  std::string Name = Lex.getStrVal();
272  LocTy NameLoc = Lex.getLoc();
273  Lex.Lex();  // eat LocalVar.
274
275  PATypeHolder Ty(Type::VoidTy);
276
277  if (ParseToken(lltok::equal, "expected '=' after name") ||
278      ParseToken(lltok::kw_type, "expected 'type' after name") ||
279      ParseType(Ty))
280    return true;
281
282  // Set the type name, checking for conflicts as we do so.
283  bool AlreadyExists = M->addTypeName(Name, Ty);
284  if (!AlreadyExists) return false;
285
286  // See if this type is a forward reference.  We need to eagerly resolve
287  // types to allow recursive type redefinitions below.
288  std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
289  FI = ForwardRefTypes.find(Name);
290  if (FI != ForwardRefTypes.end()) {
291    if (FI->second.first.get() == Ty)
292      return Error(NameLoc, "self referential type is invalid");
293
294    cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
295    Ty = FI->second.first.get();
296    ForwardRefTypes.erase(FI);
297  }
298
299  // Inserting a name that is already defined, get the existing name.
300  const Type *Existing = M->getTypeByName(Name);
301  assert(Existing && "Conflict but no matching type?!");
302
303  // Otherwise, this is an attempt to redefine a type. That's okay if
304  // the redefinition is identical to the original.
305  // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
306  if (Existing == Ty) return false;
307
308  // Any other kind of (non-equivalent) redefinition is an error.
309  return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
310               Ty->getDescription() + "'");
311}
312
313
314/// toplevelentity
315///   ::= 'declare' FunctionHeader
316bool LLParser::ParseDeclare() {
317  assert(Lex.getKind() == lltok::kw_declare);
318  Lex.Lex();
319
320  Function *F;
321  return ParseFunctionHeader(F, false);
322}
323
324/// toplevelentity
325///   ::= 'define' FunctionHeader '{' ...
326bool LLParser::ParseDefine() {
327  assert(Lex.getKind() == lltok::kw_define);
328  Lex.Lex();
329
330  Function *F;
331  return ParseFunctionHeader(F, true) ||
332         ParseFunctionBody(*F);
333}
334
335/// ParseGlobalType
336///   ::= 'constant'
337///   ::= 'global'
338bool LLParser::ParseGlobalType(bool &IsConstant) {
339  if (Lex.getKind() == lltok::kw_constant)
340    IsConstant = true;
341  else if (Lex.getKind() == lltok::kw_global)
342    IsConstant = false;
343  else {
344    IsConstant = false;
345    return TokError("expected 'global' or 'constant'");
346  }
347  Lex.Lex();
348  return false;
349}
350
351/// ParseNamedGlobal:
352///   GlobalVar '=' OptionalVisibility ALIAS ...
353///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
354bool LLParser::ParseNamedGlobal() {
355  assert(Lex.getKind() == lltok::GlobalVar);
356  LocTy NameLoc = Lex.getLoc();
357  std::string Name = Lex.getStrVal();
358  Lex.Lex();
359
360  bool HasLinkage;
361  unsigned Linkage, Visibility;
362  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
363      ParseOptionalLinkage(Linkage, HasLinkage) ||
364      ParseOptionalVisibility(Visibility))
365    return true;
366
367  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
368    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
369  return ParseAlias(Name, NameLoc, Visibility);
370}
371
372// MDString:
373//   ::= '!' STRINGCONSTANT
374bool LLParser::ParseMDString(MetadataBase *&MDS) {
375  std::string Str;
376  if (ParseStringConstant(Str)) return true;
377  MDS = Context.getMDString(Str);
378  return false;
379}
380
381// MDNode:
382//   ::= '!' MDNodeNumber
383bool LLParser::ParseMDNode(MetadataBase *&Node) {
384  // !{ ..., !42, ... }
385  unsigned MID = 0;
386  if (ParseUInt32(MID))  return true;
387
388  // Check existing MDNode.
389  std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
390  if (I != MetadataCache.end()) {
391    Node = I->second;
392    return false;
393  }
394
395  // Check known forward references.
396  std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
397    FI = ForwardRefMDNodes.find(MID);
398  if (FI != ForwardRefMDNodes.end()) {
399    Node = FI->second.first;
400    return false;
401  }
402
403  // Create MDNode forward reference
404  SmallVector<Value *, 1> Elts;
405  std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
406  Elts.push_back(Context.getMDString(FwdRefName));
407  MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
408  ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
409  Node = FwdNode;
410  return false;
411}
412
413///ParseNamedMetadata:
414///   !foo = !{ !1, !2 }
415bool LLParser::ParseNamedMetadata() {
416  assert(Lex.getKind() == lltok::NamedMD);
417  Lex.Lex();
418  std::string Name = Lex.getStrVal();
419
420  if (ParseToken(lltok::equal, "expected '=' here"))
421    return true;
422
423  if (Lex.getKind() != lltok::Metadata)
424    return TokError("Expected '!' here");
425  Lex.Lex();
426
427  if (Lex.getKind() != lltok::lbrace)
428    return TokError("Expected '{' here");
429  Lex.Lex();
430  SmallVector<MetadataBase *, 8> Elts;
431  do {
432    if (Lex.getKind() != lltok::Metadata)
433      return TokError("Expected '!' here");
434    Lex.Lex();
435    MetadataBase *N = 0;
436    if (ParseMDNode(N)) return true;
437    Elts.push_back(N);
438  } while (EatIfPresent(lltok::comma));
439
440  if (ParseToken(lltok::rbrace, "expected end of metadata node"))
441    return true;
442
443  NamedMDNode::Create(Name, Elts.data(), Elts.size(), M);
444  return false;
445}
446
447/// ParseStandaloneMetadata:
448///   !42 = !{...}
449bool LLParser::ParseStandaloneMetadata() {
450  assert(Lex.getKind() == lltok::Metadata);
451  Lex.Lex();
452  unsigned MetadataID = 0;
453  if (ParseUInt32(MetadataID))
454    return true;
455  if (MetadataCache.find(MetadataID) != MetadataCache.end())
456    return TokError("Metadata id is already used");
457  if (ParseToken(lltok::equal, "expected '=' here"))
458    return true;
459
460  LocTy TyLoc;
461  PATypeHolder Ty(Type::VoidTy);
462  if (ParseType(Ty, TyLoc))
463    return true;
464
465  if (Lex.getKind() != lltok::Metadata)
466    return TokError("Expected metadata here");
467
468  Lex.Lex();
469  if (Lex.getKind() != lltok::lbrace)
470    return TokError("Expected '{' here");
471
472  SmallVector<Value *, 16> Elts;
473  if (ParseMDNodeVector(Elts)
474      || ParseToken(lltok::rbrace, "expected end of metadata node"))
475    return true;
476
477  MDNode *Init = Context.getMDNode(Elts.data(), Elts.size());
478  MetadataCache[MetadataID] = Init;
479  std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
480    FI = ForwardRefMDNodes.find(MetadataID);
481  if (FI != ForwardRefMDNodes.end()) {
482    MDNode *FwdNode = cast<MDNode>(FI->second.first);
483    FwdNode->replaceAllUsesWith(Init);
484    ForwardRefMDNodes.erase(FI);
485  }
486
487  return false;
488}
489
490/// ParseAlias:
491///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
492/// Aliasee
493///   ::= TypeAndValue
494///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
495///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
496///
497/// Everything through visibility has already been parsed.
498///
499bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
500                          unsigned Visibility) {
501  assert(Lex.getKind() == lltok::kw_alias);
502  Lex.Lex();
503  unsigned Linkage;
504  LocTy LinkageLoc = Lex.getLoc();
505  if (ParseOptionalLinkage(Linkage))
506    return true;
507
508  if (Linkage != GlobalValue::ExternalLinkage &&
509      Linkage != GlobalValue::WeakAnyLinkage &&
510      Linkage != GlobalValue::WeakODRLinkage &&
511      Linkage != GlobalValue::InternalLinkage &&
512      Linkage != GlobalValue::PrivateLinkage &&
513      Linkage != GlobalValue::LinkerPrivateLinkage)
514    return Error(LinkageLoc, "invalid linkage type for alias");
515
516  Constant *Aliasee;
517  LocTy AliaseeLoc = Lex.getLoc();
518  if (Lex.getKind() != lltok::kw_bitcast &&
519      Lex.getKind() != lltok::kw_getelementptr) {
520    if (ParseGlobalTypeAndValue(Aliasee)) return true;
521  } else {
522    // The bitcast dest type is not present, it is implied by the dest type.
523    ValID ID;
524    if (ParseValID(ID)) return true;
525    if (ID.Kind != ValID::t_Constant)
526      return Error(AliaseeLoc, "invalid aliasee");
527    Aliasee = ID.ConstantVal;
528  }
529
530  if (!isa<PointerType>(Aliasee->getType()))
531    return Error(AliaseeLoc, "alias must have pointer type");
532
533  // Okay, create the alias but do not insert it into the module yet.
534  GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
535                                    (GlobalValue::LinkageTypes)Linkage, Name,
536                                    Aliasee);
537  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
538
539  // See if this value already exists in the symbol table.  If so, it is either
540  // a redefinition or a definition of a forward reference.
541  if (GlobalValue *Val =
542        cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
543    // See if this was a redefinition.  If so, there is no entry in
544    // ForwardRefVals.
545    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
546      I = ForwardRefVals.find(Name);
547    if (I == ForwardRefVals.end())
548      return Error(NameLoc, "redefinition of global named '@" + Name + "'");
549
550    // Otherwise, this was a definition of forward ref.  Verify that types
551    // agree.
552    if (Val->getType() != GA->getType())
553      return Error(NameLoc,
554              "forward reference and definition of alias have different types");
555
556    // If they agree, just RAUW the old value with the alias and remove the
557    // forward ref info.
558    Val->replaceAllUsesWith(GA);
559    Val->eraseFromParent();
560    ForwardRefVals.erase(I);
561  }
562
563  // Insert into the module, we know its name won't collide now.
564  M->getAliasList().push_back(GA);
565  assert(GA->getNameStr() == Name && "Should not be a name conflict!");
566
567  return false;
568}
569
570/// ParseGlobal
571///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
572///       OptionalAddrSpace GlobalType Type Const
573///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
574///       OptionalAddrSpace GlobalType Type Const
575///
576/// Everything through visibility has been parsed already.
577///
578bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
579                           unsigned Linkage, bool HasLinkage,
580                           unsigned Visibility) {
581  unsigned AddrSpace;
582  bool ThreadLocal, IsConstant;
583  LocTy TyLoc;
584
585  PATypeHolder Ty(Type::VoidTy);
586  if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
587      ParseOptionalAddrSpace(AddrSpace) ||
588      ParseGlobalType(IsConstant) ||
589      ParseType(Ty, TyLoc))
590    return true;
591
592  // If the linkage is specified and is external, then no initializer is
593  // present.
594  Constant *Init = 0;
595  if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
596                      Linkage != GlobalValue::ExternalWeakLinkage &&
597                      Linkage != GlobalValue::ExternalLinkage)) {
598    if (ParseGlobalValue(Ty, Init))
599      return true;
600  }
601
602  if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
603    return Error(TyLoc, "invalid type for global variable");
604
605  GlobalVariable *GV = 0;
606
607  // See if the global was forward referenced, if so, use the global.
608  if (!Name.empty()) {
609    if ((GV = M->getGlobalVariable(Name, true)) &&
610        !ForwardRefVals.erase(Name))
611      return Error(NameLoc, "redefinition of global '@" + Name + "'");
612  } else {
613    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
614      I = ForwardRefValIDs.find(NumberedVals.size());
615    if (I != ForwardRefValIDs.end()) {
616      GV = cast<GlobalVariable>(I->second.first);
617      ForwardRefValIDs.erase(I);
618    }
619  }
620
621  if (GV == 0) {
622    GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
623                            Name, 0, false, AddrSpace);
624  } else {
625    if (GV->getType()->getElementType() != Ty)
626      return Error(TyLoc,
627            "forward reference and definition of global have different types");
628
629    // Move the forward-reference to the correct spot in the module.
630    M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
631  }
632
633  if (Name.empty())
634    NumberedVals.push_back(GV);
635
636  // Set the parsed properties on the global.
637  if (Init)
638    GV->setInitializer(Init);
639  GV->setConstant(IsConstant);
640  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
641  GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
642  GV->setThreadLocal(ThreadLocal);
643
644  // Parse attributes on the global.
645  while (Lex.getKind() == lltok::comma) {
646    Lex.Lex();
647
648    if (Lex.getKind() == lltok::kw_section) {
649      Lex.Lex();
650      GV->setSection(Lex.getStrVal());
651      if (ParseToken(lltok::StringConstant, "expected global section string"))
652        return true;
653    } else if (Lex.getKind() == lltok::kw_align) {
654      unsigned Alignment;
655      if (ParseOptionalAlignment(Alignment)) return true;
656      GV->setAlignment(Alignment);
657    } else {
658      TokError("unknown global variable property!");
659    }
660  }
661
662  return false;
663}
664
665
666//===----------------------------------------------------------------------===//
667// GlobalValue Reference/Resolution Routines.
668//===----------------------------------------------------------------------===//
669
670/// GetGlobalVal - Get a value with the specified name or ID, creating a
671/// forward reference record if needed.  This can return null if the value
672/// exists but does not have the right type.
673GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
674                                    LocTy Loc) {
675  const PointerType *PTy = dyn_cast<PointerType>(Ty);
676  if (PTy == 0) {
677    Error(Loc, "global variable reference must have pointer type");
678    return 0;
679  }
680
681  // Look this name up in the normal function symbol table.
682  GlobalValue *Val =
683    cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
684
685  // If this is a forward reference for the value, see if we already created a
686  // forward ref record.
687  if (Val == 0) {
688    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
689      I = ForwardRefVals.find(Name);
690    if (I != ForwardRefVals.end())
691      Val = I->second.first;
692  }
693
694  // If we have the value in the symbol table or fwd-ref table, return it.
695  if (Val) {
696    if (Val->getType() == Ty) return Val;
697    Error(Loc, "'@" + Name + "' defined with type '" +
698          Val->getType()->getDescription() + "'");
699    return 0;
700  }
701
702  // Otherwise, create a new forward reference for this value and remember it.
703  GlobalValue *FwdVal;
704  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
705    // Function types can return opaque but functions can't.
706    if (isa<OpaqueType>(FT->getReturnType())) {
707      Error(Loc, "function may not return opaque type");
708      return 0;
709    }
710
711    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
712  } else {
713    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
714                                GlobalValue::ExternalWeakLinkage, 0, Name);
715  }
716
717  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
718  return FwdVal;
719}
720
721GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
722  const PointerType *PTy = dyn_cast<PointerType>(Ty);
723  if (PTy == 0) {
724    Error(Loc, "global variable reference must have pointer type");
725    return 0;
726  }
727
728  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
729
730  // If this is a forward reference for the value, see if we already created a
731  // forward ref record.
732  if (Val == 0) {
733    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
734      I = ForwardRefValIDs.find(ID);
735    if (I != ForwardRefValIDs.end())
736      Val = I->second.first;
737  }
738
739  // If we have the value in the symbol table or fwd-ref table, return it.
740  if (Val) {
741    if (Val->getType() == Ty) return Val;
742    Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
743          Val->getType()->getDescription() + "'");
744    return 0;
745  }
746
747  // Otherwise, create a new forward reference for this value and remember it.
748  GlobalValue *FwdVal;
749  if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
750    // Function types can return opaque but functions can't.
751    if (isa<OpaqueType>(FT->getReturnType())) {
752      Error(Loc, "function may not return opaque type");
753      return 0;
754    }
755    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
756  } else {
757    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
758                                GlobalValue::ExternalWeakLinkage, 0, "");
759  }
760
761  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
762  return FwdVal;
763}
764
765
766//===----------------------------------------------------------------------===//
767// Helper Routines.
768//===----------------------------------------------------------------------===//
769
770/// ParseToken - If the current token has the specified kind, eat it and return
771/// success.  Otherwise, emit the specified error and return failure.
772bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
773  if (Lex.getKind() != T)
774    return TokError(ErrMsg);
775  Lex.Lex();
776  return false;
777}
778
779/// ParseStringConstant
780///   ::= StringConstant
781bool LLParser::ParseStringConstant(std::string &Result) {
782  if (Lex.getKind() != lltok::StringConstant)
783    return TokError("expected string constant");
784  Result = Lex.getStrVal();
785  Lex.Lex();
786  return false;
787}
788
789/// ParseUInt32
790///   ::= uint32
791bool LLParser::ParseUInt32(unsigned &Val) {
792  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
793    return TokError("expected integer");
794  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
795  if (Val64 != unsigned(Val64))
796    return TokError("expected 32-bit integer (too large)");
797  Val = Val64;
798  Lex.Lex();
799  return false;
800}
801
802
803/// ParseOptionalAddrSpace
804///   := /*empty*/
805///   := 'addrspace' '(' uint32 ')'
806bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
807  AddrSpace = 0;
808  if (!EatIfPresent(lltok::kw_addrspace))
809    return false;
810  return ParseToken(lltok::lparen, "expected '(' in address space") ||
811         ParseUInt32(AddrSpace) ||
812         ParseToken(lltok::rparen, "expected ')' in address space");
813}
814
815/// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKind
816/// indicates what kind of attribute list this is: 0: function arg, 1: result,
817/// 2: function attr.
818/// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
819bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
820  Attrs = Attribute::None;
821  LocTy AttrLoc = Lex.getLoc();
822
823  while (1) {
824    switch (Lex.getKind()) {
825    case lltok::kw_sext:
826    case lltok::kw_zext:
827      // Treat these as signext/zeroext if they occur in the argument list after
828      // the value, as in "call i8 @foo(i8 10 sext)".  If they occur before the
829      // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
830      // expr.
831      // FIXME: REMOVE THIS IN LLVM 3.0
832      if (AttrKind == 3) {
833        if (Lex.getKind() == lltok::kw_sext)
834          Attrs |= Attribute::SExt;
835        else
836          Attrs |= Attribute::ZExt;
837        break;
838      }
839      // FALL THROUGH.
840    default:  // End of attributes.
841      if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
842        return Error(AttrLoc, "invalid use of function-only attribute");
843
844      if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
845        return Error(AttrLoc, "invalid use of parameter-only attribute");
846
847      return false;
848    case lltok::kw_zeroext:         Attrs |= Attribute::ZExt; break;
849    case lltok::kw_signext:         Attrs |= Attribute::SExt; break;
850    case lltok::kw_inreg:           Attrs |= Attribute::InReg; break;
851    case lltok::kw_sret:            Attrs |= Attribute::StructRet; break;
852    case lltok::kw_noalias:         Attrs |= Attribute::NoAlias; break;
853    case lltok::kw_nocapture:       Attrs |= Attribute::NoCapture; break;
854    case lltok::kw_byval:           Attrs |= Attribute::ByVal; break;
855    case lltok::kw_nest:            Attrs |= Attribute::Nest; break;
856
857    case lltok::kw_noreturn:        Attrs |= Attribute::NoReturn; break;
858    case lltok::kw_nounwind:        Attrs |= Attribute::NoUnwind; break;
859    case lltok::kw_noinline:        Attrs |= Attribute::NoInline; break;
860    case lltok::kw_readnone:        Attrs |= Attribute::ReadNone; break;
861    case lltok::kw_readonly:        Attrs |= Attribute::ReadOnly; break;
862    case lltok::kw_alwaysinline:    Attrs |= Attribute::AlwaysInline; break;
863    case lltok::kw_optsize:         Attrs |= Attribute::OptimizeForSize; break;
864    case lltok::kw_ssp:             Attrs |= Attribute::StackProtect; break;
865    case lltok::kw_sspreq:          Attrs |= Attribute::StackProtectReq; break;
866    case lltok::kw_noredzone:       Attrs |= Attribute::NoRedZone; break;
867    case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
868    case lltok::kw_naked:           Attrs |= Attribute::Naked; break;
869
870    case lltok::kw_align: {
871      unsigned Alignment;
872      if (ParseOptionalAlignment(Alignment))
873        return true;
874      Attrs |= Attribute::constructAlignmentFromInt(Alignment);
875      continue;
876    }
877    }
878    Lex.Lex();
879  }
880}
881
882/// ParseOptionalLinkage
883///   ::= /*empty*/
884///   ::= 'private'
885///   ::= 'linker_private'
886///   ::= 'internal'
887///   ::= 'weak'
888///   ::= 'weak_odr'
889///   ::= 'linkonce'
890///   ::= 'linkonce_odr'
891///   ::= 'appending'
892///   ::= 'dllexport'
893///   ::= 'common'
894///   ::= 'dllimport'
895///   ::= 'extern_weak'
896///   ::= 'external'
897bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
898  HasLinkage = false;
899  switch (Lex.getKind()) {
900  default:                       Res=GlobalValue::ExternalLinkage; return false;
901  case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
902  case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
903  case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
904  case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
905  case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
906  case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
907  case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
908  case lltok::kw_available_externally:
909    Res = GlobalValue::AvailableExternallyLinkage;
910    break;
911  case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
912  case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
913  case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
914  case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
915  case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
916  case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
917  }
918  Lex.Lex();
919  HasLinkage = true;
920  return false;
921}
922
923/// ParseOptionalVisibility
924///   ::= /*empty*/
925///   ::= 'default'
926///   ::= 'hidden'
927///   ::= 'protected'
928///
929bool LLParser::ParseOptionalVisibility(unsigned &Res) {
930  switch (Lex.getKind()) {
931  default:                  Res = GlobalValue::DefaultVisibility; return false;
932  case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
933  case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
934  case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
935  }
936  Lex.Lex();
937  return false;
938}
939
940/// ParseOptionalCallingConv
941///   ::= /*empty*/
942///   ::= 'ccc'
943///   ::= 'fastcc'
944///   ::= 'coldcc'
945///   ::= 'x86_stdcallcc'
946///   ::= 'x86_fastcallcc'
947///   ::= 'arm_apcscc'
948///   ::= 'arm_aapcscc'
949///   ::= 'arm_aapcs_vfpcc'
950///   ::= 'cc' UINT
951///
952bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
953  switch (Lex.getKind()) {
954  default:                       CC = CallingConv::C; return false;
955  case lltok::kw_ccc:            CC = CallingConv::C; break;
956  case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
957  case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
958  case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
959  case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
960  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
961  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
962  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
963  case lltok::kw_cc:             Lex.Lex(); return ParseUInt32(CC);
964  }
965  Lex.Lex();
966  return false;
967}
968
969/// ParseOptionalAlignment
970///   ::= /* empty */
971///   ::= 'align' 4
972bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
973  Alignment = 0;
974  if (!EatIfPresent(lltok::kw_align))
975    return false;
976  LocTy AlignLoc = Lex.getLoc();
977  if (ParseUInt32(Alignment)) return true;
978  if (!isPowerOf2_32(Alignment))
979    return Error(AlignLoc, "alignment is not a power of two");
980  return false;
981}
982
983/// ParseOptionalCommaAlignment
984///   ::= /* empty */
985///   ::= ',' 'align' 4
986bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
987  Alignment = 0;
988  if (!EatIfPresent(lltok::comma))
989    return false;
990  return ParseToken(lltok::kw_align, "expected 'align'") ||
991         ParseUInt32(Alignment);
992}
993
994/// ParseIndexList
995///    ::=  (',' uint32)+
996bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
997  if (Lex.getKind() != lltok::comma)
998    return TokError("expected ',' as start of index list");
999
1000  while (EatIfPresent(lltok::comma)) {
1001    unsigned Idx;
1002    if (ParseUInt32(Idx)) return true;
1003    Indices.push_back(Idx);
1004  }
1005
1006  return false;
1007}
1008
1009//===----------------------------------------------------------------------===//
1010// Type Parsing.
1011//===----------------------------------------------------------------------===//
1012
1013/// ParseType - Parse and resolve a full type.
1014bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1015  LocTy TypeLoc = Lex.getLoc();
1016  if (ParseTypeRec(Result)) return true;
1017
1018  // Verify no unresolved uprefs.
1019  if (!UpRefs.empty())
1020    return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1021
1022  if (!AllowVoid && Result.get() == Type::VoidTy)
1023    return Error(TypeLoc, "void type only allowed for function results");
1024
1025  return false;
1026}
1027
1028/// HandleUpRefs - Every time we finish a new layer of types, this function is
1029/// called.  It loops through the UpRefs vector, which is a list of the
1030/// currently active types.  For each type, if the up-reference is contained in
1031/// the newly completed type, we decrement the level count.  When the level
1032/// count reaches zero, the up-referenced type is the type that is passed in:
1033/// thus we can complete the cycle.
1034///
1035PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1036  // If Ty isn't abstract, or if there are no up-references in it, then there is
1037  // nothing to resolve here.
1038  if (!ty->isAbstract() || UpRefs.empty()) return ty;
1039
1040  PATypeHolder Ty(ty);
1041#if 0
1042  errs() << "Type '" << Ty->getDescription()
1043         << "' newly formed.  Resolving upreferences.\n"
1044         << UpRefs.size() << " upreferences active!\n";
1045#endif
1046
1047  // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1048  // to zero), we resolve them all together before we resolve them to Ty.  At
1049  // the end of the loop, if there is anything to resolve to Ty, it will be in
1050  // this variable.
1051  OpaqueType *TypeToResolve = 0;
1052
1053  for (unsigned i = 0; i != UpRefs.size(); ++i) {
1054    // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1055    bool ContainsType =
1056      std::find(Ty->subtype_begin(), Ty->subtype_end(),
1057                UpRefs[i].LastContainedTy) != Ty->subtype_end();
1058
1059#if 0
1060    errs() << "  UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1061           << UpRefs[i].LastContainedTy->getDescription() << ") = "
1062           << (ContainsType ? "true" : "false")
1063           << " level=" << UpRefs[i].NestingLevel << "\n";
1064#endif
1065    if (!ContainsType)
1066      continue;
1067
1068    // Decrement level of upreference
1069    unsigned Level = --UpRefs[i].NestingLevel;
1070    UpRefs[i].LastContainedTy = Ty;
1071
1072    // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1073    if (Level != 0)
1074      continue;
1075
1076#if 0
1077    errs() << "  * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1078#endif
1079    if (!TypeToResolve)
1080      TypeToResolve = UpRefs[i].UpRefTy;
1081    else
1082      UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1083    UpRefs.erase(UpRefs.begin()+i);     // Remove from upreference list.
1084    --i;                                // Do not skip the next element.
1085  }
1086
1087  if (TypeToResolve)
1088    TypeToResolve->refineAbstractTypeTo(Ty);
1089
1090  return Ty;
1091}
1092
1093
1094/// ParseTypeRec - The recursive function used to process the internal
1095/// implementation details of types.
1096bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1097  switch (Lex.getKind()) {
1098  default:
1099    return TokError("expected type");
1100  case lltok::Type:
1101    // TypeRec ::= 'float' | 'void' (etc)
1102    Result = Lex.getTyVal();
1103    Lex.Lex();
1104    break;
1105  case lltok::kw_opaque:
1106    // TypeRec ::= 'opaque'
1107    Result = Context.getOpaqueType();
1108    Lex.Lex();
1109    break;
1110  case lltok::lbrace:
1111    // TypeRec ::= '{' ... '}'
1112    if (ParseStructType(Result, false))
1113      return true;
1114    break;
1115  case lltok::lsquare:
1116    // TypeRec ::= '[' ... ']'
1117    Lex.Lex(); // eat the lsquare.
1118    if (ParseArrayVectorType(Result, false))
1119      return true;
1120    break;
1121  case lltok::less: // Either vector or packed struct.
1122    // TypeRec ::= '<' ... '>'
1123    Lex.Lex();
1124    if (Lex.getKind() == lltok::lbrace) {
1125      if (ParseStructType(Result, true) ||
1126          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1127        return true;
1128    } else if (ParseArrayVectorType(Result, true))
1129      return true;
1130    break;
1131  case lltok::LocalVar:
1132  case lltok::StringConstant:  // FIXME: REMOVE IN LLVM 3.0
1133    // TypeRec ::= %foo
1134    if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1135      Result = T;
1136    } else {
1137      Result = Context.getOpaqueType();
1138      ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1139                                            std::make_pair(Result,
1140                                                           Lex.getLoc())));
1141      M->addTypeName(Lex.getStrVal(), Result.get());
1142    }
1143    Lex.Lex();
1144    break;
1145
1146  case lltok::LocalVarID:
1147    // TypeRec ::= %4
1148    if (Lex.getUIntVal() < NumberedTypes.size())
1149      Result = NumberedTypes[Lex.getUIntVal()];
1150    else {
1151      std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1152        I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1153      if (I != ForwardRefTypeIDs.end())
1154        Result = I->second.first;
1155      else {
1156        Result = Context.getOpaqueType();
1157        ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1158                                                std::make_pair(Result,
1159                                                               Lex.getLoc())));
1160      }
1161    }
1162    Lex.Lex();
1163    break;
1164  case lltok::backslash: {
1165    // TypeRec ::= '\' 4
1166    Lex.Lex();
1167    unsigned Val;
1168    if (ParseUInt32(Val)) return true;
1169    OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1170    UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1171    Result = OT;
1172    break;
1173  }
1174  }
1175
1176  // Parse the type suffixes.
1177  while (1) {
1178    switch (Lex.getKind()) {
1179    // End of type.
1180    default: return false;
1181
1182    // TypeRec ::= TypeRec '*'
1183    case lltok::star:
1184      if (Result.get() == Type::LabelTy)
1185        return TokError("basic block pointers are invalid");
1186      if (Result.get() == Type::VoidTy)
1187        return TokError("pointers to void are invalid; use i8* instead");
1188      if (!PointerType::isValidElementType(Result.get()))
1189        return TokError("pointer to this type is invalid");
1190      Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1191      Lex.Lex();
1192      break;
1193
1194    // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1195    case lltok::kw_addrspace: {
1196      if (Result.get() == Type::LabelTy)
1197        return TokError("basic block pointers are invalid");
1198      if (Result.get() == Type::VoidTy)
1199        return TokError("pointers to void are invalid; use i8* instead");
1200      if (!PointerType::isValidElementType(Result.get()))
1201        return TokError("pointer to this type is invalid");
1202      unsigned AddrSpace;
1203      if (ParseOptionalAddrSpace(AddrSpace) ||
1204          ParseToken(lltok::star, "expected '*' in address space"))
1205        return true;
1206
1207      Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1208      break;
1209    }
1210
1211    /// Types '(' ArgTypeListI ')' OptFuncAttrs
1212    case lltok::lparen:
1213      if (ParseFunctionType(Result))
1214        return true;
1215      break;
1216    }
1217  }
1218}
1219
1220/// ParseParameterList
1221///    ::= '(' ')'
1222///    ::= '(' Arg (',' Arg)* ')'
1223///  Arg
1224///    ::= Type OptionalAttributes Value OptionalAttributes
1225bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1226                                  PerFunctionState &PFS) {
1227  if (ParseToken(lltok::lparen, "expected '(' in call"))
1228    return true;
1229
1230  while (Lex.getKind() != lltok::rparen) {
1231    // If this isn't the first argument, we need a comma.
1232    if (!ArgList.empty() &&
1233        ParseToken(lltok::comma, "expected ',' in argument list"))
1234      return true;
1235
1236    // Parse the argument.
1237    LocTy ArgLoc;
1238    PATypeHolder ArgTy(Type::VoidTy);
1239    unsigned ArgAttrs1, ArgAttrs2;
1240    Value *V;
1241    if (ParseType(ArgTy, ArgLoc) ||
1242        ParseOptionalAttrs(ArgAttrs1, 0) ||
1243        ParseValue(ArgTy, V, PFS) ||
1244        // FIXME: Should not allow attributes after the argument, remove this in
1245        // LLVM 3.0.
1246        ParseOptionalAttrs(ArgAttrs2, 3))
1247      return true;
1248    ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1249  }
1250
1251  Lex.Lex();  // Lex the ')'.
1252  return false;
1253}
1254
1255
1256
1257/// ParseArgumentList - Parse the argument list for a function type or function
1258/// prototype.  If 'inType' is true then we are parsing a FunctionType.
1259///   ::= '(' ArgTypeListI ')'
1260/// ArgTypeListI
1261///   ::= /*empty*/
1262///   ::= '...'
1263///   ::= ArgTypeList ',' '...'
1264///   ::= ArgType (',' ArgType)*
1265///
1266bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1267                                 bool &isVarArg, bool inType) {
1268  isVarArg = false;
1269  assert(Lex.getKind() == lltok::lparen);
1270  Lex.Lex(); // eat the (.
1271
1272  if (Lex.getKind() == lltok::rparen) {
1273    // empty
1274  } else if (Lex.getKind() == lltok::dotdotdot) {
1275    isVarArg = true;
1276    Lex.Lex();
1277  } else {
1278    LocTy TypeLoc = Lex.getLoc();
1279    PATypeHolder ArgTy(Type::VoidTy);
1280    unsigned Attrs;
1281    std::string Name;
1282
1283    // If we're parsing a type, use ParseTypeRec, because we allow recursive
1284    // types (such as a function returning a pointer to itself).  If parsing a
1285    // function prototype, we require fully resolved types.
1286    if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1287        ParseOptionalAttrs(Attrs, 0)) return true;
1288
1289    if (ArgTy == Type::VoidTy)
1290      return Error(TypeLoc, "argument can not have void type");
1291
1292    if (Lex.getKind() == lltok::LocalVar ||
1293        Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1294      Name = Lex.getStrVal();
1295      Lex.Lex();
1296    }
1297
1298    if (!FunctionType::isValidArgumentType(ArgTy))
1299      return Error(TypeLoc, "invalid type for function argument");
1300
1301    ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1302
1303    while (EatIfPresent(lltok::comma)) {
1304      // Handle ... at end of arg list.
1305      if (EatIfPresent(lltok::dotdotdot)) {
1306        isVarArg = true;
1307        break;
1308      }
1309
1310      // Otherwise must be an argument type.
1311      TypeLoc = Lex.getLoc();
1312      if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1313          ParseOptionalAttrs(Attrs, 0)) return true;
1314
1315      if (ArgTy == Type::VoidTy)
1316        return Error(TypeLoc, "argument can not have void type");
1317
1318      if (Lex.getKind() == lltok::LocalVar ||
1319          Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1320        Name = Lex.getStrVal();
1321        Lex.Lex();
1322      } else {
1323        Name = "";
1324      }
1325
1326      if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1327        return Error(TypeLoc, "invalid type for function argument");
1328
1329      ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1330    }
1331  }
1332
1333  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1334}
1335
1336/// ParseFunctionType
1337///  ::= Type ArgumentList OptionalAttrs
1338bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1339  assert(Lex.getKind() == lltok::lparen);
1340
1341  if (!FunctionType::isValidReturnType(Result))
1342    return TokError("invalid function return type");
1343
1344  std::vector<ArgInfo> ArgList;
1345  bool isVarArg;
1346  unsigned Attrs;
1347  if (ParseArgumentList(ArgList, isVarArg, true) ||
1348      // FIXME: Allow, but ignore attributes on function types!
1349      // FIXME: Remove in LLVM 3.0
1350      ParseOptionalAttrs(Attrs, 2))
1351    return true;
1352
1353  // Reject names on the arguments lists.
1354  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1355    if (!ArgList[i].Name.empty())
1356      return Error(ArgList[i].Loc, "argument name invalid in function type");
1357    if (!ArgList[i].Attrs != 0) {
1358      // Allow but ignore attributes on function types; this permits
1359      // auto-upgrade.
1360      // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1361    }
1362  }
1363
1364  std::vector<const Type*> ArgListTy;
1365  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1366    ArgListTy.push_back(ArgList[i].Type);
1367
1368  Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1369                                                ArgListTy, isVarArg));
1370  return false;
1371}
1372
1373/// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1374///   TypeRec
1375///     ::= '{' '}'
1376///     ::= '{' TypeRec (',' TypeRec)* '}'
1377///     ::= '<' '{' '}' '>'
1378///     ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1379bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1380  assert(Lex.getKind() == lltok::lbrace);
1381  Lex.Lex(); // Consume the '{'
1382
1383  if (EatIfPresent(lltok::rbrace)) {
1384    Result = Context.getStructType(Packed);
1385    return false;
1386  }
1387
1388  std::vector<PATypeHolder> ParamsList;
1389  LocTy EltTyLoc = Lex.getLoc();
1390  if (ParseTypeRec(Result)) return true;
1391  ParamsList.push_back(Result);
1392
1393  if (Result == Type::VoidTy)
1394    return Error(EltTyLoc, "struct element can not have void type");
1395  if (!StructType::isValidElementType(Result))
1396    return Error(EltTyLoc, "invalid element type for struct");
1397
1398  while (EatIfPresent(lltok::comma)) {
1399    EltTyLoc = Lex.getLoc();
1400    if (ParseTypeRec(Result)) return true;
1401
1402    if (Result == Type::VoidTy)
1403      return Error(EltTyLoc, "struct element can not have void type");
1404    if (!StructType::isValidElementType(Result))
1405      return Error(EltTyLoc, "invalid element type for struct");
1406
1407    ParamsList.push_back(Result);
1408  }
1409
1410  if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1411    return true;
1412
1413  std::vector<const Type*> ParamsListTy;
1414  for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1415    ParamsListTy.push_back(ParamsList[i].get());
1416  Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1417  return false;
1418}
1419
1420/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1421/// token has already been consumed.
1422///   TypeRec
1423///     ::= '[' APSINTVAL 'x' Types ']'
1424///     ::= '<' APSINTVAL 'x' Types '>'
1425bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1426  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1427      Lex.getAPSIntVal().getBitWidth() > 64)
1428    return TokError("expected number in address space");
1429
1430  LocTy SizeLoc = Lex.getLoc();
1431  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1432  Lex.Lex();
1433
1434  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1435      return true;
1436
1437  LocTy TypeLoc = Lex.getLoc();
1438  PATypeHolder EltTy(Type::VoidTy);
1439  if (ParseTypeRec(EltTy)) return true;
1440
1441  if (EltTy == Type::VoidTy)
1442    return Error(TypeLoc, "array and vector element type cannot be void");
1443
1444  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1445                 "expected end of sequential type"))
1446    return true;
1447
1448  if (isVector) {
1449    if (Size == 0)
1450      return Error(SizeLoc, "zero element vector is illegal");
1451    if ((unsigned)Size != Size)
1452      return Error(SizeLoc, "size too large for vector");
1453    if (!VectorType::isValidElementType(EltTy))
1454      return Error(TypeLoc, "vector element type must be fp or integer");
1455    Result = Context.getVectorType(EltTy, unsigned(Size));
1456  } else {
1457    if (!ArrayType::isValidElementType(EltTy))
1458      return Error(TypeLoc, "invalid array element type");
1459    Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1460  }
1461  return false;
1462}
1463
1464//===----------------------------------------------------------------------===//
1465// Function Semantic Analysis.
1466//===----------------------------------------------------------------------===//
1467
1468LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1469  : P(p), F(f) {
1470
1471  // Insert unnamed arguments into the NumberedVals list.
1472  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1473       AI != E; ++AI)
1474    if (!AI->hasName())
1475      NumberedVals.push_back(AI);
1476}
1477
1478LLParser::PerFunctionState::~PerFunctionState() {
1479  // If there were any forward referenced non-basicblock values, delete them.
1480  for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1481       I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1482    if (!isa<BasicBlock>(I->second.first)) {
1483      I->second.first->replaceAllUsesWith(
1484                           P.getContext().getUndef(I->second.first->getType()));
1485      delete I->second.first;
1486      I->second.first = 0;
1487    }
1488
1489  for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1490       I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1491    if (!isa<BasicBlock>(I->second.first)) {
1492      I->second.first->replaceAllUsesWith(
1493                           P.getContext().getUndef(I->second.first->getType()));
1494      delete I->second.first;
1495      I->second.first = 0;
1496    }
1497}
1498
1499bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1500  if (!ForwardRefVals.empty())
1501    return P.Error(ForwardRefVals.begin()->second.second,
1502                   "use of undefined value '%" + ForwardRefVals.begin()->first +
1503                   "'");
1504  if (!ForwardRefValIDs.empty())
1505    return P.Error(ForwardRefValIDs.begin()->second.second,
1506                   "use of undefined value '%" +
1507                   utostr(ForwardRefValIDs.begin()->first) + "'");
1508  return false;
1509}
1510
1511
1512/// GetVal - Get a value with the specified name or ID, creating a
1513/// forward reference record if needed.  This can return null if the value
1514/// exists but does not have the right type.
1515Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1516                                          const Type *Ty, LocTy Loc) {
1517  // Look this name up in the normal function symbol table.
1518  Value *Val = F.getValueSymbolTable().lookup(Name);
1519
1520  // If this is a forward reference for the value, see if we already created a
1521  // forward ref record.
1522  if (Val == 0) {
1523    std::map<std::string, std::pair<Value*, LocTy> >::iterator
1524      I = ForwardRefVals.find(Name);
1525    if (I != ForwardRefVals.end())
1526      Val = I->second.first;
1527  }
1528
1529  // If we have the value in the symbol table or fwd-ref table, return it.
1530  if (Val) {
1531    if (Val->getType() == Ty) return Val;
1532    if (Ty == Type::LabelTy)
1533      P.Error(Loc, "'%" + Name + "' is not a basic block");
1534    else
1535      P.Error(Loc, "'%" + Name + "' defined with type '" +
1536              Val->getType()->getDescription() + "'");
1537    return 0;
1538  }
1539
1540  // Don't make placeholders with invalid type.
1541  if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1542    P.Error(Loc, "invalid use of a non-first-class type");
1543    return 0;
1544  }
1545
1546  // Otherwise, create a new forward reference for this value and remember it.
1547  Value *FwdVal;
1548  if (Ty == Type::LabelTy)
1549    FwdVal = BasicBlock::Create(Name, &F);
1550  else
1551    FwdVal = new Argument(Ty, Name);
1552
1553  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1554  return FwdVal;
1555}
1556
1557Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1558                                          LocTy Loc) {
1559  // Look this name up in the normal function symbol table.
1560  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1561
1562  // If this is a forward reference for the value, see if we already created a
1563  // forward ref record.
1564  if (Val == 0) {
1565    std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1566      I = ForwardRefValIDs.find(ID);
1567    if (I != ForwardRefValIDs.end())
1568      Val = I->second.first;
1569  }
1570
1571  // If we have the value in the symbol table or fwd-ref table, return it.
1572  if (Val) {
1573    if (Val->getType() == Ty) return Val;
1574    if (Ty == Type::LabelTy)
1575      P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1576    else
1577      P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1578              Val->getType()->getDescription() + "'");
1579    return 0;
1580  }
1581
1582  if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1583    P.Error(Loc, "invalid use of a non-first-class type");
1584    return 0;
1585  }
1586
1587  // Otherwise, create a new forward reference for this value and remember it.
1588  Value *FwdVal;
1589  if (Ty == Type::LabelTy)
1590    FwdVal = BasicBlock::Create("", &F);
1591  else
1592    FwdVal = new Argument(Ty);
1593
1594  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1595  return FwdVal;
1596}
1597
1598/// SetInstName - After an instruction is parsed and inserted into its
1599/// basic block, this installs its name.
1600bool LLParser::PerFunctionState::SetInstName(int NameID,
1601                                             const std::string &NameStr,
1602                                             LocTy NameLoc, Instruction *Inst) {
1603  // If this instruction has void type, it cannot have a name or ID specified.
1604  if (Inst->getType() == Type::VoidTy) {
1605    if (NameID != -1 || !NameStr.empty())
1606      return P.Error(NameLoc, "instructions returning void cannot have a name");
1607    return false;
1608  }
1609
1610  // If this was a numbered instruction, verify that the instruction is the
1611  // expected value and resolve any forward references.
1612  if (NameStr.empty()) {
1613    // If neither a name nor an ID was specified, just use the next ID.
1614    if (NameID == -1)
1615      NameID = NumberedVals.size();
1616
1617    if (unsigned(NameID) != NumberedVals.size())
1618      return P.Error(NameLoc, "instruction expected to be numbered '%" +
1619                     utostr(NumberedVals.size()) + "'");
1620
1621    std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1622      ForwardRefValIDs.find(NameID);
1623    if (FI != ForwardRefValIDs.end()) {
1624      if (FI->second.first->getType() != Inst->getType())
1625        return P.Error(NameLoc, "instruction forward referenced with type '" +
1626                       FI->second.first->getType()->getDescription() + "'");
1627      FI->second.first->replaceAllUsesWith(Inst);
1628      ForwardRefValIDs.erase(FI);
1629    }
1630
1631    NumberedVals.push_back(Inst);
1632    return false;
1633  }
1634
1635  // Otherwise, the instruction had a name.  Resolve forward refs and set it.
1636  std::map<std::string, std::pair<Value*, LocTy> >::iterator
1637    FI = ForwardRefVals.find(NameStr);
1638  if (FI != ForwardRefVals.end()) {
1639    if (FI->second.first->getType() != Inst->getType())
1640      return P.Error(NameLoc, "instruction forward referenced with type '" +
1641                     FI->second.first->getType()->getDescription() + "'");
1642    FI->second.first->replaceAllUsesWith(Inst);
1643    ForwardRefVals.erase(FI);
1644  }
1645
1646  // Set the name on the instruction.
1647  Inst->setName(NameStr);
1648
1649  if (Inst->getNameStr() != NameStr)
1650    return P.Error(NameLoc, "multiple definition of local value named '" +
1651                   NameStr + "'");
1652  return false;
1653}
1654
1655/// GetBB - Get a basic block with the specified name or ID, creating a
1656/// forward reference record if needed.
1657BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1658                                              LocTy Loc) {
1659  return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1660}
1661
1662BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1663  return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1664}
1665
1666/// DefineBB - Define the specified basic block, which is either named or
1667/// unnamed.  If there is an error, this returns null otherwise it returns
1668/// the block being defined.
1669BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1670                                                 LocTy Loc) {
1671  BasicBlock *BB;
1672  if (Name.empty())
1673    BB = GetBB(NumberedVals.size(), Loc);
1674  else
1675    BB = GetBB(Name, Loc);
1676  if (BB == 0) return 0; // Already diagnosed error.
1677
1678  // Move the block to the end of the function.  Forward ref'd blocks are
1679  // inserted wherever they happen to be referenced.
1680  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1681
1682  // Remove the block from forward ref sets.
1683  if (Name.empty()) {
1684    ForwardRefValIDs.erase(NumberedVals.size());
1685    NumberedVals.push_back(BB);
1686  } else {
1687    // BB forward references are already in the function symbol table.
1688    ForwardRefVals.erase(Name);
1689  }
1690
1691  return BB;
1692}
1693
1694//===----------------------------------------------------------------------===//
1695// Constants.
1696//===----------------------------------------------------------------------===//
1697
1698/// ParseValID - Parse an abstract value that doesn't necessarily have a
1699/// type implied.  For example, if we parse "4" we don't know what integer type
1700/// it has.  The value will later be combined with its type and checked for
1701/// sanity.
1702bool LLParser::ParseValID(ValID &ID) {
1703  ID.Loc = Lex.getLoc();
1704  switch (Lex.getKind()) {
1705  default: return TokError("expected value token");
1706  case lltok::GlobalID:  // @42
1707    ID.UIntVal = Lex.getUIntVal();
1708    ID.Kind = ValID::t_GlobalID;
1709    break;
1710  case lltok::GlobalVar:  // @foo
1711    ID.StrVal = Lex.getStrVal();
1712    ID.Kind = ValID::t_GlobalName;
1713    break;
1714  case lltok::LocalVarID:  // %42
1715    ID.UIntVal = Lex.getUIntVal();
1716    ID.Kind = ValID::t_LocalID;
1717    break;
1718  case lltok::LocalVar:  // %foo
1719  case lltok::StringConstant:  // "foo" - FIXME: REMOVE IN LLVM 3.0
1720    ID.StrVal = Lex.getStrVal();
1721    ID.Kind = ValID::t_LocalName;
1722    break;
1723  case lltok::Metadata: {  // !{...} MDNode, !"foo" MDString
1724    ID.Kind = ValID::t_Metadata;
1725    Lex.Lex();
1726    if (Lex.getKind() == lltok::lbrace) {
1727      SmallVector<Value*, 16> Elts;
1728      if (ParseMDNodeVector(Elts) ||
1729          ParseToken(lltok::rbrace, "expected end of metadata node"))
1730        return true;
1731
1732      ID.MetadataVal = Context.getMDNode(Elts.data(), Elts.size());
1733      return false;
1734    }
1735
1736    // Standalone metadata reference
1737    // !{ ..., !42, ... }
1738    if (!ParseMDNode(ID.MetadataVal))
1739      return false;
1740
1741    // MDString:
1742    //   ::= '!' STRINGCONSTANT
1743    if (ParseMDString(ID.MetadataVal)) return true;
1744    ID.Kind = ValID::t_Metadata;
1745    return false;
1746  }
1747  case lltok::APSInt:
1748    ID.APSIntVal = Lex.getAPSIntVal();
1749    ID.Kind = ValID::t_APSInt;
1750    break;
1751  case lltok::APFloat:
1752    ID.APFloatVal = Lex.getAPFloatVal();
1753    ID.Kind = ValID::t_APFloat;
1754    break;
1755  case lltok::kw_true:
1756    ID.ConstantVal = Context.getTrue();
1757    ID.Kind = ValID::t_Constant;
1758    break;
1759  case lltok::kw_false:
1760    ID.ConstantVal = Context.getFalse();
1761    ID.Kind = ValID::t_Constant;
1762    break;
1763  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1764  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1765  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1766
1767  case lltok::lbrace: {
1768    // ValID ::= '{' ConstVector '}'
1769    Lex.Lex();
1770    SmallVector<Constant*, 16> Elts;
1771    if (ParseGlobalValueVector(Elts) ||
1772        ParseToken(lltok::rbrace, "expected end of struct constant"))
1773      return true;
1774
1775    ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
1776    ID.Kind = ValID::t_Constant;
1777    return false;
1778  }
1779  case lltok::less: {
1780    // ValID ::= '<' ConstVector '>'         --> Vector.
1781    // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1782    Lex.Lex();
1783    bool isPackedStruct = EatIfPresent(lltok::lbrace);
1784
1785    SmallVector<Constant*, 16> Elts;
1786    LocTy FirstEltLoc = Lex.getLoc();
1787    if (ParseGlobalValueVector(Elts) ||
1788        (isPackedStruct &&
1789         ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1790        ParseToken(lltok::greater, "expected end of constant"))
1791      return true;
1792
1793    if (isPackedStruct) {
1794      ID.ConstantVal =
1795        ConstantStruct::get(Elts.data(), Elts.size(), true);
1796      ID.Kind = ValID::t_Constant;
1797      return false;
1798    }
1799
1800    if (Elts.empty())
1801      return Error(ID.Loc, "constant vector must not be empty");
1802
1803    if (!Elts[0]->getType()->isInteger() &&
1804        !Elts[0]->getType()->isFloatingPoint())
1805      return Error(FirstEltLoc,
1806                   "vector elements must have integer or floating point type");
1807
1808    // Verify that all the vector elements have the same type.
1809    for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1810      if (Elts[i]->getType() != Elts[0]->getType())
1811        return Error(FirstEltLoc,
1812                     "vector element #" + utostr(i) +
1813                    " is not of type '" + Elts[0]->getType()->getDescription());
1814
1815    ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1816    ID.Kind = ValID::t_Constant;
1817    return false;
1818  }
1819  case lltok::lsquare: {   // Array Constant
1820    Lex.Lex();
1821    SmallVector<Constant*, 16> Elts;
1822    LocTy FirstEltLoc = Lex.getLoc();
1823    if (ParseGlobalValueVector(Elts) ||
1824        ParseToken(lltok::rsquare, "expected end of array constant"))
1825      return true;
1826
1827    // Handle empty element.
1828    if (Elts.empty()) {
1829      // Use undef instead of an array because it's inconvenient to determine
1830      // the element type at this point, there being no elements to examine.
1831      ID.Kind = ValID::t_EmptyArray;
1832      return false;
1833    }
1834
1835    if (!Elts[0]->getType()->isFirstClassType())
1836      return Error(FirstEltLoc, "invalid array element type: " +
1837                   Elts[0]->getType()->getDescription());
1838
1839    ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1840
1841    // Verify all elements are correct type!
1842    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1843      if (Elts[i]->getType() != Elts[0]->getType())
1844        return Error(FirstEltLoc,
1845                     "array element #" + utostr(i) +
1846                     " is not of type '" +Elts[0]->getType()->getDescription());
1847    }
1848
1849    ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1850    ID.Kind = ValID::t_Constant;
1851    return false;
1852  }
1853  case lltok::kw_c:  // c "foo"
1854    Lex.Lex();
1855    ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1856    if (ParseToken(lltok::StringConstant, "expected string")) return true;
1857    ID.Kind = ValID::t_Constant;
1858    return false;
1859
1860  case lltok::kw_asm: {
1861    // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1862    bool HasSideEffect;
1863    Lex.Lex();
1864    if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1865        ParseStringConstant(ID.StrVal) ||
1866        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1867        ParseToken(lltok::StringConstant, "expected constraint string"))
1868      return true;
1869    ID.StrVal2 = Lex.getStrVal();
1870    ID.UIntVal = HasSideEffect;
1871    ID.Kind = ValID::t_InlineAsm;
1872    return false;
1873  }
1874
1875  case lltok::kw_trunc:
1876  case lltok::kw_zext:
1877  case lltok::kw_sext:
1878  case lltok::kw_fptrunc:
1879  case lltok::kw_fpext:
1880  case lltok::kw_bitcast:
1881  case lltok::kw_uitofp:
1882  case lltok::kw_sitofp:
1883  case lltok::kw_fptoui:
1884  case lltok::kw_fptosi:
1885  case lltok::kw_inttoptr:
1886  case lltok::kw_ptrtoint: {
1887    unsigned Opc = Lex.getUIntVal();
1888    PATypeHolder DestTy(Type::VoidTy);
1889    Constant *SrcVal;
1890    Lex.Lex();
1891    if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1892        ParseGlobalTypeAndValue(SrcVal) ||
1893        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1894        ParseType(DestTy) ||
1895        ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1896      return true;
1897    if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1898      return Error(ID.Loc, "invalid cast opcode for cast from '" +
1899                   SrcVal->getType()->getDescription() + "' to '" +
1900                   DestTy->getDescription() + "'");
1901    ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
1902                                                 SrcVal, DestTy);
1903    ID.Kind = ValID::t_Constant;
1904    return false;
1905  }
1906  case lltok::kw_extractvalue: {
1907    Lex.Lex();
1908    Constant *Val;
1909    SmallVector<unsigned, 4> Indices;
1910    if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1911        ParseGlobalTypeAndValue(Val) ||
1912        ParseIndexList(Indices) ||
1913        ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1914      return true;
1915    if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1916      return Error(ID.Loc, "extractvalue operand must be array or struct");
1917    if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1918                                          Indices.end()))
1919      return Error(ID.Loc, "invalid indices for extractvalue");
1920    ID.ConstantVal =
1921      ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1922    ID.Kind = ValID::t_Constant;
1923    return false;
1924  }
1925  case lltok::kw_insertvalue: {
1926    Lex.Lex();
1927    Constant *Val0, *Val1;
1928    SmallVector<unsigned, 4> Indices;
1929    if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1930        ParseGlobalTypeAndValue(Val0) ||
1931        ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1932        ParseGlobalTypeAndValue(Val1) ||
1933        ParseIndexList(Indices) ||
1934        ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1935      return true;
1936    if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1937      return Error(ID.Loc, "extractvalue operand must be array or struct");
1938    if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1939                                          Indices.end()))
1940      return Error(ID.Loc, "invalid indices for insertvalue");
1941    ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1942                       Indices.data(), Indices.size());
1943    ID.Kind = ValID::t_Constant;
1944    return false;
1945  }
1946  case lltok::kw_icmp:
1947  case lltok::kw_fcmp: {
1948    unsigned PredVal, Opc = Lex.getUIntVal();
1949    Constant *Val0, *Val1;
1950    Lex.Lex();
1951    if (ParseCmpPredicate(PredVal, Opc) ||
1952        ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1953        ParseGlobalTypeAndValue(Val0) ||
1954        ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1955        ParseGlobalTypeAndValue(Val1) ||
1956        ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1957      return true;
1958
1959    if (Val0->getType() != Val1->getType())
1960      return Error(ID.Loc, "compare operands must have the same type");
1961
1962    CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1963
1964    if (Opc == Instruction::FCmp) {
1965      if (!Val0->getType()->isFPOrFPVector())
1966        return Error(ID.Loc, "fcmp requires floating point operands");
1967      ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1968    } else {
1969      assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1970      if (!Val0->getType()->isIntOrIntVector() &&
1971          !isa<PointerType>(Val0->getType()))
1972        return Error(ID.Loc, "icmp requires pointer or integer operands");
1973      ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1974    }
1975    ID.Kind = ValID::t_Constant;
1976    return false;
1977  }
1978
1979  // Binary Operators.
1980  case lltok::kw_add:
1981  case lltok::kw_fadd:
1982  case lltok::kw_sub:
1983  case lltok::kw_fsub:
1984  case lltok::kw_mul:
1985  case lltok::kw_fmul:
1986  case lltok::kw_udiv:
1987  case lltok::kw_sdiv:
1988  case lltok::kw_fdiv:
1989  case lltok::kw_urem:
1990  case lltok::kw_srem:
1991  case lltok::kw_frem: {
1992    bool NUW = false;
1993    bool NSW = false;
1994    bool Exact = false;
1995    unsigned Opc = Lex.getUIntVal();
1996    Constant *Val0, *Val1;
1997    Lex.Lex();
1998    LocTy ModifierLoc = Lex.getLoc();
1999    if (Opc == Instruction::Add ||
2000        Opc == Instruction::Sub ||
2001        Opc == Instruction::Mul) {
2002      if (EatIfPresent(lltok::kw_nuw))
2003        NUW = true;
2004      if (EatIfPresent(lltok::kw_nsw)) {
2005        NSW = true;
2006        if (EatIfPresent(lltok::kw_nuw))
2007          NUW = true;
2008      }
2009    } else if (Opc == Instruction::SDiv) {
2010      if (EatIfPresent(lltok::kw_exact))
2011        Exact = true;
2012    }
2013    if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2014        ParseGlobalTypeAndValue(Val0) ||
2015        ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2016        ParseGlobalTypeAndValue(Val1) ||
2017        ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2018      return true;
2019    if (Val0->getType() != Val1->getType())
2020      return Error(ID.Loc, "operands of constexpr must have same type");
2021    if (!Val0->getType()->isIntOrIntVector()) {
2022      if (NUW)
2023        return Error(ModifierLoc, "nuw only applies to integer operations");
2024      if (NSW)
2025        return Error(ModifierLoc, "nsw only applies to integer operations");
2026    }
2027    // API compatibility: Accept either integer or floating-point types with
2028    // add, sub, and mul.
2029    if (!Val0->getType()->isIntOrIntVector() &&
2030        !Val0->getType()->isFPOrFPVector())
2031      return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2032    Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2033    if (NUW)
2034      cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2035    if (NSW)
2036      cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2037    if (Exact)
2038      cast<SDivOperator>(C)->setIsExact(true);
2039    ID.ConstantVal = C;
2040    ID.Kind = ValID::t_Constant;
2041    return false;
2042  }
2043
2044  // Logical Operations
2045  case lltok::kw_shl:
2046  case lltok::kw_lshr:
2047  case lltok::kw_ashr:
2048  case lltok::kw_and:
2049  case lltok::kw_or:
2050  case lltok::kw_xor: {
2051    unsigned Opc = Lex.getUIntVal();
2052    Constant *Val0, *Val1;
2053    Lex.Lex();
2054    if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2055        ParseGlobalTypeAndValue(Val0) ||
2056        ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2057        ParseGlobalTypeAndValue(Val1) ||
2058        ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2059      return true;
2060    if (Val0->getType() != Val1->getType())
2061      return Error(ID.Loc, "operands of constexpr must have same type");
2062    if (!Val0->getType()->isIntOrIntVector())
2063      return Error(ID.Loc,
2064                   "constexpr requires integer or integer vector operands");
2065    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2066    ID.Kind = ValID::t_Constant;
2067    return false;
2068  }
2069
2070  case lltok::kw_getelementptr:
2071  case lltok::kw_shufflevector:
2072  case lltok::kw_insertelement:
2073  case lltok::kw_extractelement:
2074  case lltok::kw_select: {
2075    unsigned Opc = Lex.getUIntVal();
2076    SmallVector<Constant*, 16> Elts;
2077    bool InBounds = false;
2078    Lex.Lex();
2079    if (Opc == Instruction::GetElementPtr)
2080      InBounds = EatIfPresent(lltok::kw_inbounds);
2081    if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2082        ParseGlobalValueVector(Elts) ||
2083        ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2084      return true;
2085
2086    if (Opc == Instruction::GetElementPtr) {
2087      if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2088        return Error(ID.Loc, "getelementptr requires pointer operand");
2089
2090      if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2091                                             (Value**)(Elts.data() + 1),
2092                                             Elts.size() - 1))
2093        return Error(ID.Loc, "invalid indices for getelementptr");
2094      ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2095                                              Elts.data() + 1, Elts.size() - 1);
2096      if (InBounds)
2097        cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2098    } else if (Opc == Instruction::Select) {
2099      if (Elts.size() != 3)
2100        return Error(ID.Loc, "expected three operands to select");
2101      if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2102                                                              Elts[2]))
2103        return Error(ID.Loc, Reason);
2104      ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2105    } else if (Opc == Instruction::ShuffleVector) {
2106      if (Elts.size() != 3)
2107        return Error(ID.Loc, "expected three operands to shufflevector");
2108      if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2109        return Error(ID.Loc, "invalid operands to shufflevector");
2110      ID.ConstantVal =
2111                 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2112    } else if (Opc == Instruction::ExtractElement) {
2113      if (Elts.size() != 2)
2114        return Error(ID.Loc, "expected two operands to extractelement");
2115      if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2116        return Error(ID.Loc, "invalid extractelement operands");
2117      ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2118    } else {
2119      assert(Opc == Instruction::InsertElement && "Unknown opcode");
2120      if (Elts.size() != 3)
2121      return Error(ID.Loc, "expected three operands to insertelement");
2122      if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2123        return Error(ID.Loc, "invalid insertelement operands");
2124      ID.ConstantVal =
2125                 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2126    }
2127
2128    ID.Kind = ValID::t_Constant;
2129    return false;
2130  }
2131  }
2132
2133  Lex.Lex();
2134  return false;
2135}
2136
2137/// ParseGlobalValue - Parse a global value with the specified type.
2138bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2139  V = 0;
2140  ValID ID;
2141  return ParseValID(ID) ||
2142         ConvertGlobalValIDToValue(Ty, ID, V);
2143}
2144
2145/// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2146/// constant.
2147bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2148                                         Constant *&V) {
2149  if (isa<FunctionType>(Ty))
2150    return Error(ID.Loc, "functions are not values, refer to them as pointers");
2151
2152  switch (ID.Kind) {
2153  default: llvm_unreachable("Unknown ValID!");
2154  case ValID::t_Metadata:
2155    return Error(ID.Loc, "invalid use of metadata");
2156  case ValID::t_LocalID:
2157  case ValID::t_LocalName:
2158    return Error(ID.Loc, "invalid use of function-local name");
2159  case ValID::t_InlineAsm:
2160    return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2161  case ValID::t_GlobalName:
2162    V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2163    return V == 0;
2164  case ValID::t_GlobalID:
2165    V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2166    return V == 0;
2167  case ValID::t_APSInt:
2168    if (!isa<IntegerType>(Ty))
2169      return Error(ID.Loc, "integer constant must have integer type");
2170    ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2171    V = ConstantInt::get(Context, ID.APSIntVal);
2172    return false;
2173  case ValID::t_APFloat:
2174    if (!Ty->isFloatingPoint() ||
2175        !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2176      return Error(ID.Loc, "floating point constant invalid for type");
2177
2178    // The lexer has no type info, so builds all float and double FP constants
2179    // as double.  Fix this here.  Long double does not need this.
2180    if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2181        Ty == Type::FloatTy) {
2182      bool Ignored;
2183      ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2184                            &Ignored);
2185    }
2186    V = ConstantFP::get(Context, ID.APFloatVal);
2187
2188    if (V->getType() != Ty)
2189      return Error(ID.Loc, "floating point constant does not have type '" +
2190                   Ty->getDescription() + "'");
2191
2192    return false;
2193  case ValID::t_Null:
2194    if (!isa<PointerType>(Ty))
2195      return Error(ID.Loc, "null must be a pointer type");
2196    V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2197    return false;
2198  case ValID::t_Undef:
2199    // FIXME: LabelTy should not be a first-class type.
2200    if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2201        !isa<OpaqueType>(Ty))
2202      return Error(ID.Loc, "invalid type for undef constant");
2203    V = Context.getUndef(Ty);
2204    return false;
2205  case ValID::t_EmptyArray:
2206    if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2207      return Error(ID.Loc, "invalid empty array initializer");
2208    V = Context.getUndef(Ty);
2209    return false;
2210  case ValID::t_Zero:
2211    // FIXME: LabelTy should not be a first-class type.
2212    if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2213      return Error(ID.Loc, "invalid type for null constant");
2214    V = Context.getNullValue(Ty);
2215    return false;
2216  case ValID::t_Constant:
2217    if (ID.ConstantVal->getType() != Ty)
2218      return Error(ID.Loc, "constant expression type mismatch");
2219    V = ID.ConstantVal;
2220    return false;
2221  }
2222}
2223
2224bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2225  PATypeHolder Type(Type::VoidTy);
2226  return ParseType(Type) ||
2227         ParseGlobalValue(Type, V);
2228}
2229
2230/// ParseGlobalValueVector
2231///   ::= /*empty*/
2232///   ::= TypeAndValue (',' TypeAndValue)*
2233bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2234  // Empty list.
2235  if (Lex.getKind() == lltok::rbrace ||
2236      Lex.getKind() == lltok::rsquare ||
2237      Lex.getKind() == lltok::greater ||
2238      Lex.getKind() == lltok::rparen)
2239    return false;
2240
2241  Constant *C;
2242  if (ParseGlobalTypeAndValue(C)) return true;
2243  Elts.push_back(C);
2244
2245  while (EatIfPresent(lltok::comma)) {
2246    if (ParseGlobalTypeAndValue(C)) return true;
2247    Elts.push_back(C);
2248  }
2249
2250  return false;
2251}
2252
2253
2254//===----------------------------------------------------------------------===//
2255// Function Parsing.
2256//===----------------------------------------------------------------------===//
2257
2258bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2259                                   PerFunctionState &PFS) {
2260  if (ID.Kind == ValID::t_LocalID)
2261    V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2262  else if (ID.Kind == ValID::t_LocalName)
2263    V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2264  else if (ID.Kind == ValID::t_InlineAsm) {
2265    const PointerType *PTy = dyn_cast<PointerType>(Ty);
2266    const FunctionType *FTy =
2267      PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2268    if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2269      return Error(ID.Loc, "invalid type for inline asm constraint string");
2270    V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2271    return false;
2272  } else if (ID.Kind == ValID::t_Metadata) {
2273    V = ID.MetadataVal;
2274  } else {
2275    Constant *C;
2276    if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2277    V = C;
2278    return false;
2279  }
2280
2281  return V == 0;
2282}
2283
2284bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2285  V = 0;
2286  ValID ID;
2287  return ParseValID(ID) ||
2288         ConvertValIDToValue(Ty, ID, V, PFS);
2289}
2290
2291bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2292  PATypeHolder T(Type::VoidTy);
2293  return ParseType(T) ||
2294         ParseValue(T, V, PFS);
2295}
2296
2297/// FunctionHeader
2298///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2299///       Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2300///       OptionalAlign OptGC
2301bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2302  // Parse the linkage.
2303  LocTy LinkageLoc = Lex.getLoc();
2304  unsigned Linkage;
2305
2306  unsigned Visibility, CC, RetAttrs;
2307  PATypeHolder RetType(Type::VoidTy);
2308  LocTy RetTypeLoc = Lex.getLoc();
2309  if (ParseOptionalLinkage(Linkage) ||
2310      ParseOptionalVisibility(Visibility) ||
2311      ParseOptionalCallingConv(CC) ||
2312      ParseOptionalAttrs(RetAttrs, 1) ||
2313      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2314    return true;
2315
2316  // Verify that the linkage is ok.
2317  switch ((GlobalValue::LinkageTypes)Linkage) {
2318  case GlobalValue::ExternalLinkage:
2319    break; // always ok.
2320  case GlobalValue::DLLImportLinkage:
2321  case GlobalValue::ExternalWeakLinkage:
2322    if (isDefine)
2323      return Error(LinkageLoc, "invalid linkage for function definition");
2324    break;
2325  case GlobalValue::PrivateLinkage:
2326  case GlobalValue::LinkerPrivateLinkage:
2327  case GlobalValue::InternalLinkage:
2328  case GlobalValue::AvailableExternallyLinkage:
2329  case GlobalValue::LinkOnceAnyLinkage:
2330  case GlobalValue::LinkOnceODRLinkage:
2331  case GlobalValue::WeakAnyLinkage:
2332  case GlobalValue::WeakODRLinkage:
2333  case GlobalValue::DLLExportLinkage:
2334    if (!isDefine)
2335      return Error(LinkageLoc, "invalid linkage for function declaration");
2336    break;
2337  case GlobalValue::AppendingLinkage:
2338  case GlobalValue::GhostLinkage:
2339  case GlobalValue::CommonLinkage:
2340    return Error(LinkageLoc, "invalid function linkage type");
2341  }
2342
2343  if (!FunctionType::isValidReturnType(RetType) ||
2344      isa<OpaqueType>(RetType))
2345    return Error(RetTypeLoc, "invalid function return type");
2346
2347  LocTy NameLoc = Lex.getLoc();
2348
2349  std::string FunctionName;
2350  if (Lex.getKind() == lltok::GlobalVar) {
2351    FunctionName = Lex.getStrVal();
2352  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2353    unsigned NameID = Lex.getUIntVal();
2354
2355    if (NameID != NumberedVals.size())
2356      return TokError("function expected to be numbered '%" +
2357                      utostr(NumberedVals.size()) + "'");
2358  } else {
2359    return TokError("expected function name");
2360  }
2361
2362  Lex.Lex();
2363
2364  if (Lex.getKind() != lltok::lparen)
2365    return TokError("expected '(' in function argument list");
2366
2367  std::vector<ArgInfo> ArgList;
2368  bool isVarArg;
2369  unsigned FuncAttrs;
2370  std::string Section;
2371  unsigned Alignment;
2372  std::string GC;
2373
2374  if (ParseArgumentList(ArgList, isVarArg, false) ||
2375      ParseOptionalAttrs(FuncAttrs, 2) ||
2376      (EatIfPresent(lltok::kw_section) &&
2377       ParseStringConstant(Section)) ||
2378      ParseOptionalAlignment(Alignment) ||
2379      (EatIfPresent(lltok::kw_gc) &&
2380       ParseStringConstant(GC)))
2381    return true;
2382
2383  // If the alignment was parsed as an attribute, move to the alignment field.
2384  if (FuncAttrs & Attribute::Alignment) {
2385    Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2386    FuncAttrs &= ~Attribute::Alignment;
2387  }
2388
2389  // Okay, if we got here, the function is syntactically valid.  Convert types
2390  // and do semantic checks.
2391  std::vector<const Type*> ParamTypeList;
2392  SmallVector<AttributeWithIndex, 8> Attrs;
2393  // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2394  // attributes.
2395  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2396  if (FuncAttrs & ObsoleteFuncAttrs) {
2397    RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2398    FuncAttrs &= ~ObsoleteFuncAttrs;
2399  }
2400
2401  if (RetAttrs != Attribute::None)
2402    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2403
2404  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2405    ParamTypeList.push_back(ArgList[i].Type);
2406    if (ArgList[i].Attrs != Attribute::None)
2407      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2408  }
2409
2410  if (FuncAttrs != Attribute::None)
2411    Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2412
2413  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2414
2415  if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2416      RetType != Type::VoidTy)
2417    return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2418
2419  const FunctionType *FT =
2420    Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2421  const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2422
2423  Fn = 0;
2424  if (!FunctionName.empty()) {
2425    // If this was a definition of a forward reference, remove the definition
2426    // from the forward reference table and fill in the forward ref.
2427    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2428      ForwardRefVals.find(FunctionName);
2429    if (FRVI != ForwardRefVals.end()) {
2430      Fn = M->getFunction(FunctionName);
2431      ForwardRefVals.erase(FRVI);
2432    } else if ((Fn = M->getFunction(FunctionName))) {
2433      // If this function already exists in the symbol table, then it is
2434      // multiply defined.  We accept a few cases for old backwards compat.
2435      // FIXME: Remove this stuff for LLVM 3.0.
2436      if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2437          (!Fn->isDeclaration() && isDefine)) {
2438        // If the redefinition has different type or different attributes,
2439        // reject it.  If both have bodies, reject it.
2440        return Error(NameLoc, "invalid redefinition of function '" +
2441                     FunctionName + "'");
2442      } else if (Fn->isDeclaration()) {
2443        // Make sure to strip off any argument names so we can't get conflicts.
2444        for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2445             AI != AE; ++AI)
2446          AI->setName("");
2447      }
2448    }
2449
2450  } else if (FunctionName.empty()) {
2451    // If this is a definition of a forward referenced function, make sure the
2452    // types agree.
2453    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2454      = ForwardRefValIDs.find(NumberedVals.size());
2455    if (I != ForwardRefValIDs.end()) {
2456      Fn = cast<Function>(I->second.first);
2457      if (Fn->getType() != PFT)
2458        return Error(NameLoc, "type of definition and forward reference of '@" +
2459                     utostr(NumberedVals.size()) +"' disagree");
2460      ForwardRefValIDs.erase(I);
2461    }
2462  }
2463
2464  if (Fn == 0)
2465    Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2466  else // Move the forward-reference to the correct spot in the module.
2467    M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2468
2469  if (FunctionName.empty())
2470    NumberedVals.push_back(Fn);
2471
2472  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2473  Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2474  Fn->setCallingConv(CC);
2475  Fn->setAttributes(PAL);
2476  Fn->setAlignment(Alignment);
2477  Fn->setSection(Section);
2478  if (!GC.empty()) Fn->setGC(GC.c_str());
2479
2480  // Add all of the arguments we parsed to the function.
2481  Function::arg_iterator ArgIt = Fn->arg_begin();
2482  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2483    // If the argument has a name, insert it into the argument symbol table.
2484    if (ArgList[i].Name.empty()) continue;
2485
2486    // Set the name, if it conflicted, it will be auto-renamed.
2487    ArgIt->setName(ArgList[i].Name);
2488
2489    if (ArgIt->getNameStr() != ArgList[i].Name)
2490      return Error(ArgList[i].Loc, "redefinition of argument '%" +
2491                   ArgList[i].Name + "'");
2492  }
2493
2494  return false;
2495}
2496
2497
2498/// ParseFunctionBody
2499///   ::= '{' BasicBlock+ '}'
2500///   ::= 'begin' BasicBlock+ 'end'  // FIXME: remove in LLVM 3.0
2501///
2502bool LLParser::ParseFunctionBody(Function &Fn) {
2503  if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2504    return TokError("expected '{' in function body");
2505  Lex.Lex();  // eat the {.
2506
2507  PerFunctionState PFS(*this, Fn);
2508
2509  while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2510    if (ParseBasicBlock(PFS)) return true;
2511
2512  // Eat the }.
2513  Lex.Lex();
2514
2515  // Verify function is ok.
2516  return PFS.VerifyFunctionComplete();
2517}
2518
2519/// ParseBasicBlock
2520///   ::= LabelStr? Instruction*
2521bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2522  // If this basic block starts out with a name, remember it.
2523  std::string Name;
2524  LocTy NameLoc = Lex.getLoc();
2525  if (Lex.getKind() == lltok::LabelStr) {
2526    Name = Lex.getStrVal();
2527    Lex.Lex();
2528  }
2529
2530  BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2531  if (BB == 0) return true;
2532
2533  std::string NameStr;
2534
2535  // Parse the instructions in this block until we get a terminator.
2536  Instruction *Inst;
2537  do {
2538    // This instruction may have three possibilities for a name: a) none
2539    // specified, b) name specified "%foo =", c) number specified: "%4 =".
2540    LocTy NameLoc = Lex.getLoc();
2541    int NameID = -1;
2542    NameStr = "";
2543
2544    if (Lex.getKind() == lltok::LocalVarID) {
2545      NameID = Lex.getUIntVal();
2546      Lex.Lex();
2547      if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2548        return true;
2549    } else if (Lex.getKind() == lltok::LocalVar ||
2550               // FIXME: REMOVE IN LLVM 3.0
2551               Lex.getKind() == lltok::StringConstant) {
2552      NameStr = Lex.getStrVal();
2553      Lex.Lex();
2554      if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2555        return true;
2556    }
2557
2558    if (ParseInstruction(Inst, BB, PFS)) return true;
2559
2560    BB->getInstList().push_back(Inst);
2561
2562    // Set the name on the instruction.
2563    if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2564  } while (!isa<TerminatorInst>(Inst));
2565
2566  return false;
2567}
2568
2569//===----------------------------------------------------------------------===//
2570// Instruction Parsing.
2571//===----------------------------------------------------------------------===//
2572
2573/// ParseInstruction - Parse one of the many different instructions.
2574///
2575bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2576                                PerFunctionState &PFS) {
2577  lltok::Kind Token = Lex.getKind();
2578  if (Token == lltok::Eof)
2579    return TokError("found end of file when expecting more instructions");
2580  LocTy Loc = Lex.getLoc();
2581  unsigned KeywordVal = Lex.getUIntVal();
2582  Lex.Lex();  // Eat the keyword.
2583
2584  switch (Token) {
2585  default:                    return Error(Loc, "expected instruction opcode");
2586  // Terminator Instructions.
2587  case lltok::kw_unwind:      Inst = new UnwindInst(); return false;
2588  case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2589  case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
2590  case lltok::kw_br:          return ParseBr(Inst, PFS);
2591  case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
2592  case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
2593  // Binary Operators.
2594  case lltok::kw_add:
2595  case lltok::kw_sub:
2596  case lltok::kw_mul: {
2597    bool NUW = false;
2598    bool NSW = false;
2599    LocTy ModifierLoc = Lex.getLoc();
2600    if (EatIfPresent(lltok::kw_nuw))
2601      NUW = true;
2602    if (EatIfPresent(lltok::kw_nsw)) {
2603      NSW = true;
2604      if (EatIfPresent(lltok::kw_nuw))
2605        NUW = true;
2606    }
2607    // API compatibility: Accept either integer or floating-point types.
2608    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2609    if (!Result) {
2610      if (!Inst->getType()->isIntOrIntVector()) {
2611        if (NUW)
2612          return Error(ModifierLoc, "nuw only applies to integer operations");
2613        if (NSW)
2614          return Error(ModifierLoc, "nsw only applies to integer operations");
2615      }
2616      if (NUW)
2617        cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2618      if (NSW)
2619        cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2620    }
2621    return Result;
2622  }
2623  case lltok::kw_fadd:
2624  case lltok::kw_fsub:
2625  case lltok::kw_fmul:    return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2626
2627  case lltok::kw_sdiv: {
2628    bool Exact = false;
2629    if (EatIfPresent(lltok::kw_exact))
2630      Exact = true;
2631    bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2632    if (!Result)
2633      if (Exact)
2634        cast<SDivOperator>(Inst)->setIsExact(true);
2635    return Result;
2636  }
2637
2638  case lltok::kw_udiv:
2639  case lltok::kw_urem:
2640  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2641  case lltok::kw_fdiv:
2642  case lltok::kw_frem:   return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2643  case lltok::kw_shl:
2644  case lltok::kw_lshr:
2645  case lltok::kw_ashr:
2646  case lltok::kw_and:
2647  case lltok::kw_or:
2648  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
2649  case lltok::kw_icmp:
2650  case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
2651  // Casts.
2652  case lltok::kw_trunc:
2653  case lltok::kw_zext:
2654  case lltok::kw_sext:
2655  case lltok::kw_fptrunc:
2656  case lltok::kw_fpext:
2657  case lltok::kw_bitcast:
2658  case lltok::kw_uitofp:
2659  case lltok::kw_sitofp:
2660  case lltok::kw_fptoui:
2661  case lltok::kw_fptosi:
2662  case lltok::kw_inttoptr:
2663  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
2664  // Other.
2665  case lltok::kw_select:         return ParseSelect(Inst, PFS);
2666  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
2667  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2668  case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
2669  case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
2670  case lltok::kw_phi:            return ParsePHI(Inst, PFS);
2671  case lltok::kw_call:           return ParseCall(Inst, PFS, false);
2672  case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
2673  // Memory.
2674  case lltok::kw_alloca:
2675  case lltok::kw_malloc:         return ParseAlloc(Inst, PFS, KeywordVal);
2676  case lltok::kw_free:           return ParseFree(Inst, PFS);
2677  case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
2678  case lltok::kw_store:          return ParseStore(Inst, PFS, false);
2679  case lltok::kw_volatile:
2680    if (EatIfPresent(lltok::kw_load))
2681      return ParseLoad(Inst, PFS, true);
2682    else if (EatIfPresent(lltok::kw_store))
2683      return ParseStore(Inst, PFS, true);
2684    else
2685      return TokError("expected 'load' or 'store'");
2686  case lltok::kw_getresult:     return ParseGetResult(Inst, PFS);
2687  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2688  case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
2689  case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
2690  }
2691}
2692
2693/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2694bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2695  if (Opc == Instruction::FCmp) {
2696    switch (Lex.getKind()) {
2697    default: TokError("expected fcmp predicate (e.g. 'oeq')");
2698    case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2699    case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2700    case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2701    case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2702    case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2703    case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2704    case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2705    case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2706    case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2707    case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2708    case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2709    case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2710    case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2711    case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2712    case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2713    case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2714    }
2715  } else {
2716    switch (Lex.getKind()) {
2717    default: TokError("expected icmp predicate (e.g. 'eq')");
2718    case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
2719    case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
2720    case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2721    case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2722    case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2723    case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2724    case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2725    case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2726    case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2727    case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2728    }
2729  }
2730  Lex.Lex();
2731  return false;
2732}
2733
2734//===----------------------------------------------------------------------===//
2735// Terminator Instructions.
2736//===----------------------------------------------------------------------===//
2737
2738/// ParseRet - Parse a return instruction.
2739///   ::= 'ret' void
2740///   ::= 'ret' TypeAndValue
2741///   ::= 'ret' TypeAndValue (',' TypeAndValue)+  [[obsolete: LLVM 3.0]]
2742bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2743                        PerFunctionState &PFS) {
2744  PATypeHolder Ty(Type::VoidTy);
2745  if (ParseType(Ty, true /*void allowed*/)) return true;
2746
2747  if (Ty == Type::VoidTy) {
2748    Inst = ReturnInst::Create();
2749    return false;
2750  }
2751
2752  Value *RV;
2753  if (ParseValue(Ty, RV, PFS)) return true;
2754
2755  // The normal case is one return value.
2756  if (Lex.getKind() == lltok::comma) {
2757    // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2758    // of 'ret {i32,i32} {i32 1, i32 2}'
2759    SmallVector<Value*, 8> RVs;
2760    RVs.push_back(RV);
2761
2762    while (EatIfPresent(lltok::comma)) {
2763      if (ParseTypeAndValue(RV, PFS)) return true;
2764      RVs.push_back(RV);
2765    }
2766
2767    RV = Context.getUndef(PFS.getFunction().getReturnType());
2768    for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2769      Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2770      BB->getInstList().push_back(I);
2771      RV = I;
2772    }
2773  }
2774  Inst = ReturnInst::Create(RV);
2775  return false;
2776}
2777
2778
2779/// ParseBr
2780///   ::= 'br' TypeAndValue
2781///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2782bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2783  LocTy Loc, Loc2;
2784  Value *Op0, *Op1, *Op2;
2785  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2786
2787  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2788    Inst = BranchInst::Create(BB);
2789    return false;
2790  }
2791
2792  if (Op0->getType() != Type::Int1Ty)
2793    return Error(Loc, "branch condition must have 'i1' type");
2794
2795  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2796      ParseTypeAndValue(Op1, Loc, PFS) ||
2797      ParseToken(lltok::comma, "expected ',' after true destination") ||
2798      ParseTypeAndValue(Op2, Loc2, PFS))
2799    return true;
2800
2801  if (!isa<BasicBlock>(Op1))
2802    return Error(Loc, "true destination of branch must be a basic block");
2803  if (!isa<BasicBlock>(Op2))
2804    return Error(Loc2, "true destination of branch must be a basic block");
2805
2806  Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2807  return false;
2808}
2809
2810/// ParseSwitch
2811///  Instruction
2812///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2813///  JumpTable
2814///    ::= (TypeAndValue ',' TypeAndValue)*
2815bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2816  LocTy CondLoc, BBLoc;
2817  Value *Cond, *DefaultBB;
2818  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2819      ParseToken(lltok::comma, "expected ',' after switch condition") ||
2820      ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2821      ParseToken(lltok::lsquare, "expected '[' with switch table"))
2822    return true;
2823
2824  if (!isa<IntegerType>(Cond->getType()))
2825    return Error(CondLoc, "switch condition must have integer type");
2826  if (!isa<BasicBlock>(DefaultBB))
2827    return Error(BBLoc, "default destination must be a basic block");
2828
2829  // Parse the jump table pairs.
2830  SmallPtrSet<Value*, 32> SeenCases;
2831  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2832  while (Lex.getKind() != lltok::rsquare) {
2833    Value *Constant, *DestBB;
2834
2835    if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2836        ParseToken(lltok::comma, "expected ',' after case value") ||
2837        ParseTypeAndValue(DestBB, BBLoc, PFS))
2838      return true;
2839
2840    if (!SeenCases.insert(Constant))
2841      return Error(CondLoc, "duplicate case value in switch");
2842    if (!isa<ConstantInt>(Constant))
2843      return Error(CondLoc, "case value is not a constant integer");
2844    if (!isa<BasicBlock>(DestBB))
2845      return Error(BBLoc, "case destination is not a basic block");
2846
2847    Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2848                                   cast<BasicBlock>(DestBB)));
2849  }
2850
2851  Lex.Lex();  // Eat the ']'.
2852
2853  SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2854                                      Table.size());
2855  for (unsigned i = 0, e = Table.size(); i != e; ++i)
2856    SI->addCase(Table[i].first, Table[i].second);
2857  Inst = SI;
2858  return false;
2859}
2860
2861/// ParseInvoke
2862///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2863///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2864bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2865  LocTy CallLoc = Lex.getLoc();
2866  unsigned CC, RetAttrs, FnAttrs;
2867  PATypeHolder RetType(Type::VoidTy);
2868  LocTy RetTypeLoc;
2869  ValID CalleeID;
2870  SmallVector<ParamInfo, 16> ArgList;
2871
2872  Value *NormalBB, *UnwindBB;
2873  if (ParseOptionalCallingConv(CC) ||
2874      ParseOptionalAttrs(RetAttrs, 1) ||
2875      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2876      ParseValID(CalleeID) ||
2877      ParseParameterList(ArgList, PFS) ||
2878      ParseOptionalAttrs(FnAttrs, 2) ||
2879      ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2880      ParseTypeAndValue(NormalBB, PFS) ||
2881      ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2882      ParseTypeAndValue(UnwindBB, PFS))
2883    return true;
2884
2885  if (!isa<BasicBlock>(NormalBB))
2886    return Error(CallLoc, "normal destination is not a basic block");
2887  if (!isa<BasicBlock>(UnwindBB))
2888    return Error(CallLoc, "unwind destination is not a basic block");
2889
2890  // If RetType is a non-function pointer type, then this is the short syntax
2891  // for the call, which means that RetType is just the return type.  Infer the
2892  // rest of the function argument types from the arguments that are present.
2893  const PointerType *PFTy = 0;
2894  const FunctionType *Ty = 0;
2895  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2896      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2897    // Pull out the types of all of the arguments...
2898    std::vector<const Type*> ParamTypes;
2899    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2900      ParamTypes.push_back(ArgList[i].V->getType());
2901
2902    if (!FunctionType::isValidReturnType(RetType))
2903      return Error(RetTypeLoc, "Invalid result type for LLVM function");
2904
2905    Ty = Context.getFunctionType(RetType, ParamTypes, false);
2906    PFTy = Context.getPointerTypeUnqual(Ty);
2907  }
2908
2909  // Look up the callee.
2910  Value *Callee;
2911  if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2912
2913  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2914  // function attributes.
2915  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2916  if (FnAttrs & ObsoleteFuncAttrs) {
2917    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2918    FnAttrs &= ~ObsoleteFuncAttrs;
2919  }
2920
2921  // Set up the Attributes for the function.
2922  SmallVector<AttributeWithIndex, 8> Attrs;
2923  if (RetAttrs != Attribute::None)
2924    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2925
2926  SmallVector<Value*, 8> Args;
2927
2928  // Loop through FunctionType's arguments and ensure they are specified
2929  // correctly.  Also, gather any parameter attributes.
2930  FunctionType::param_iterator I = Ty->param_begin();
2931  FunctionType::param_iterator E = Ty->param_end();
2932  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2933    const Type *ExpectedTy = 0;
2934    if (I != E) {
2935      ExpectedTy = *I++;
2936    } else if (!Ty->isVarArg()) {
2937      return Error(ArgList[i].Loc, "too many arguments specified");
2938    }
2939
2940    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2941      return Error(ArgList[i].Loc, "argument is not of expected type '" +
2942                   ExpectedTy->getDescription() + "'");
2943    Args.push_back(ArgList[i].V);
2944    if (ArgList[i].Attrs != Attribute::None)
2945      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2946  }
2947
2948  if (I != E)
2949    return Error(CallLoc, "not enough parameters specified for call");
2950
2951  if (FnAttrs != Attribute::None)
2952    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2953
2954  // Finish off the Attributes and check them
2955  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2956
2957  InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2958                                      cast<BasicBlock>(UnwindBB),
2959                                      Args.begin(), Args.end());
2960  II->setCallingConv(CC);
2961  II->setAttributes(PAL);
2962  Inst = II;
2963  return false;
2964}
2965
2966
2967
2968//===----------------------------------------------------------------------===//
2969// Binary Operators.
2970//===----------------------------------------------------------------------===//
2971
2972/// ParseArithmetic
2973///  ::= ArithmeticOps TypeAndValue ',' Value
2974///
2975/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
2976/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2977bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2978                               unsigned Opc, unsigned OperandType) {
2979  LocTy Loc; Value *LHS, *RHS;
2980  if (ParseTypeAndValue(LHS, Loc, PFS) ||
2981      ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2982      ParseValue(LHS->getType(), RHS, PFS))
2983    return true;
2984
2985  bool Valid;
2986  switch (OperandType) {
2987  default: llvm_unreachable("Unknown operand type!");
2988  case 0: // int or FP.
2989    Valid = LHS->getType()->isIntOrIntVector() ||
2990            LHS->getType()->isFPOrFPVector();
2991    break;
2992  case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2993  case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2994  }
2995
2996  if (!Valid)
2997    return Error(Loc, "invalid operand type for instruction");
2998
2999  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3000  return false;
3001}
3002
3003/// ParseLogical
3004///  ::= ArithmeticOps TypeAndValue ',' Value {
3005bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3006                            unsigned Opc) {
3007  LocTy Loc; Value *LHS, *RHS;
3008  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3009      ParseToken(lltok::comma, "expected ',' in logical operation") ||
3010      ParseValue(LHS->getType(), RHS, PFS))
3011    return true;
3012
3013  if (!LHS->getType()->isIntOrIntVector())
3014    return Error(Loc,"instruction requires integer or integer vector operands");
3015
3016  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3017  return false;
3018}
3019
3020
3021/// ParseCompare
3022///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3023///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3024bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3025                            unsigned Opc) {
3026  // Parse the integer/fp comparison predicate.
3027  LocTy Loc;
3028  unsigned Pred;
3029  Value *LHS, *RHS;
3030  if (ParseCmpPredicate(Pred, Opc) ||
3031      ParseTypeAndValue(LHS, Loc, PFS) ||
3032      ParseToken(lltok::comma, "expected ',' after compare value") ||
3033      ParseValue(LHS->getType(), RHS, PFS))
3034    return true;
3035
3036  if (Opc == Instruction::FCmp) {
3037    if (!LHS->getType()->isFPOrFPVector())
3038      return Error(Loc, "fcmp requires floating point operands");
3039    Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3040  } else {
3041    assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3042    if (!LHS->getType()->isIntOrIntVector() &&
3043        !isa<PointerType>(LHS->getType()))
3044      return Error(Loc, "icmp requires integer operands");
3045    Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3046  }
3047  return false;
3048}
3049
3050//===----------------------------------------------------------------------===//
3051// Other Instructions.
3052//===----------------------------------------------------------------------===//
3053
3054
3055/// ParseCast
3056///   ::= CastOpc TypeAndValue 'to' Type
3057bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3058                         unsigned Opc) {
3059  LocTy Loc;  Value *Op;
3060  PATypeHolder DestTy(Type::VoidTy);
3061  if (ParseTypeAndValue(Op, Loc, PFS) ||
3062      ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3063      ParseType(DestTy))
3064    return true;
3065
3066  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3067    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3068    return Error(Loc, "invalid cast opcode for cast from '" +
3069                 Op->getType()->getDescription() + "' to '" +
3070                 DestTy->getDescription() + "'");
3071  }
3072  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3073  return false;
3074}
3075
3076/// ParseSelect
3077///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3078bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3079  LocTy Loc;
3080  Value *Op0, *Op1, *Op2;
3081  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3082      ParseToken(lltok::comma, "expected ',' after select condition") ||
3083      ParseTypeAndValue(Op1, PFS) ||
3084      ParseToken(lltok::comma, "expected ',' after select value") ||
3085      ParseTypeAndValue(Op2, PFS))
3086    return true;
3087
3088  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3089    return Error(Loc, Reason);
3090
3091  Inst = SelectInst::Create(Op0, Op1, Op2);
3092  return false;
3093}
3094
3095/// ParseVA_Arg
3096///   ::= 'va_arg' TypeAndValue ',' Type
3097bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3098  Value *Op;
3099  PATypeHolder EltTy(Type::VoidTy);
3100  LocTy TypeLoc;
3101  if (ParseTypeAndValue(Op, PFS) ||
3102      ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3103      ParseType(EltTy, TypeLoc))
3104    return true;
3105
3106  if (!EltTy->isFirstClassType())
3107    return Error(TypeLoc, "va_arg requires operand with first class type");
3108
3109  Inst = new VAArgInst(Op, EltTy);
3110  return false;
3111}
3112
3113/// ParseExtractElement
3114///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3115bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3116  LocTy Loc;
3117  Value *Op0, *Op1;
3118  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3119      ParseToken(lltok::comma, "expected ',' after extract value") ||
3120      ParseTypeAndValue(Op1, PFS))
3121    return true;
3122
3123  if (!ExtractElementInst::isValidOperands(Op0, Op1))
3124    return Error(Loc, "invalid extractelement operands");
3125
3126  Inst = ExtractElementInst::Create(Op0, Op1);
3127  return false;
3128}
3129
3130/// ParseInsertElement
3131///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3132bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3133  LocTy Loc;
3134  Value *Op0, *Op1, *Op2;
3135  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3136      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3137      ParseTypeAndValue(Op1, PFS) ||
3138      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3139      ParseTypeAndValue(Op2, PFS))
3140    return true;
3141
3142  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3143    return Error(Loc, "invalid insertelement operands");
3144
3145  Inst = InsertElementInst::Create(Op0, Op1, Op2);
3146  return false;
3147}
3148
3149/// ParseShuffleVector
3150///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3151bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3152  LocTy Loc;
3153  Value *Op0, *Op1, *Op2;
3154  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3155      ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3156      ParseTypeAndValue(Op1, PFS) ||
3157      ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3158      ParseTypeAndValue(Op2, PFS))
3159    return true;
3160
3161  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3162    return Error(Loc, "invalid extractelement operands");
3163
3164  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3165  return false;
3166}
3167
3168/// ParsePHI
3169///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3170bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3171  PATypeHolder Ty(Type::VoidTy);
3172  Value *Op0, *Op1;
3173  LocTy TypeLoc = Lex.getLoc();
3174
3175  if (ParseType(Ty) ||
3176      ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3177      ParseValue(Ty, Op0, PFS) ||
3178      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3179      ParseValue(Type::LabelTy, Op1, PFS) ||
3180      ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3181    return true;
3182
3183  SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3184  while (1) {
3185    PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3186
3187    if (!EatIfPresent(lltok::comma))
3188      break;
3189
3190    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3191        ParseValue(Ty, Op0, PFS) ||
3192        ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3193        ParseValue(Type::LabelTy, Op1, PFS) ||
3194        ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3195      return true;
3196  }
3197
3198  if (!Ty->isFirstClassType())
3199    return Error(TypeLoc, "phi node must have first class type");
3200
3201  PHINode *PN = PHINode::Create(Ty);
3202  PN->reserveOperandSpace(PHIVals.size());
3203  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3204    PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3205  Inst = PN;
3206  return false;
3207}
3208
3209/// ParseCall
3210///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3211///       ParameterList OptionalAttrs
3212bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3213                         bool isTail) {
3214  unsigned CC, RetAttrs, FnAttrs;
3215  PATypeHolder RetType(Type::VoidTy);
3216  LocTy RetTypeLoc;
3217  ValID CalleeID;
3218  SmallVector<ParamInfo, 16> ArgList;
3219  LocTy CallLoc = Lex.getLoc();
3220
3221  if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3222      ParseOptionalCallingConv(CC) ||
3223      ParseOptionalAttrs(RetAttrs, 1) ||
3224      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3225      ParseValID(CalleeID) ||
3226      ParseParameterList(ArgList, PFS) ||
3227      ParseOptionalAttrs(FnAttrs, 2))
3228    return true;
3229
3230  // If RetType is a non-function pointer type, then this is the short syntax
3231  // for the call, which means that RetType is just the return type.  Infer the
3232  // rest of the function argument types from the arguments that are present.
3233  const PointerType *PFTy = 0;
3234  const FunctionType *Ty = 0;
3235  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3236      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3237    // Pull out the types of all of the arguments...
3238    std::vector<const Type*> ParamTypes;
3239    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3240      ParamTypes.push_back(ArgList[i].V->getType());
3241
3242    if (!FunctionType::isValidReturnType(RetType))
3243      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3244
3245    Ty = Context.getFunctionType(RetType, ParamTypes, false);
3246    PFTy = Context.getPointerTypeUnqual(Ty);
3247  }
3248
3249  // Look up the callee.
3250  Value *Callee;
3251  if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3252
3253  // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3254  // function attributes.
3255  unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3256  if (FnAttrs & ObsoleteFuncAttrs) {
3257    RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3258    FnAttrs &= ~ObsoleteFuncAttrs;
3259  }
3260
3261  // Set up the Attributes for the function.
3262  SmallVector<AttributeWithIndex, 8> Attrs;
3263  if (RetAttrs != Attribute::None)
3264    Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3265
3266  SmallVector<Value*, 8> Args;
3267
3268  // Loop through FunctionType's arguments and ensure they are specified
3269  // correctly.  Also, gather any parameter attributes.
3270  FunctionType::param_iterator I = Ty->param_begin();
3271  FunctionType::param_iterator E = Ty->param_end();
3272  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3273    const Type *ExpectedTy = 0;
3274    if (I != E) {
3275      ExpectedTy = *I++;
3276    } else if (!Ty->isVarArg()) {
3277      return Error(ArgList[i].Loc, "too many arguments specified");
3278    }
3279
3280    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3281      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3282                   ExpectedTy->getDescription() + "'");
3283    Args.push_back(ArgList[i].V);
3284    if (ArgList[i].Attrs != Attribute::None)
3285      Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3286  }
3287
3288  if (I != E)
3289    return Error(CallLoc, "not enough parameters specified for call");
3290
3291  if (FnAttrs != Attribute::None)
3292    Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3293
3294  // Finish off the Attributes and check them
3295  AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3296
3297  CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3298  CI->setTailCall(isTail);
3299  CI->setCallingConv(CC);
3300  CI->setAttributes(PAL);
3301  Inst = CI;
3302  return false;
3303}
3304
3305//===----------------------------------------------------------------------===//
3306// Memory Instructions.
3307//===----------------------------------------------------------------------===//
3308
3309/// ParseAlloc
3310///   ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3311///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3312bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3313                          unsigned Opc) {
3314  PATypeHolder Ty(Type::VoidTy);
3315  Value *Size = 0;
3316  LocTy SizeLoc;
3317  unsigned Alignment = 0;
3318  if (ParseType(Ty)) return true;
3319
3320  if (EatIfPresent(lltok::comma)) {
3321    if (Lex.getKind() == lltok::kw_align) {
3322      if (ParseOptionalAlignment(Alignment)) return true;
3323    } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3324               ParseOptionalCommaAlignment(Alignment)) {
3325      return true;
3326    }
3327  }
3328
3329  if (Size && Size->getType() != Type::Int32Ty)
3330    return Error(SizeLoc, "element count must be i32");
3331
3332  if (Opc == Instruction::Malloc)
3333    Inst = new MallocInst(Ty, Size, Alignment);
3334  else
3335    Inst = new AllocaInst(Ty, Size, Alignment);
3336  return false;
3337}
3338
3339/// ParseFree
3340///   ::= 'free' TypeAndValue
3341bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3342  Value *Val; LocTy Loc;
3343  if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3344  if (!isa<PointerType>(Val->getType()))
3345    return Error(Loc, "operand to free must be a pointer");
3346  Inst = new FreeInst(Val);
3347  return false;
3348}
3349
3350/// ParseLoad
3351///   ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3352bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3353                         bool isVolatile) {
3354  Value *Val; LocTy Loc;
3355  unsigned Alignment;
3356  if (ParseTypeAndValue(Val, Loc, PFS) ||
3357      ParseOptionalCommaAlignment(Alignment))
3358    return true;
3359
3360  if (!isa<PointerType>(Val->getType()) ||
3361      !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3362    return Error(Loc, "load operand must be a pointer to a first class type");
3363
3364  Inst = new LoadInst(Val, "", isVolatile, Alignment);
3365  return false;
3366}
3367
3368/// ParseStore
3369///   ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3370bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3371                          bool isVolatile) {
3372  Value *Val, *Ptr; LocTy Loc, PtrLoc;
3373  unsigned Alignment;
3374  if (ParseTypeAndValue(Val, Loc, PFS) ||
3375      ParseToken(lltok::comma, "expected ',' after store operand") ||
3376      ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3377      ParseOptionalCommaAlignment(Alignment))
3378    return true;
3379
3380  if (!isa<PointerType>(Ptr->getType()))
3381    return Error(PtrLoc, "store operand must be a pointer");
3382  if (!Val->getType()->isFirstClassType())
3383    return Error(Loc, "store operand must be a first class value");
3384  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3385    return Error(Loc, "stored value and pointer type do not match");
3386
3387  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3388  return false;
3389}
3390
3391/// ParseGetResult
3392///   ::= 'getresult' TypeAndValue ',' i32
3393/// FIXME: Remove support for getresult in LLVM 3.0
3394bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3395  Value *Val; LocTy ValLoc, EltLoc;
3396  unsigned Element;
3397  if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3398      ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3399      ParseUInt32(Element, EltLoc))
3400    return true;
3401
3402  if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3403    return Error(ValLoc, "getresult inst requires an aggregate operand");
3404  if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3405    return Error(EltLoc, "invalid getresult index for value");
3406  Inst = ExtractValueInst::Create(Val, Element);
3407  return false;
3408}
3409
3410/// ParseGetElementPtr
3411///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3412bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3413  Value *Ptr, *Val; LocTy Loc, EltLoc;
3414
3415  bool InBounds = EatIfPresent(lltok::kw_inbounds);
3416
3417  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3418
3419  if (!isa<PointerType>(Ptr->getType()))
3420    return Error(Loc, "base of getelementptr must be a pointer");
3421
3422  SmallVector<Value*, 16> Indices;
3423  while (EatIfPresent(lltok::comma)) {
3424    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3425    if (!isa<IntegerType>(Val->getType()))
3426      return Error(EltLoc, "getelementptr index must be an integer");
3427    Indices.push_back(Val);
3428  }
3429
3430  if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3431                                         Indices.begin(), Indices.end()))
3432    return Error(Loc, "invalid getelementptr indices");
3433  Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3434  if (InBounds)
3435    cast<GEPOperator>(Inst)->setIsInBounds(true);
3436  return false;
3437}
3438
3439/// ParseExtractValue
3440///   ::= 'extractvalue' TypeAndValue (',' uint32)+
3441bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3442  Value *Val; LocTy Loc;
3443  SmallVector<unsigned, 4> Indices;
3444  if (ParseTypeAndValue(Val, Loc, PFS) ||
3445      ParseIndexList(Indices))
3446    return true;
3447
3448  if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3449    return Error(Loc, "extractvalue operand must be array or struct");
3450
3451  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3452                                        Indices.end()))
3453    return Error(Loc, "invalid indices for extractvalue");
3454  Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3455  return false;
3456}
3457
3458/// ParseInsertValue
3459///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3460bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3461  Value *Val0, *Val1; LocTy Loc0, Loc1;
3462  SmallVector<unsigned, 4> Indices;
3463  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3464      ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3465      ParseTypeAndValue(Val1, Loc1, PFS) ||
3466      ParseIndexList(Indices))
3467    return true;
3468
3469  if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3470    return Error(Loc0, "extractvalue operand must be array or struct");
3471
3472  if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3473                                        Indices.end()))
3474    return Error(Loc0, "invalid indices for insertvalue");
3475  Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3476  return false;
3477}
3478
3479//===----------------------------------------------------------------------===//
3480// Embedded metadata.
3481//===----------------------------------------------------------------------===//
3482
3483/// ParseMDNodeVector
3484///   ::= Element (',' Element)*
3485/// Element
3486///   ::= 'null' | TypeAndValue
3487bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3488  assert(Lex.getKind() == lltok::lbrace);
3489  Lex.Lex();
3490  do {
3491    Value *V = 0;
3492    if (Lex.getKind() == lltok::kw_null) {
3493      Lex.Lex();
3494      V = 0;
3495    } else {
3496      PATypeHolder Ty(Type::VoidTy);
3497      if (ParseType(Ty)) return true;
3498      if (Lex.getKind() == lltok::Metadata) {
3499        Lex.Lex();
3500        MetadataBase *Node = 0;
3501        if (!ParseMDNode(Node))
3502          V = Node;
3503        else {
3504          MetadataBase *MDS = 0;
3505          if (ParseMDString(MDS)) return true;
3506          V = MDS;
3507        }
3508      } else {
3509        Constant *C;
3510        if (ParseGlobalValue(Ty, C)) return true;
3511        V = C;
3512      }
3513    }
3514    Elts.push_back(V);
3515  } while (EatIfPresent(lltok::comma));
3516
3517  return false;
3518}
3519