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