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