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