LLParser.cpp revision 256030
1193323Sed//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed//  This file defines the parser class for .ll files.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "LLParser.h"
15249423Sdim#include "llvm/ADT/SmallPtrSet.h"
16193323Sed#include "llvm/AutoUpgrade.h"
17249423Sdim#include "llvm/IR/CallingConv.h"
18249423Sdim#include "llvm/IR/Constants.h"
19249423Sdim#include "llvm/IR/DerivedTypes.h"
20249423Sdim#include "llvm/IR/InlineAsm.h"
21249423Sdim#include "llvm/IR/Instructions.h"
22249423Sdim#include "llvm/IR/Module.h"
23249423Sdim#include "llvm/IR/Operator.h"
24249423Sdim#include "llvm/IR/ValueSymbolTable.h"
25198090Srdivacky#include "llvm/Support/ErrorHandling.h"
26193323Sed#include "llvm/Support/raw_ostream.h"
27193323Sedusing namespace llvm;
28193323Sed
29226633Sdimstatic std::string getTypeString(Type *T) {
30224145Sdim  std::string Result;
31224145Sdim  raw_string_ostream Tmp(Result);
32224145Sdim  Tmp << *T;
33224145Sdim  return Tmp.str();
34224145Sdim}
35224145Sdim
36193323Sed/// Run: module ::= toplevelentity*
37193323Sedbool LLParser::Run() {
38193323Sed  // Prime the lexer.
39193323Sed  Lex.Lex();
40193323Sed
41193323Sed  return ParseTopLevelEntities() ||
42193323Sed         ValidateEndOfModule();
43193323Sed}
44193323Sed
45193323Sed/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
46193323Sed/// module.
47193323Sedbool LLParser::ValidateEndOfModule() {
48206083Srdivacky  // Handle any instruction metadata forward references.
49206083Srdivacky  if (!ForwardRefInstMetadata.empty()) {
50206083Srdivacky    for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51206083Srdivacky         I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
52206083Srdivacky         I != E; ++I) {
53206083Srdivacky      Instruction *Inst = I->first;
54206083Srdivacky      const std::vector<MDRef> &MDList = I->second;
55249423Sdim
56206083Srdivacky      for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57206083Srdivacky        unsigned SlotNo = MDList[i].MDSlot;
58249423Sdim
59206083Srdivacky        if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60206083Srdivacky          return Error(MDList[i].Loc, "use of undefined metadata '!" +
61218893Sdim                       Twine(SlotNo) + "'");
62206083Srdivacky        Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
63206083Srdivacky      }
64206083Srdivacky    }
65206083Srdivacky    ForwardRefInstMetadata.clear();
66206083Srdivacky  }
67249423Sdim
68249423Sdim  // Handle any function attribute group forward references.
69249423Sdim  for (std::map<Value*, std::vector<unsigned> >::iterator
70249423Sdim         I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
71249423Sdim         I != E; ++I) {
72249423Sdim    Value *V = I->first;
73249423Sdim    std::vector<unsigned> &Vec = I->second;
74249423Sdim    AttrBuilder B;
75249423Sdim
76249423Sdim    for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
77249423Sdim         VI != VE; ++VI)
78249423Sdim      B.merge(NumberedAttrBuilders[*VI]);
79249423Sdim
80249423Sdim    if (Function *Fn = dyn_cast<Function>(V)) {
81249423Sdim      AttributeSet AS = Fn->getAttributes();
82249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84249423Sdim                               AS.getFnAttributes());
85249423Sdim
86249423Sdim      FnAttrs.merge(B);
87249423Sdim
88249423Sdim      // If the alignment was parsed as an attribute, move to the alignment
89249423Sdim      // field.
90249423Sdim      if (FnAttrs.hasAlignmentAttr()) {
91249423Sdim        Fn->setAlignment(FnAttrs.getAlignment());
92249423Sdim        FnAttrs.removeAttribute(Attribute::Alignment);
93249423Sdim      }
94249423Sdim
95249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96249423Sdim                            AttributeSet::get(Context,
97249423Sdim                                              AttributeSet::FunctionIndex,
98249423Sdim                                              FnAttrs));
99249423Sdim      Fn->setAttributes(AS);
100249423Sdim    } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101249423Sdim      AttributeSet AS = CI->getAttributes();
102249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104249423Sdim                               AS.getFnAttributes());
105249423Sdim      FnAttrs.merge(B);
106249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107249423Sdim                            AttributeSet::get(Context,
108249423Sdim                                              AttributeSet::FunctionIndex,
109249423Sdim                                              FnAttrs));
110249423Sdim      CI->setAttributes(AS);
111249423Sdim    } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112249423Sdim      AttributeSet AS = II->getAttributes();
113249423Sdim      AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114249423Sdim      AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115249423Sdim                               AS.getFnAttributes());
116249423Sdim      FnAttrs.merge(B);
117249423Sdim      AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118249423Sdim                            AttributeSet::get(Context,
119249423Sdim                                              AttributeSet::FunctionIndex,
120249423Sdim                                              FnAttrs));
121249423Sdim      II->setAttributes(AS);
122249423Sdim    } else {
123249423Sdim      llvm_unreachable("invalid object with forward attribute group reference");
124249423Sdim    }
125249423Sdim  }
126249423Sdim
127198892Srdivacky  // If there are entries in ForwardRefBlockAddresses at this point, they are
128198892Srdivacky  // references after the function was defined.  Resolve those now.
129198892Srdivacky  while (!ForwardRefBlockAddresses.empty()) {
130198892Srdivacky    // Okay, we are referencing an already-parsed function, resolve them now.
131198892Srdivacky    Function *TheFn = 0;
132198892Srdivacky    const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
133198892Srdivacky    if (Fn.Kind == ValID::t_GlobalName)
134198892Srdivacky      TheFn = M->getFunction(Fn.StrVal);
135198892Srdivacky    else if (Fn.UIntVal < NumberedVals.size())
136198892Srdivacky      TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
137249423Sdim
138198892Srdivacky    if (TheFn == 0)
139198892Srdivacky      return Error(Fn.Loc, "unknown function referenced by blockaddress");
140249423Sdim
141198892Srdivacky    // Resolve all these references.
142249423Sdim    if (ResolveForwardRefBlockAddresses(TheFn,
143198892Srdivacky                                      ForwardRefBlockAddresses.begin()->second,
144198892Srdivacky                                        0))
145198892Srdivacky      return true;
146249423Sdim
147198892Srdivacky    ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
148198892Srdivacky  }
149249423Sdim
150224145Sdim  for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
151224145Sdim    if (NumberedTypes[i].second.isValid())
152224145Sdim      return Error(NumberedTypes[i].second,
153224145Sdim                   "use of undefined type '%" + Twine(i) + "'");
154198090Srdivacky
155224145Sdim  for (StringMap<std::pair<Type*, LocTy> >::iterator I =
156224145Sdim       NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
157224145Sdim    if (I->second.second.isValid())
158224145Sdim      return Error(I->second.second,
159224145Sdim                   "use of undefined type named '" + I->getKey() + "'");
160224145Sdim
161193323Sed  if (!ForwardRefVals.empty())
162193323Sed    return Error(ForwardRefVals.begin()->second.second,
163193323Sed                 "use of undefined value '@" + ForwardRefVals.begin()->first +
164193323Sed                 "'");
165198090Srdivacky
166193323Sed  if (!ForwardRefValIDs.empty())
167193323Sed    return Error(ForwardRefValIDs.begin()->second.second,
168193323Sed                 "use of undefined value '@" +
169218893Sdim                 Twine(ForwardRefValIDs.begin()->first) + "'");
170198090Srdivacky
171198090Srdivacky  if (!ForwardRefMDNodes.empty())
172198090Srdivacky    return Error(ForwardRefMDNodes.begin()->second.second,
173198090Srdivacky                 "use of undefined metadata '!" +
174218893Sdim                 Twine(ForwardRefMDNodes.begin()->first) + "'");
175198090Srdivacky
176198090Srdivacky
177193323Sed  // Look for intrinsic functions and CallInst that need to be upgraded
178193323Sed  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
179193323Sed    UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
180198090Srdivacky
181193323Sed  return false;
182193323Sed}
183193323Sed
184249423Sdimbool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
185198892Srdivacky                             std::vector<std::pair<ValID, GlobalValue*> > &Refs,
186198892Srdivacky                                               PerFunctionState *PFS) {
187198892Srdivacky  // Loop over all the references, resolving them.
188198892Srdivacky  for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
189198892Srdivacky    BasicBlock *Res;
190198892Srdivacky    if (PFS) {
191198892Srdivacky      if (Refs[i].first.Kind == ValID::t_LocalName)
192198892Srdivacky        Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
193198892Srdivacky      else
194198892Srdivacky        Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
195198892Srdivacky    } else if (Refs[i].first.Kind == ValID::t_LocalID) {
196198892Srdivacky      return Error(Refs[i].first.Loc,
197198892Srdivacky       "cannot take address of numeric label after the function is defined");
198198892Srdivacky    } else {
199198892Srdivacky      Res = dyn_cast_or_null<BasicBlock>(
200198892Srdivacky                     TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
201198892Srdivacky    }
202249423Sdim
203198892Srdivacky    if (Res == 0)
204198892Srdivacky      return Error(Refs[i].first.Loc,
205198892Srdivacky                   "referenced value is not a basic block");
206249423Sdim
207198892Srdivacky    // Get the BlockAddress for this and update references to use it.
208198892Srdivacky    BlockAddress *BA = BlockAddress::get(TheFn, Res);
209198892Srdivacky    Refs[i].second->replaceAllUsesWith(BA);
210198892Srdivacky    Refs[i].second->eraseFromParent();
211198892Srdivacky  }
212198892Srdivacky  return false;
213198892Srdivacky}
214198892Srdivacky
215198892Srdivacky
216193323Sed//===----------------------------------------------------------------------===//
217193323Sed// Top-Level Entities
218193323Sed//===----------------------------------------------------------------------===//
219193323Sed
220193323Sedbool LLParser::ParseTopLevelEntities() {
221193323Sed  while (1) {
222193323Sed    switch (Lex.getKind()) {
223193323Sed    default:         return TokError("expected top-level entity");
224193323Sed    case lltok::Eof: return false;
225193323Sed    case lltok::kw_declare: if (ParseDeclare()) return true; break;
226193323Sed    case lltok::kw_define:  if (ParseDefine()) return true; break;
227193323Sed    case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
228193323Sed    case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
229193323Sed    case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
230198090Srdivacky    case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
231193323Sed    case lltok::LocalVar:   if (ParseNamedType()) return true; break;
232198090Srdivacky    case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
233193323Sed    case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
234201360Srdivacky    case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
235249423Sdim    case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
236193323Sed
237193323Sed    // The Global variable production with no name can have many different
238193323Sed    // optional leading prefixes, the production is:
239193323Sed    // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
240218893Sdim    //               OptionalAddrSpace OptionalUnNammedAddr
241218893Sdim    //               ('constant'|'global') ...
242210299Sed    case lltok::kw_private:             // OptionalLinkage
243210299Sed    case lltok::kw_linker_private:      // OptionalLinkage
244210299Sed    case lltok::kw_linker_private_weak: // OptionalLinkage
245243830Sdim    case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
246210299Sed    case lltok::kw_internal:            // OptionalLinkage
247210299Sed    case lltok::kw_weak:                // OptionalLinkage
248210299Sed    case lltok::kw_weak_odr:            // OptionalLinkage
249210299Sed    case lltok::kw_linkonce:            // OptionalLinkage
250210299Sed    case lltok::kw_linkonce_odr:        // OptionalLinkage
251243830Sdim    case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
252210299Sed    case lltok::kw_appending:           // OptionalLinkage
253210299Sed    case lltok::kw_dllexport:           // OptionalLinkage
254210299Sed    case lltok::kw_common:              // OptionalLinkage
255210299Sed    case lltok::kw_dllimport:           // OptionalLinkage
256210299Sed    case lltok::kw_extern_weak:         // OptionalLinkage
257210299Sed    case lltok::kw_external: {          // OptionalLinkage
258193323Sed      unsigned Linkage, Visibility;
259193323Sed      if (ParseOptionalLinkage(Linkage) ||
260193323Sed          ParseOptionalVisibility(Visibility) ||
261195340Sed          ParseGlobal("", SMLoc(), Linkage, true, Visibility))
262193323Sed        return true;
263193323Sed      break;
264193323Sed    }
265193323Sed    case lltok::kw_default:       // OptionalVisibility
266193323Sed    case lltok::kw_hidden:        // OptionalVisibility
267193323Sed    case lltok::kw_protected: {   // OptionalVisibility
268193323Sed      unsigned Visibility;
269193323Sed      if (ParseOptionalVisibility(Visibility) ||
270195340Sed          ParseGlobal("", SMLoc(), 0, false, Visibility))
271193323Sed        return true;
272193323Sed      break;
273193323Sed    }
274198090Srdivacky
275193323Sed    case lltok::kw_thread_local:  // OptionalThreadLocal
276193323Sed    case lltok::kw_addrspace:     // OptionalAddrSpace
277193323Sed    case lltok::kw_constant:      // GlobalType
278193323Sed    case lltok::kw_global:        // GlobalType
279195340Sed      if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
280193323Sed      break;
281249423Sdim
282249423Sdim    case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
283193323Sed    }
284193323Sed  }
285193323Sed}
286193323Sed
287193323Sed
288193323Sed/// toplevelentity
289193323Sed///   ::= 'module' 'asm' STRINGCONSTANT
290193323Sedbool LLParser::ParseModuleAsm() {
291193323Sed  assert(Lex.getKind() == lltok::kw_module);
292193323Sed  Lex.Lex();
293198090Srdivacky
294198090Srdivacky  std::string AsmStr;
295193323Sed  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
296193323Sed      ParseStringConstant(AsmStr)) return true;
297198090Srdivacky
298221345Sdim  M->appendModuleInlineAsm(AsmStr);
299193323Sed  return false;
300193323Sed}
301193323Sed
302193323Sed/// toplevelentity
303193323Sed///   ::= 'target' 'triple' '=' STRINGCONSTANT
304193323Sed///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
305193323Sedbool LLParser::ParseTargetDefinition() {
306193323Sed  assert(Lex.getKind() == lltok::kw_target);
307193323Sed  std::string Str;
308193323Sed  switch (Lex.Lex()) {
309193323Sed  default: return TokError("unknown target property");
310193323Sed  case lltok::kw_triple:
311193323Sed    Lex.Lex();
312193323Sed    if (ParseToken(lltok::equal, "expected '=' after target triple") ||
313193323Sed        ParseStringConstant(Str))
314193323Sed      return true;
315193323Sed    M->setTargetTriple(Str);
316193323Sed    return false;
317193323Sed  case lltok::kw_datalayout:
318193323Sed    Lex.Lex();
319193323Sed    if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
320193323Sed        ParseStringConstant(Str))
321193323Sed      return true;
322193323Sed    M->setDataLayout(Str);
323193323Sed    return false;
324193323Sed  }
325193323Sed}
326193323Sed
327193323Sed/// toplevelentity
328193323Sed///   ::= 'deplibs' '=' '[' ']'
329193323Sed///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
330249423Sdim/// FIXME: Remove in 4.0. Currently parse, but ignore.
331193323Sedbool LLParser::ParseDepLibs() {
332193323Sed  assert(Lex.getKind() == lltok::kw_deplibs);
333193323Sed  Lex.Lex();
334193323Sed  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
335193323Sed      ParseToken(lltok::lsquare, "expected '=' after deplibs"))
336193323Sed    return true;
337193323Sed
338193323Sed  if (EatIfPresent(lltok::rsquare))
339193323Sed    return false;
340198090Srdivacky
341249423Sdim  do {
342249423Sdim    std::string Str;
343193323Sed    if (ParseStringConstant(Str)) return true;
344249423Sdim  } while (EatIfPresent(lltok::comma));
345193323Sed
346193323Sed  return ParseToken(lltok::rsquare, "expected ']' at end of list");
347193323Sed}
348193323Sed
349198090Srdivacky/// ParseUnnamedType:
350198090Srdivacky///   ::= LocalVarID '=' 'type' type
351193323Sedbool LLParser::ParseUnnamedType() {
352193323Sed  LocTy TypeLoc = Lex.getLoc();
353224145Sdim  unsigned TypeID = Lex.getUIntVal();
354224145Sdim  Lex.Lex(); // eat LocalVarID;
355193323Sed
356224145Sdim  if (ParseToken(lltok::equal, "expected '=' after name") ||
357224145Sdim      ParseToken(lltok::kw_type, "expected 'type' after '='"))
358224145Sdim    return true;
359198090Srdivacky
360224145Sdim  if (TypeID >= NumberedTypes.size())
361224145Sdim    NumberedTypes.resize(TypeID+1);
362249423Sdim
363224145Sdim  Type *Result = 0;
364224145Sdim  if (ParseStructDefinition(TypeLoc, "",
365224145Sdim                            NumberedTypes[TypeID], Result)) return true;
366249423Sdim
367224145Sdim  if (!isa<StructType>(Result)) {
368224145Sdim    std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
369224145Sdim    if (Entry.first)
370224145Sdim      return Error(TypeLoc, "non-struct types may not be recursive");
371224145Sdim    Entry.first = Result;
372224145Sdim    Entry.second = SMLoc();
373193323Sed  }
374198090Srdivacky
375193323Sed  return false;
376193323Sed}
377193323Sed
378224145Sdim
379193323Sed/// toplevelentity
380193323Sed///   ::= LocalVar '=' 'type' type
381193323Sedbool LLParser::ParseNamedType() {
382193323Sed  std::string Name = Lex.getStrVal();
383193323Sed  LocTy NameLoc = Lex.getLoc();
384193323Sed  Lex.Lex();  // eat LocalVar.
385198090Srdivacky
386193323Sed  if (ParseToken(lltok::equal, "expected '=' after name") ||
387224145Sdim      ParseToken(lltok::kw_type, "expected 'type' after name"))
388193323Sed    return true;
389249423Sdim
390224145Sdim  Type *Result = 0;
391224145Sdim  if (ParseStructDefinition(NameLoc, Name,
392224145Sdim                            NamedTypes[Name], Result)) return true;
393249423Sdim
394224145Sdim  if (!isa<StructType>(Result)) {
395224145Sdim    std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
396224145Sdim    if (Entry.first)
397224145Sdim      return Error(NameLoc, "non-struct types may not be recursive");
398224145Sdim    Entry.first = Result;
399224145Sdim    Entry.second = SMLoc();
400193323Sed  }
401249423Sdim
402224145Sdim  return false;
403193323Sed}
404193323Sed
405193323Sed
406193323Sed/// toplevelentity
407193323Sed///   ::= 'declare' FunctionHeader
408193323Sedbool LLParser::ParseDeclare() {
409193323Sed  assert(Lex.getKind() == lltok::kw_declare);
410193323Sed  Lex.Lex();
411198090Srdivacky
412193323Sed  Function *F;
413193323Sed  return ParseFunctionHeader(F, false);
414193323Sed}
415193323Sed
416193323Sed/// toplevelentity
417193323Sed///   ::= 'define' FunctionHeader '{' ...
418193323Sedbool LLParser::ParseDefine() {
419193323Sed  assert(Lex.getKind() == lltok::kw_define);
420193323Sed  Lex.Lex();
421198090Srdivacky
422193323Sed  Function *F;
423193323Sed  return ParseFunctionHeader(F, true) ||
424193323Sed         ParseFunctionBody(*F);
425193323Sed}
426193323Sed
427193323Sed/// ParseGlobalType
428193323Sed///   ::= 'constant'
429193323Sed///   ::= 'global'
430193323Sedbool LLParser::ParseGlobalType(bool &IsConstant) {
431193323Sed  if (Lex.getKind() == lltok::kw_constant)
432193323Sed    IsConstant = true;
433193323Sed  else if (Lex.getKind() == lltok::kw_global)
434193323Sed    IsConstant = false;
435193323Sed  else {
436193323Sed    IsConstant = false;
437193323Sed    return TokError("expected 'global' or 'constant'");
438193323Sed  }
439193323Sed  Lex.Lex();
440193323Sed  return false;
441193323Sed}
442193323Sed
443198090Srdivacky/// ParseUnnamedGlobal:
444198090Srdivacky///   OptionalVisibility ALIAS ...
445198090Srdivacky///   OptionalLinkage OptionalVisibility ...   -> global variable
446198090Srdivacky///   GlobalID '=' OptionalVisibility ALIAS ...
447198090Srdivacky///   GlobalID '=' OptionalLinkage OptionalVisibility ...   -> global variable
448198090Srdivackybool LLParser::ParseUnnamedGlobal() {
449198090Srdivacky  unsigned VarID = NumberedVals.size();
450198090Srdivacky  std::string Name;
451198090Srdivacky  LocTy NameLoc = Lex.getLoc();
452198090Srdivacky
453198090Srdivacky  // Handle the GlobalID form.
454198090Srdivacky  if (Lex.getKind() == lltok::GlobalID) {
455198090Srdivacky    if (Lex.getUIntVal() != VarID)
456198090Srdivacky      return Error(Lex.getLoc(), "variable expected to be numbered '%" +
457218893Sdim                   Twine(VarID) + "'");
458198090Srdivacky    Lex.Lex(); // eat GlobalID;
459198090Srdivacky
460198090Srdivacky    if (ParseToken(lltok::equal, "expected '=' after name"))
461198090Srdivacky      return true;
462198090Srdivacky  }
463198090Srdivacky
464198090Srdivacky  bool HasLinkage;
465198090Srdivacky  unsigned Linkage, Visibility;
466198090Srdivacky  if (ParseOptionalLinkage(Linkage, HasLinkage) ||
467198090Srdivacky      ParseOptionalVisibility(Visibility))
468198090Srdivacky    return true;
469198090Srdivacky
470198090Srdivacky  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
471198090Srdivacky    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
472198090Srdivacky  return ParseAlias(Name, NameLoc, Visibility);
473198090Srdivacky}
474198090Srdivacky
475193323Sed/// ParseNamedGlobal:
476193323Sed///   GlobalVar '=' OptionalVisibility ALIAS ...
477193323Sed///   GlobalVar '=' OptionalLinkage OptionalVisibility ...   -> global variable
478193323Sedbool LLParser::ParseNamedGlobal() {
479193323Sed  assert(Lex.getKind() == lltok::GlobalVar);
480193323Sed  LocTy NameLoc = Lex.getLoc();
481193323Sed  std::string Name = Lex.getStrVal();
482193323Sed  Lex.Lex();
483198090Srdivacky
484193323Sed  bool HasLinkage;
485193323Sed  unsigned Linkage, Visibility;
486193323Sed  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
487193323Sed      ParseOptionalLinkage(Linkage, HasLinkage) ||
488193323Sed      ParseOptionalVisibility(Visibility))
489193323Sed    return true;
490198090Srdivacky
491193323Sed  if (HasLinkage || Lex.getKind() != lltok::kw_alias)
492193323Sed    return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
493193323Sed  return ParseAlias(Name, NameLoc, Visibility);
494193323Sed}
495193323Sed
496198090Srdivacky// MDString:
497198090Srdivacky//   ::= '!' STRINGCONSTANT
498201360Srdivackybool LLParser::ParseMDString(MDString *&Result) {
499198090Srdivacky  std::string Str;
500198090Srdivacky  if (ParseStringConstant(Str)) return true;
501201360Srdivacky  Result = MDString::get(Context, Str);
502198090Srdivacky  return false;
503198090Srdivacky}
504198090Srdivacky
505198090Srdivacky// MDNode:
506198090Srdivacky//   ::= '!' MDNodeNumber
507206083Srdivacky//
508206083Srdivacky/// This version of ParseMDNodeID returns the slot number and null in the case
509206083Srdivacky/// of a forward reference.
510206083Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
511206083Srdivacky  // !{ ..., !42, ... }
512206083Srdivacky  if (ParseUInt32(SlotNo)) return true;
513206083Srdivacky
514206083Srdivacky  // Check existing MDNode.
515206083Srdivacky  if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
516206083Srdivacky    Result = NumberedMetadata[SlotNo];
517206083Srdivacky  else
518206083Srdivacky    Result = 0;
519206083Srdivacky  return false;
520206083Srdivacky}
521206083Srdivacky
522201360Srdivackybool LLParser::ParseMDNodeID(MDNode *&Result) {
523198090Srdivacky  // !{ ..., !42, ... }
524198090Srdivacky  unsigned MID = 0;
525206083Srdivacky  if (ParseMDNodeID(Result, MID)) return true;
526198090Srdivacky
527206083Srdivacky  // If not a forward reference, just return it now.
528206083Srdivacky  if (Result) return false;
529198090Srdivacky
530206083Srdivacky  // Otherwise, create MDNode forward reference.
531251662Sdim  MDNode *FwdNode = MDNode::getTemporary(Context, None);
532198090Srdivacky  ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
533249423Sdim
534201360Srdivacky  if (NumberedMetadata.size() <= MID)
535201360Srdivacky    NumberedMetadata.resize(MID+1);
536201360Srdivacky  NumberedMetadata[MID] = FwdNode;
537201360Srdivacky  Result = FwdNode;
538198090Srdivacky  return false;
539198090Srdivacky}
540198090Srdivacky
541201360Srdivacky/// ParseNamedMetadata:
542198090Srdivacky///   !foo = !{ !1, !2 }
543198090Srdivackybool LLParser::ParseNamedMetadata() {
544201360Srdivacky  assert(Lex.getKind() == lltok::MetadataVar);
545201360Srdivacky  std::string Name = Lex.getStrVal();
546198090Srdivacky  Lex.Lex();
547198090Srdivacky
548201360Srdivacky  if (ParseToken(lltok::equal, "expected '=' here") ||
549201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
550201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here"))
551198090Srdivacky    return true;
552198090Srdivacky
553212904Sdim  NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
554210299Sed  if (Lex.getKind() != lltok::rbrace)
555210299Sed    do {
556210299Sed      if (ParseToken(lltok::exclaim, "Expected '!' here"))
557210299Sed        return true;
558249423Sdim
559210299Sed      MDNode *N = 0;
560210299Sed      if (ParseMDNodeID(N)) return true;
561212904Sdim      NMD->addOperand(N);
562210299Sed    } while (EatIfPresent(lltok::comma));
563198090Srdivacky
564198090Srdivacky  if (ParseToken(lltok::rbrace, "expected end of metadata node"))
565198090Srdivacky    return true;
566198090Srdivacky
567198090Srdivacky  return false;
568198090Srdivacky}
569198090Srdivacky
570195340Sed/// ParseStandaloneMetadata:
571198090Srdivacky///   !42 = !{...}
572195340Sedbool LLParser::ParseStandaloneMetadata() {
573201360Srdivacky  assert(Lex.getKind() == lltok::exclaim);
574195340Sed  Lex.Lex();
575195340Sed  unsigned MetadataID = 0;
576195340Sed
577195340Sed  LocTy TyLoc;
578224145Sdim  Type *Ty = 0;
579198090Srdivacky  SmallVector<Value *, 16> Elts;
580201360Srdivacky  if (ParseUInt32(MetadataID) ||
581201360Srdivacky      ParseToken(lltok::equal, "expected '=' here") ||
582201360Srdivacky      ParseType(Ty, TyLoc) ||
583201360Srdivacky      ParseToken(lltok::exclaim, "Expected '!' here") ||
584201360Srdivacky      ParseToken(lltok::lbrace, "Expected '{' here") ||
585202375Srdivacky      ParseMDNodeVector(Elts, NULL) ||
586201360Srdivacky      ParseToken(lltok::rbrace, "expected end of metadata node"))
587198090Srdivacky    return true;
588198090Srdivacky
589221345Sdim  MDNode *Init = MDNode::get(Context, Elts);
590249423Sdim
591201360Srdivacky  // See if this was forward referenced, if so, handle it.
592201360Srdivacky  std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
593198090Srdivacky    FI = ForwardRefMDNodes.find(MetadataID);
594198090Srdivacky  if (FI != ForwardRefMDNodes.end()) {
595212904Sdim    MDNode *Temp = FI->second.first;
596212904Sdim    Temp->replaceAllUsesWith(Init);
597212904Sdim    MDNode::deleteTemporary(Temp);
598198090Srdivacky    ForwardRefMDNodes.erase(FI);
599249423Sdim
600201360Srdivacky    assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
601201360Srdivacky  } else {
602201360Srdivacky    if (MetadataID >= NumberedMetadata.size())
603201360Srdivacky      NumberedMetadata.resize(MetadataID+1);
604198090Srdivacky
605201360Srdivacky    if (NumberedMetadata[MetadataID] != 0)
606201360Srdivacky      return TokError("Metadata id is already used");
607201360Srdivacky    NumberedMetadata[MetadataID] = Init;
608200581Srdivacky  }
609200581Srdivacky
610200581Srdivacky  return false;
611200581Srdivacky}
612200581Srdivacky
613193323Sed/// ParseAlias:
614193323Sed///   ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
615193323Sed/// Aliasee
616193323Sed///   ::= TypeAndValue
617193323Sed///   ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
618198090Srdivacky///   ::= 'getelementptr' 'inbounds'? '(' ... ')'
619193323Sed///
620193323Sed/// Everything through visibility has already been parsed.
621193323Sed///
622193323Sedbool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
623193323Sed                          unsigned Visibility) {
624193323Sed  assert(Lex.getKind() == lltok::kw_alias);
625193323Sed  Lex.Lex();
626193323Sed  unsigned Linkage;
627193323Sed  LocTy LinkageLoc = Lex.getLoc();
628193323Sed  if (ParseOptionalLinkage(Linkage))
629193323Sed    return true;
630193323Sed
631193323Sed  if (Linkage != GlobalValue::ExternalLinkage &&
632193323Sed      Linkage != GlobalValue::WeakAnyLinkage &&
633193323Sed      Linkage != GlobalValue::WeakODRLinkage &&
634193323Sed      Linkage != GlobalValue::InternalLinkage &&
635198090Srdivacky      Linkage != GlobalValue::PrivateLinkage &&
636210299Sed      Linkage != GlobalValue::LinkerPrivateLinkage &&
637243830Sdim      Linkage != GlobalValue::LinkerPrivateWeakLinkage)
638193323Sed    return Error(LinkageLoc, "invalid linkage type for alias");
639198090Srdivacky
640193323Sed  Constant *Aliasee;
641193323Sed  LocTy AliaseeLoc = Lex.getLoc();
642193323Sed  if (Lex.getKind() != lltok::kw_bitcast &&
643193323Sed      Lex.getKind() != lltok::kw_getelementptr) {
644193323Sed    if (ParseGlobalTypeAndValue(Aliasee)) return true;
645193323Sed  } else {
646193323Sed    // The bitcast dest type is not present, it is implied by the dest type.
647193323Sed    ValID ID;
648193323Sed    if (ParseValID(ID)) return true;
649193323Sed    if (ID.Kind != ValID::t_Constant)
650193323Sed      return Error(AliaseeLoc, "invalid aliasee");
651193323Sed    Aliasee = ID.ConstantVal;
652193323Sed  }
653198090Srdivacky
654204642Srdivacky  if (!Aliasee->getType()->isPointerTy())
655193323Sed    return Error(AliaseeLoc, "alias must have pointer type");
656193323Sed
657193323Sed  // Okay, create the alias but do not insert it into the module yet.
658193323Sed  GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
659193323Sed                                    (GlobalValue::LinkageTypes)Linkage, Name,
660193323Sed                                    Aliasee);
661193323Sed  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
662198090Srdivacky
663193323Sed  // See if this value already exists in the symbol table.  If so, it is either
664193323Sed  // a redefinition or a definition of a forward reference.
665198892Srdivacky  if (GlobalValue *Val = M->getNamedValue(Name)) {
666193323Sed    // See if this was a redefinition.  If so, there is no entry in
667193323Sed    // ForwardRefVals.
668193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
669193323Sed      I = ForwardRefVals.find(Name);
670193323Sed    if (I == ForwardRefVals.end())
671193323Sed      return Error(NameLoc, "redefinition of global named '@" + Name + "'");
672193323Sed
673193323Sed    // Otherwise, this was a definition of forward ref.  Verify that types
674193323Sed    // agree.
675193323Sed    if (Val->getType() != GA->getType())
676193323Sed      return Error(NameLoc,
677193323Sed              "forward reference and definition of alias have different types");
678198090Srdivacky
679193323Sed    // If they agree, just RAUW the old value with the alias and remove the
680193323Sed    // forward ref info.
681193323Sed    Val->replaceAllUsesWith(GA);
682193323Sed    Val->eraseFromParent();
683193323Sed    ForwardRefVals.erase(I);
684193323Sed  }
685198090Srdivacky
686193323Sed  // Insert into the module, we know its name won't collide now.
687193323Sed  M->getAliasList().push_back(GA);
688218893Sdim  assert(GA->getName() == Name && "Should not be a name conflict!");
689198090Srdivacky
690193323Sed  return false;
691193323Sed}
692193323Sed
693193323Sed/// ParseGlobal
694193323Sed///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
695249423Sdim///       OptionalAddrSpace OptionalUnNammedAddr
696249423Sdim///       OptionalExternallyInitialized GlobalType Type Const
697193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
698249423Sdim///       OptionalAddrSpace OptionalUnNammedAddr
699249423Sdim///       OptionalExternallyInitialized GlobalType Type Const
700193323Sed///
701193323Sed/// Everything through visibility has been parsed already.
702193323Sed///
703193323Sedbool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
704193323Sed                           unsigned Linkage, bool HasLinkage,
705193323Sed                           unsigned Visibility) {
706193323Sed  unsigned AddrSpace;
707249423Sdim  bool IsConstant, UnnamedAddr, IsExternallyInitialized;
708239462Sdim  GlobalVariable::ThreadLocalMode TLM;
709218893Sdim  LocTy UnnamedAddrLoc;
710249423Sdim  LocTy IsExternallyInitializedLoc;
711193323Sed  LocTy TyLoc;
712198090Srdivacky
713224145Sdim  Type *Ty = 0;
714239462Sdim  if (ParseOptionalThreadLocal(TLM) ||
715193323Sed      ParseOptionalAddrSpace(AddrSpace) ||
716218893Sdim      ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
717218893Sdim                         &UnnamedAddrLoc) ||
718249423Sdim      ParseOptionalToken(lltok::kw_externally_initialized,
719249423Sdim                         IsExternallyInitialized,
720249423Sdim                         &IsExternallyInitializedLoc) ||
721193323Sed      ParseGlobalType(IsConstant) ||
722193323Sed      ParseType(Ty, TyLoc))
723193323Sed    return true;
724198090Srdivacky
725193323Sed  // If the linkage is specified and is external, then no initializer is
726193323Sed  // present.
727193323Sed  Constant *Init = 0;
728193323Sed  if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
729193323Sed                      Linkage != GlobalValue::ExternalWeakLinkage &&
730193323Sed                      Linkage != GlobalValue::ExternalLinkage)) {
731193323Sed    if (ParseGlobalValue(Ty, Init))
732193323Sed      return true;
733193323Sed  }
734193323Sed
735204642Srdivacky  if (Ty->isFunctionTy() || Ty->isLabelTy())
736193323Sed    return Error(TyLoc, "invalid type for global variable");
737198090Srdivacky
738193323Sed  GlobalVariable *GV = 0;
739193323Sed
740193323Sed  // See if the global was forward referenced, if so, use the global.
741193323Sed  if (!Name.empty()) {
742198892Srdivacky    if (GlobalValue *GVal = M->getNamedValue(Name)) {
743198892Srdivacky      if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
744198892Srdivacky        return Error(NameLoc, "redefinition of global '@" + Name + "'");
745198892Srdivacky      GV = cast<GlobalVariable>(GVal);
746198892Srdivacky    }
747193323Sed  } else {
748193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
749193323Sed      I = ForwardRefValIDs.find(NumberedVals.size());
750193323Sed    if (I != ForwardRefValIDs.end()) {
751193323Sed      GV = cast<GlobalVariable>(I->second.first);
752193323Sed      ForwardRefValIDs.erase(I);
753193323Sed    }
754193323Sed  }
755193323Sed
756193323Sed  if (GV == 0) {
757198090Srdivacky    GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
758239462Sdim                            Name, 0, GlobalVariable::NotThreadLocal,
759239462Sdim                            AddrSpace);
760193323Sed  } else {
761193323Sed    if (GV->getType()->getElementType() != Ty)
762193323Sed      return Error(TyLoc,
763193323Sed            "forward reference and definition of global have different types");
764198090Srdivacky
765193323Sed    // Move the forward-reference to the correct spot in the module.
766193323Sed    M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
767193323Sed  }
768193323Sed
769193323Sed  if (Name.empty())
770193323Sed    NumberedVals.push_back(GV);
771198090Srdivacky
772193323Sed  // Set the parsed properties on the global.
773193323Sed  if (Init)
774193323Sed    GV->setInitializer(Init);
775193323Sed  GV->setConstant(IsConstant);
776193323Sed  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
777193323Sed  GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
778249423Sdim  GV->setExternallyInitialized(IsExternallyInitialized);
779239462Sdim  GV->setThreadLocalMode(TLM);
780218893Sdim  GV->setUnnamedAddr(UnnamedAddr);
781198090Srdivacky
782193323Sed  // Parse attributes on the global.
783193323Sed  while (Lex.getKind() == lltok::comma) {
784193323Sed    Lex.Lex();
785198090Srdivacky
786193323Sed    if (Lex.getKind() == lltok::kw_section) {
787193323Sed      Lex.Lex();
788193323Sed      GV->setSection(Lex.getStrVal());
789193323Sed      if (ParseToken(lltok::StringConstant, "expected global section string"))
790193323Sed        return true;
791193323Sed    } else if (Lex.getKind() == lltok::kw_align) {
792193323Sed      unsigned Alignment;
793193323Sed      if (ParseOptionalAlignment(Alignment)) return true;
794193323Sed      GV->setAlignment(Alignment);
795193323Sed    } else {
796193323Sed      TokError("unknown global variable property!");
797193323Sed    }
798193323Sed  }
799198090Srdivacky
800193323Sed  return false;
801193323Sed}
802193323Sed
803249423Sdim/// ParseUnnamedAttrGrp
804249423Sdim///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
805249423Sdimbool LLParser::ParseUnnamedAttrGrp() {
806249423Sdim  assert(Lex.getKind() == lltok::kw_attributes);
807249423Sdim  LocTy AttrGrpLoc = Lex.getLoc();
808249423Sdim  Lex.Lex();
809193323Sed
810249423Sdim  assert(Lex.getKind() == lltok::AttrGrpID);
811249423Sdim  unsigned VarID = Lex.getUIntVal();
812249423Sdim  std::vector<unsigned> unused;
813249423Sdim  LocTy NoBuiltinLoc;
814249423Sdim  Lex.Lex();
815249423Sdim
816249423Sdim  if (ParseToken(lltok::equal, "expected '=' here") ||
817249423Sdim      ParseToken(lltok::lbrace, "expected '{' here") ||
818249423Sdim      ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
819249423Sdim                                 NoBuiltinLoc) ||
820249423Sdim      ParseToken(lltok::rbrace, "expected end of attribute group"))
821249423Sdim    return true;
822249423Sdim
823249423Sdim  if (!NumberedAttrBuilders[VarID].hasAttributes())
824249423Sdim    return Error(AttrGrpLoc, "attribute group has no attributes");
825249423Sdim
826249423Sdim  return false;
827249423Sdim}
828249423Sdim
829249423Sdim/// ParseFnAttributeValuePairs
830249423Sdim///   ::= <attr> | <attr> '=' <value>
831249423Sdimbool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
832249423Sdim                                          std::vector<unsigned> &FwdRefAttrGrps,
833249423Sdim                                          bool inAttrGrp, LocTy &NoBuiltinLoc) {
834249423Sdim  bool HaveError = false;
835249423Sdim
836249423Sdim  B.clear();
837249423Sdim
838249423Sdim  while (true) {
839249423Sdim    lltok::Kind Token = Lex.getKind();
840249423Sdim    if (Token == lltok::kw_nobuiltin)
841249423Sdim      NoBuiltinLoc = Lex.getLoc();
842249423Sdim    switch (Token) {
843249423Sdim    default:
844249423Sdim      if (!inAttrGrp) return HaveError;
845249423Sdim      return Error(Lex.getLoc(), "unterminated attribute group");
846249423Sdim    case lltok::rbrace:
847249423Sdim      // Finished.
848249423Sdim      return false;
849249423Sdim
850249423Sdim    case lltok::AttrGrpID: {
851249423Sdim      // Allow a function to reference an attribute group:
852249423Sdim      //
853249423Sdim      //   define void @foo() #1 { ... }
854249423Sdim      if (inAttrGrp)
855249423Sdim        HaveError |=
856249423Sdim          Error(Lex.getLoc(),
857249423Sdim              "cannot have an attribute group reference in an attribute group");
858249423Sdim
859249423Sdim      unsigned AttrGrpNum = Lex.getUIntVal();
860249423Sdim      if (inAttrGrp) break;
861249423Sdim
862249423Sdim      // Save the reference to the attribute group. We'll fill it in later.
863249423Sdim      FwdRefAttrGrps.push_back(AttrGrpNum);
864249423Sdim      break;
865249423Sdim    }
866249423Sdim    // Target-dependent attributes:
867249423Sdim    case lltok::StringConstant: {
868249423Sdim      std::string Attr = Lex.getStrVal();
869249423Sdim      Lex.Lex();
870249423Sdim      std::string Val;
871249423Sdim      if (EatIfPresent(lltok::equal) &&
872249423Sdim          ParseStringConstant(Val))
873249423Sdim        return true;
874249423Sdim
875249423Sdim      B.addAttribute(Attr, Val);
876249423Sdim      continue;
877249423Sdim    }
878249423Sdim
879249423Sdim    // Target-independent attributes:
880249423Sdim    case lltok::kw_align: {
881251662Sdim      // As a hack, we allow function alignment to be initially parsed as an
882251662Sdim      // attribute on a function declaration/definition or added to an attribute
883251662Sdim      // group and later moved to the alignment field.
884249423Sdim      unsigned Alignment;
885249423Sdim      if (inAttrGrp) {
886249423Sdim        Lex.Lex();
887249423Sdim        if (ParseToken(lltok::equal, "expected '=' here") ||
888249423Sdim            ParseUInt32(Alignment))
889249423Sdim          return true;
890249423Sdim      } else {
891249423Sdim        if (ParseOptionalAlignment(Alignment))
892249423Sdim          return true;
893249423Sdim      }
894249423Sdim      B.addAlignmentAttr(Alignment);
895249423Sdim      continue;
896249423Sdim    }
897249423Sdim    case lltok::kw_alignstack: {
898249423Sdim      unsigned Alignment;
899249423Sdim      if (inAttrGrp) {
900249423Sdim        Lex.Lex();
901249423Sdim        if (ParseToken(lltok::equal, "expected '=' here") ||
902249423Sdim            ParseUInt32(Alignment))
903249423Sdim          return true;
904249423Sdim      } else {
905249423Sdim        if (ParseOptionalStackAlignment(Alignment))
906249423Sdim          return true;
907249423Sdim      }
908249423Sdim      B.addStackAlignmentAttr(Alignment);
909249423Sdim      continue;
910249423Sdim    }
911249423Sdim    case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
912249423Sdim    case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
913249423Sdim    case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
914249423Sdim    case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
915249423Sdim    case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
916249423Sdim    case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
917249423Sdim    case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
918249423Sdim    case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
919249423Sdim    case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
920249423Sdim    case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
921249423Sdim    case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
922249423Sdim    case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
923249423Sdim    case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
924249423Sdim    case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
925249423Sdim    case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
926249423Sdim    case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
927249423Sdim    case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
928249423Sdim    case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
929249423Sdim    case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
930249423Sdim    case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
931249423Sdim    case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
932249423Sdim    case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
933249423Sdim    case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
934249423Sdim
935249423Sdim    // Error handling.
936249423Sdim    case lltok::kw_inreg:
937249423Sdim    case lltok::kw_signext:
938249423Sdim    case lltok::kw_zeroext:
939249423Sdim      HaveError |=
940249423Sdim        Error(Lex.getLoc(),
941249423Sdim              "invalid use of attribute on a function");
942249423Sdim      break;
943249423Sdim    case lltok::kw_byval:
944249423Sdim    case lltok::kw_nest:
945249423Sdim    case lltok::kw_noalias:
946249423Sdim    case lltok::kw_nocapture:
947251662Sdim    case lltok::kw_returned:
948249423Sdim    case lltok::kw_sret:
949249423Sdim      HaveError |=
950249423Sdim        Error(Lex.getLoc(),
951249423Sdim              "invalid use of parameter-only attribute on a function");
952249423Sdim      break;
953249423Sdim    }
954249423Sdim
955249423Sdim    Lex.Lex();
956249423Sdim  }
957249423Sdim}
958249423Sdim
959193323Sed//===----------------------------------------------------------------------===//
960193323Sed// GlobalValue Reference/Resolution Routines.
961193323Sed//===----------------------------------------------------------------------===//
962193323Sed
963193323Sed/// GetGlobalVal - Get a value with the specified name or ID, creating a
964193323Sed/// forward reference record if needed.  This can return null if the value
965193323Sed/// exists but does not have the right type.
966226633SdimGlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
967193323Sed                                    LocTy Loc) {
968226633Sdim  PointerType *PTy = dyn_cast<PointerType>(Ty);
969193323Sed  if (PTy == 0) {
970193323Sed    Error(Loc, "global variable reference must have pointer type");
971193323Sed    return 0;
972193323Sed  }
973198090Srdivacky
974193323Sed  // Look this name up in the normal function symbol table.
975193323Sed  GlobalValue *Val =
976193323Sed    cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
977198090Srdivacky
978193323Sed  // If this is a forward reference for the value, see if we already created a
979193323Sed  // forward ref record.
980193323Sed  if (Val == 0) {
981193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
982193323Sed      I = ForwardRefVals.find(Name);
983193323Sed    if (I != ForwardRefVals.end())
984193323Sed      Val = I->second.first;
985193323Sed  }
986198090Srdivacky
987193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
988193323Sed  if (Val) {
989193323Sed    if (Val->getType() == Ty) return Val;
990193323Sed    Error(Loc, "'@" + Name + "' defined with type '" +
991224145Sdim          getTypeString(Val->getType()) + "'");
992193323Sed    return 0;
993193323Sed  }
994198090Srdivacky
995193323Sed  // Otherwise, create a new forward reference for this value and remember it.
996193323Sed  GlobalValue *FwdVal;
997226633Sdim  if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
998193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
999224145Sdim  else
1000198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1001243830Sdim                                GlobalValue::ExternalWeakLinkage, 0, Name,
1002243830Sdim                                0, GlobalVariable::NotThreadLocal,
1003243830Sdim                                PTy->getAddressSpace());
1004198090Srdivacky
1005193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1006193323Sed  return FwdVal;
1007193323Sed}
1008193323Sed
1009226633SdimGlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1010226633Sdim  PointerType *PTy = dyn_cast<PointerType>(Ty);
1011193323Sed  if (PTy == 0) {
1012193323Sed    Error(Loc, "global variable reference must have pointer type");
1013193323Sed    return 0;
1014193323Sed  }
1015198090Srdivacky
1016193323Sed  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1017198090Srdivacky
1018193323Sed  // If this is a forward reference for the value, see if we already created a
1019193323Sed  // forward ref record.
1020193323Sed  if (Val == 0) {
1021193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1022193323Sed      I = ForwardRefValIDs.find(ID);
1023193323Sed    if (I != ForwardRefValIDs.end())
1024193323Sed      Val = I->second.first;
1025193323Sed  }
1026198090Srdivacky
1027193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
1028193323Sed  if (Val) {
1029193323Sed    if (Val->getType() == Ty) return Val;
1030218893Sdim    Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1031224145Sdim          getTypeString(Val->getType()) + "'");
1032193323Sed    return 0;
1033193323Sed  }
1034198090Srdivacky
1035193323Sed  // Otherwise, create a new forward reference for this value and remember it.
1036193323Sed  GlobalValue *FwdVal;
1037226633Sdim  if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1038193323Sed    FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1039224145Sdim  else
1040198090Srdivacky    FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1041198090Srdivacky                                GlobalValue::ExternalWeakLinkage, 0, "");
1042198090Srdivacky
1043193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1044193323Sed  return FwdVal;
1045193323Sed}
1046193323Sed
1047193323Sed
1048193323Sed//===----------------------------------------------------------------------===//
1049193323Sed// Helper Routines.
1050193323Sed//===----------------------------------------------------------------------===//
1051193323Sed
1052193323Sed/// ParseToken - If the current token has the specified kind, eat it and return
1053193323Sed/// success.  Otherwise, emit the specified error and return failure.
1054193323Sedbool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1055193323Sed  if (Lex.getKind() != T)
1056193323Sed    return TokError(ErrMsg);
1057193323Sed  Lex.Lex();
1058193323Sed  return false;
1059193323Sed}
1060193323Sed
1061193323Sed/// ParseStringConstant
1062193323Sed///   ::= StringConstant
1063193323Sedbool LLParser::ParseStringConstant(std::string &Result) {
1064193323Sed  if (Lex.getKind() != lltok::StringConstant)
1065193323Sed    return TokError("expected string constant");
1066193323Sed  Result = Lex.getStrVal();
1067193323Sed  Lex.Lex();
1068193323Sed  return false;
1069193323Sed}
1070193323Sed
1071193323Sed/// ParseUInt32
1072193323Sed///   ::= uint32
1073193323Sedbool LLParser::ParseUInt32(unsigned &Val) {
1074193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1075193323Sed    return TokError("expected integer");
1076193323Sed  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1077193323Sed  if (Val64 != unsigned(Val64))
1078193323Sed    return TokError("expected 32-bit integer (too large)");
1079193323Sed  Val = Val64;
1080193323Sed  Lex.Lex();
1081193323Sed  return false;
1082193323Sed}
1083193323Sed
1084239462Sdim/// ParseTLSModel
1085239462Sdim///   := 'localdynamic'
1086239462Sdim///   := 'initialexec'
1087239462Sdim///   := 'localexec'
1088239462Sdimbool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1089239462Sdim  switch (Lex.getKind()) {
1090239462Sdim    default:
1091239462Sdim      return TokError("expected localdynamic, initialexec or localexec");
1092239462Sdim    case lltok::kw_localdynamic:
1093239462Sdim      TLM = GlobalVariable::LocalDynamicTLSModel;
1094239462Sdim      break;
1095239462Sdim    case lltok::kw_initialexec:
1096239462Sdim      TLM = GlobalVariable::InitialExecTLSModel;
1097239462Sdim      break;
1098239462Sdim    case lltok::kw_localexec:
1099239462Sdim      TLM = GlobalVariable::LocalExecTLSModel;
1100239462Sdim      break;
1101239462Sdim  }
1102193323Sed
1103239462Sdim  Lex.Lex();
1104239462Sdim  return false;
1105239462Sdim}
1106239462Sdim
1107239462Sdim/// ParseOptionalThreadLocal
1108239462Sdim///   := /*empty*/
1109239462Sdim///   := 'thread_local'
1110239462Sdim///   := 'thread_local' '(' tlsmodel ')'
1111239462Sdimbool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1112239462Sdim  TLM = GlobalVariable::NotThreadLocal;
1113239462Sdim  if (!EatIfPresent(lltok::kw_thread_local))
1114239462Sdim    return false;
1115239462Sdim
1116239462Sdim  TLM = GlobalVariable::GeneralDynamicTLSModel;
1117239462Sdim  if (Lex.getKind() == lltok::lparen) {
1118239462Sdim    Lex.Lex();
1119239462Sdim    return ParseTLSModel(TLM) ||
1120239462Sdim      ParseToken(lltok::rparen, "expected ')' after thread local model");
1121239462Sdim  }
1122239462Sdim  return false;
1123239462Sdim}
1124239462Sdim
1125193323Sed/// ParseOptionalAddrSpace
1126193323Sed///   := /*empty*/
1127193323Sed///   := 'addrspace' '(' uint32 ')'
1128193323Sedbool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1129193323Sed  AddrSpace = 0;
1130193323Sed  if (!EatIfPresent(lltok::kw_addrspace))
1131193323Sed    return false;
1132193323Sed  return ParseToken(lltok::lparen, "expected '(' in address space") ||
1133193323Sed         ParseUInt32(AddrSpace) ||
1134193323Sed         ParseToken(lltok::rparen, "expected ')' in address space");
1135198090Srdivacky}
1136193323Sed
1137249423Sdim/// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1138249423Sdimbool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1139243830Sdim  bool HaveError = false;
1140198090Srdivacky
1141243830Sdim  B.clear();
1142243830Sdim
1143193323Sed  while (1) {
1144243830Sdim    lltok::Kind Token = Lex.getKind();
1145243830Sdim    switch (Token) {
1146193323Sed    default:  // End of attributes.
1147243830Sdim      return HaveError;
1148193323Sed    case lltok::kw_align: {
1149193323Sed      unsigned Alignment;
1150193323Sed      if (ParseOptionalAlignment(Alignment))
1151193323Sed        return true;
1152243830Sdim      B.addAlignmentAttr(Alignment);
1153193323Sed      continue;
1154193323Sed    }
1155249423Sdim    case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1156249423Sdim    case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1157249423Sdim    case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1158249423Sdim    case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1159249423Sdim    case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1160251662Sdim    case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1161249423Sdim    case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1162249423Sdim    case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1163249423Sdim    case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1164203954Srdivacky
1165251662Sdim    case lltok::kw_alignstack:
1166251662Sdim    case lltok::kw_alwaysinline:
1167251662Sdim    case lltok::kw_inlinehint:
1168251662Sdim    case lltok::kw_minsize:
1169251662Sdim    case lltok::kw_naked:
1170251662Sdim    case lltok::kw_nobuiltin:
1171251662Sdim    case lltok::kw_noduplicate:
1172251662Sdim    case lltok::kw_noimplicitfloat:
1173251662Sdim    case lltok::kw_noinline:
1174251662Sdim    case lltok::kw_nonlazybind:
1175251662Sdim    case lltok::kw_noredzone:
1176251662Sdim    case lltok::kw_noreturn:
1177251662Sdim    case lltok::kw_nounwind:
1178251662Sdim    case lltok::kw_optsize:
1179251662Sdim    case lltok::kw_readnone:
1180251662Sdim    case lltok::kw_readonly:
1181251662Sdim    case lltok::kw_returns_twice:
1182251662Sdim    case lltok::kw_sanitize_address:
1183251662Sdim    case lltok::kw_sanitize_memory:
1184251662Sdim    case lltok::kw_sanitize_thread:
1185251662Sdim    case lltok::kw_ssp:
1186251662Sdim    case lltok::kw_sspreq:
1187251662Sdim    case lltok::kw_sspstrong:
1188251662Sdim    case lltok::kw_uwtable:
1189249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1190249423Sdim      break;
1191193323Sed    }
1192243830Sdim
1193249423Sdim    Lex.Lex();
1194249423Sdim  }
1195249423Sdim}
1196249423Sdim
1197249423Sdim/// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1198249423Sdimbool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1199249423Sdim  bool HaveError = false;
1200249423Sdim
1201249423Sdim  B.clear();
1202249423Sdim
1203249423Sdim  while (1) {
1204249423Sdim    lltok::Kind Token = Lex.getKind();
1205243830Sdim    switch (Token) {
1206249423Sdim    default:  // End of attributes.
1207249423Sdim      return HaveError;
1208249423Sdim    case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1209249423Sdim    case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1210249423Sdim    case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1211249423Sdim    case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1212243830Sdim
1213249423Sdim    // Error handling.
1214251662Sdim    case lltok::kw_align:
1215251662Sdim    case lltok::kw_byval:
1216251662Sdim    case lltok::kw_nest:
1217251662Sdim    case lltok::kw_nocapture:
1218251662Sdim    case lltok::kw_returned:
1219251662Sdim    case lltok::kw_sret:
1220249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1221243830Sdim      break;
1222243830Sdim
1223251662Sdim    case lltok::kw_alignstack:
1224251662Sdim    case lltok::kw_alwaysinline:
1225251662Sdim    case lltok::kw_inlinehint:
1226251662Sdim    case lltok::kw_minsize:
1227251662Sdim    case lltok::kw_naked:
1228251662Sdim    case lltok::kw_nobuiltin:
1229251662Sdim    case lltok::kw_noduplicate:
1230251662Sdim    case lltok::kw_noimplicitfloat:
1231251662Sdim    case lltok::kw_noinline:
1232251662Sdim    case lltok::kw_nonlazybind:
1233251662Sdim    case lltok::kw_noredzone:
1234251662Sdim    case lltok::kw_noreturn:
1235251662Sdim    case lltok::kw_nounwind:
1236251662Sdim    case lltok::kw_optsize:
1237251662Sdim    case lltok::kw_readnone:
1238251662Sdim    case lltok::kw_readonly:
1239251662Sdim    case lltok::kw_returns_twice:
1240251662Sdim    case lltok::kw_sanitize_address:
1241251662Sdim    case lltok::kw_sanitize_memory:
1242251662Sdim    case lltok::kw_sanitize_thread:
1243251662Sdim    case lltok::kw_ssp:
1244251662Sdim    case lltok::kw_sspreq:
1245251662Sdim    case lltok::kw_sspstrong:
1246251662Sdim    case lltok::kw_uwtable:
1247249423Sdim      HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1248243830Sdim      break;
1249243830Sdim    }
1250243830Sdim
1251193323Sed    Lex.Lex();
1252193323Sed  }
1253193323Sed}
1254193323Sed
1255193323Sed/// ParseOptionalLinkage
1256193323Sed///   ::= /*empty*/
1257193323Sed///   ::= 'private'
1258198090Srdivacky///   ::= 'linker_private'
1259210299Sed///   ::= 'linker_private_weak'
1260193323Sed///   ::= 'internal'
1261193323Sed///   ::= 'weak'
1262193323Sed///   ::= 'weak_odr'
1263193323Sed///   ::= 'linkonce'
1264193323Sed///   ::= 'linkonce_odr'
1265243830Sdim///   ::= 'linkonce_odr_auto_hide'
1266210299Sed///   ::= 'available_externally'
1267193323Sed///   ::= 'appending'
1268193323Sed///   ::= 'dllexport'
1269193323Sed///   ::= 'common'
1270193323Sed///   ::= 'dllimport'
1271193323Sed///   ::= 'extern_weak'
1272193323Sed///   ::= 'external'
1273193323Sedbool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1274193323Sed  HasLinkage = false;
1275193323Sed  switch (Lex.getKind()) {
1276198090Srdivacky  default:                       Res=GlobalValue::ExternalLinkage; return false;
1277198090Srdivacky  case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1278198090Srdivacky  case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1279210299Sed  case lltok::kw_linker_private_weak:
1280210299Sed    Res = GlobalValue::LinkerPrivateWeakLinkage;
1281210299Sed    break;
1282198090Srdivacky  case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1283198090Srdivacky  case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1284198090Srdivacky  case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1285198090Srdivacky  case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1286198090Srdivacky  case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1287243830Sdim  case lltok::kw_linkonce_odr_auto_hide:
1288243830Sdim  case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1289243830Sdim    Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1290243830Sdim    break;
1291193323Sed  case lltok::kw_available_externally:
1292193323Sed    Res = GlobalValue::AvailableExternallyLinkage;
1293193323Sed    break;
1294198090Srdivacky  case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1295198090Srdivacky  case lltok::kw_dllexport:      Res = GlobalValue::DLLExportLinkage;     break;
1296198090Srdivacky  case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1297198090Srdivacky  case lltok::kw_dllimport:      Res = GlobalValue::DLLImportLinkage;     break;
1298198090Srdivacky  case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1299198090Srdivacky  case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1300193323Sed  }
1301193323Sed  Lex.Lex();
1302193323Sed  HasLinkage = true;
1303193323Sed  return false;
1304193323Sed}
1305193323Sed
1306193323Sed/// ParseOptionalVisibility
1307193323Sed///   ::= /*empty*/
1308193323Sed///   ::= 'default'
1309193323Sed///   ::= 'hidden'
1310193323Sed///   ::= 'protected'
1311198090Srdivacky///
1312193323Sedbool LLParser::ParseOptionalVisibility(unsigned &Res) {
1313193323Sed  switch (Lex.getKind()) {
1314193323Sed  default:                  Res = GlobalValue::DefaultVisibility; return false;
1315193323Sed  case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1316193323Sed  case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1317193323Sed  case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1318193323Sed  }
1319193323Sed  Lex.Lex();
1320193323Sed  return false;
1321193323Sed}
1322193323Sed
1323193323Sed/// ParseOptionalCallingConv
1324193323Sed///   ::= /*empty*/
1325193323Sed///   ::= 'ccc'
1326193323Sed///   ::= 'fastcc'
1327243830Sdim///   ::= 'kw_intel_ocl_bicc'
1328193323Sed///   ::= 'coldcc'
1329193323Sed///   ::= 'x86_stdcallcc'
1330193323Sed///   ::= 'x86_fastcallcc'
1331208599Srdivacky///   ::= 'x86_thiscallcc'
1332194612Sed///   ::= 'arm_apcscc'
1333194612Sed///   ::= 'arm_aapcscc'
1334194612Sed///   ::= 'arm_aapcs_vfpcc'
1335200581Srdivacky///   ::= 'msp430_intrcc'
1336218893Sdim///   ::= 'ptx_kernel'
1337218893Sdim///   ::= 'ptx_device'
1338243830Sdim///   ::= 'spir_func'
1339243830Sdim///   ::= 'spir_kernel'
1340256030Sdim///   ::= 'x86_64_sysvcc'
1341256030Sdim///   ::= 'x86_64_win64cc'
1342193323Sed///   ::= 'cc' UINT
1343194612Sed///
1344198090Srdivackybool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1345193323Sed  switch (Lex.getKind()) {
1346193323Sed  default:                       CC = CallingConv::C; return false;
1347193323Sed  case lltok::kw_ccc:            CC = CallingConv::C; break;
1348193323Sed  case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1349193323Sed  case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1350193323Sed  case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1351193323Sed  case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1352208599Srdivacky  case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1353194612Sed  case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1354194612Sed  case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1355194612Sed  case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1356200581Srdivacky  case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1357218893Sdim  case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1358218893Sdim  case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1359243830Sdim  case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1360243830Sdim  case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1361243830Sdim  case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1362256030Sdim  case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1363256030Sdim  case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1364198090Srdivacky  case lltok::kw_cc: {
1365198090Srdivacky      unsigned ArbitraryCC;
1366198090Srdivacky      Lex.Lex();
1367234353Sdim      if (ParseUInt32(ArbitraryCC))
1368198090Srdivacky        return true;
1369234353Sdim      CC = static_cast<CallingConv::ID>(ArbitraryCC);
1370234353Sdim      return false;
1371198090Srdivacky    }
1372193323Sed  }
1373198090Srdivacky
1374193323Sed  Lex.Lex();
1375193323Sed  return false;
1376193323Sed}
1377193323Sed
1378201360Srdivacky/// ParseInstructionMetadata
1379201360Srdivacky///   ::= !dbg !42 (',' !dbg !57)*
1380212904Sdimbool LLParser::ParseInstructionMetadata(Instruction *Inst,
1381212904Sdim                                        PerFunctionState *PFS) {
1382201360Srdivacky  do {
1383201360Srdivacky    if (Lex.getKind() != lltok::MetadataVar)
1384201360Srdivacky      return TokError("expected metadata after comma");
1385198090Srdivacky
1386201360Srdivacky    std::string Name = Lex.getStrVal();
1387234353Sdim    unsigned MDK = M->getMDKindID(Name);
1388201360Srdivacky    Lex.Lex();
1389198396Srdivacky
1390201360Srdivacky    MDNode *Node;
1391206083Srdivacky    SMLoc Loc = Lex.getLoc();
1392212904Sdim
1393212904Sdim    if (ParseToken(lltok::exclaim, "expected '!' here"))
1394201360Srdivacky      return true;
1395198090Srdivacky
1396212904Sdim    // This code is similar to that of ParseMetadataValue, however it needs to
1397212904Sdim    // have special-case code for a forward reference; see the comments on
1398212904Sdim    // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1399212904Sdim    // at the top level here.
1400212904Sdim    if (Lex.getKind() == lltok::lbrace) {
1401212904Sdim      ValID ID;
1402212904Sdim      if (ParseMetadataListValue(ID, PFS))
1403212904Sdim        return true;
1404212904Sdim      assert(ID.Kind == ValID::t_MDNode);
1405212904Sdim      Inst->setMetadata(MDK, ID.MDNodeVal);
1406206083Srdivacky    } else {
1407218893Sdim      unsigned NodeID = 0;
1408212904Sdim      if (ParseMDNodeID(Node, NodeID))
1409212904Sdim        return true;
1410212904Sdim      if (Node) {
1411212904Sdim        // If we got the node, add it to the instruction.
1412212904Sdim        Inst->setMetadata(MDK, Node);
1413212904Sdim      } else {
1414212904Sdim        MDRef R = { Loc, MDK, NodeID };
1415212904Sdim        // Otherwise, remember that this should be resolved later.
1416212904Sdim        ForwardRefInstMetadata[Inst].push_back(R);
1417212904Sdim      }
1418206083Srdivacky    }
1419198090Srdivacky
1420201360Srdivacky    // If this is the end of the list, we're done.
1421201360Srdivacky  } while (EatIfPresent(lltok::comma));
1422198090Srdivacky  return false;
1423198090Srdivacky}
1424198090Srdivacky
1425193323Sed/// ParseOptionalAlignment
1426193323Sed///   ::= /* empty */
1427193323Sed///   ::= 'align' 4
1428193323Sedbool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1429193323Sed  Alignment = 0;
1430193323Sed  if (!EatIfPresent(lltok::kw_align))
1431193323Sed    return false;
1432193323Sed  LocTy AlignLoc = Lex.getLoc();
1433193323Sed  if (ParseUInt32(Alignment)) return true;
1434193323Sed  if (!isPowerOf2_32(Alignment))
1435193323Sed    return Error(AlignLoc, "alignment is not a power of two");
1436212904Sdim  if (Alignment > Value::MaximumAlignment)
1437212904Sdim    return Error(AlignLoc, "huge alignments are not supported yet");
1438193323Sed  return false;
1439193323Sed}
1440193323Sed
1441201360Srdivacky/// ParseOptionalCommaAlign
1442249423Sdim///   ::=
1443201360Srdivacky///   ::= ',' align 4
1444201360Srdivacky///
1445201360Srdivacky/// This returns with AteExtraComma set to true if it ate an excess comma at the
1446201360Srdivacky/// end.
1447201360Srdivackybool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1448201360Srdivacky                                       bool &AteExtraComma) {
1449201360Srdivacky  AteExtraComma = false;
1450201360Srdivacky  while (EatIfPresent(lltok::comma)) {
1451201360Srdivacky    // Metadata at the end is an early exit.
1452201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1453201360Srdivacky      AteExtraComma = true;
1454201360Srdivacky      return false;
1455201360Srdivacky    }
1456249423Sdim
1457207618Srdivacky    if (Lex.getKind() != lltok::kw_align)
1458207618Srdivacky      return Error(Lex.getLoc(), "expected metadata or 'align'");
1459218893Sdim
1460207618Srdivacky    if (ParseOptionalAlignment(Alignment)) return true;
1461201360Srdivacky  }
1462198090Srdivacky
1463198090Srdivacky  return false;
1464193323Sed}
1465193323Sed
1466226633Sdim/// ParseScopeAndOrdering
1467226633Sdim///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1468226633Sdim///   else: ::=
1469226633Sdim///
1470226633Sdim/// This sets Scope and Ordering to the parsed values.
1471226633Sdimbool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1472226633Sdim                                     AtomicOrdering &Ordering) {
1473226633Sdim  if (!isAtomic)
1474226633Sdim    return false;
1475226633Sdim
1476226633Sdim  Scope = CrossThread;
1477226633Sdim  if (EatIfPresent(lltok::kw_singlethread))
1478226633Sdim    Scope = SingleThread;
1479226633Sdim  switch (Lex.getKind()) {
1480226633Sdim  default: return TokError("Expected ordering on atomic instruction");
1481226633Sdim  case lltok::kw_unordered: Ordering = Unordered; break;
1482226633Sdim  case lltok::kw_monotonic: Ordering = Monotonic; break;
1483226633Sdim  case lltok::kw_acquire: Ordering = Acquire; break;
1484226633Sdim  case lltok::kw_release: Ordering = Release; break;
1485226633Sdim  case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1486226633Sdim  case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1487226633Sdim  }
1488226633Sdim  Lex.Lex();
1489226633Sdim  return false;
1490226633Sdim}
1491226633Sdim
1492203954Srdivacky/// ParseOptionalStackAlignment
1493203954Srdivacky///   ::= /* empty */
1494203954Srdivacky///   ::= 'alignstack' '(' 4 ')'
1495203954Srdivackybool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1496203954Srdivacky  Alignment = 0;
1497203954Srdivacky  if (!EatIfPresent(lltok::kw_alignstack))
1498203954Srdivacky    return false;
1499203954Srdivacky  LocTy ParenLoc = Lex.getLoc();
1500203954Srdivacky  if (!EatIfPresent(lltok::lparen))
1501203954Srdivacky    return Error(ParenLoc, "expected '('");
1502203954Srdivacky  LocTy AlignLoc = Lex.getLoc();
1503203954Srdivacky  if (ParseUInt32(Alignment)) return true;
1504203954Srdivacky  ParenLoc = Lex.getLoc();
1505203954Srdivacky  if (!EatIfPresent(lltok::rparen))
1506203954Srdivacky    return Error(ParenLoc, "expected ')'");
1507203954Srdivacky  if (!isPowerOf2_32(Alignment))
1508203954Srdivacky    return Error(AlignLoc, "stack alignment is not a power of two");
1509203954Srdivacky  return false;
1510203954Srdivacky}
1511198090Srdivacky
1512201360Srdivacky/// ParseIndexList - This parses the index list for an insert/extractvalue
1513201360Srdivacky/// instruction.  This sets AteExtraComma in the case where we eat an extra
1514201360Srdivacky/// comma at the end of the line and find that it is followed by metadata.
1515201360Srdivacky/// Clients that don't allow metadata can call the version of this function that
1516201360Srdivacky/// only takes one argument.
1517201360Srdivacky///
1518193323Sed/// ParseIndexList
1519193323Sed///    ::=  (',' uint32)+
1520201360Srdivacky///
1521201360Srdivackybool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1522201360Srdivacky                              bool &AteExtraComma) {
1523201360Srdivacky  AteExtraComma = false;
1524249423Sdim
1525193323Sed  if (Lex.getKind() != lltok::comma)
1526193323Sed    return TokError("expected ',' as start of index list");
1527198090Srdivacky
1528193323Sed  while (EatIfPresent(lltok::comma)) {
1529201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
1530201360Srdivacky      AteExtraComma = true;
1531201360Srdivacky      return false;
1532201360Srdivacky    }
1533218893Sdim    unsigned Idx = 0;
1534193323Sed    if (ParseUInt32(Idx)) return true;
1535193323Sed    Indices.push_back(Idx);
1536193323Sed  }
1537198090Srdivacky
1538193323Sed  return false;
1539193323Sed}
1540193323Sed
1541193323Sed//===----------------------------------------------------------------------===//
1542193323Sed// Type Parsing.
1543193323Sed//===----------------------------------------------------------------------===//
1544193323Sed
1545224145Sdim/// ParseType - Parse a type.
1546224145Sdimbool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1547224145Sdim  SMLoc TypeLoc = Lex.getLoc();
1548193323Sed  switch (Lex.getKind()) {
1549193323Sed  default:
1550193323Sed    return TokError("expected type");
1551193323Sed  case lltok::Type:
1552224145Sdim    // Type ::= 'float' | 'void' (etc)
1553193323Sed    Result = Lex.getTyVal();
1554198090Srdivacky    Lex.Lex();
1555193323Sed    break;
1556193323Sed  case lltok::lbrace:
1557224145Sdim    // Type ::= StructType
1558224145Sdim    if (ParseAnonStructType(Result, false))
1559193323Sed      return true;
1560193323Sed    break;
1561193323Sed  case lltok::lsquare:
1562224145Sdim    // Type ::= '[' ... ']'
1563193323Sed    Lex.Lex(); // eat the lsquare.
1564193323Sed    if (ParseArrayVectorType(Result, false))
1565193323Sed      return true;
1566193323Sed    break;
1567193323Sed  case lltok::less: // Either vector or packed struct.
1568224145Sdim    // Type ::= '<' ... '>'
1569193323Sed    Lex.Lex();
1570193323Sed    if (Lex.getKind() == lltok::lbrace) {
1571224145Sdim      if (ParseAnonStructType(Result, true) ||
1572193323Sed          ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1573193323Sed        return true;
1574193323Sed    } else if (ParseArrayVectorType(Result, true))
1575193323Sed      return true;
1576193323Sed    break;
1577224145Sdim  case lltok::LocalVar: {
1578224145Sdim    // Type ::= %foo
1579224145Sdim    std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1580249423Sdim
1581224145Sdim    // If the type hasn't been defined yet, create a forward definition and
1582224145Sdim    // remember where that forward def'n was seen (in case it never is defined).
1583224145Sdim    if (Entry.first == 0) {
1584226633Sdim      Entry.first = StructType::create(Context, Lex.getStrVal());
1585224145Sdim      Entry.second = Lex.getLoc();
1586193323Sed    }
1587224145Sdim    Result = Entry.first;
1588193323Sed    Lex.Lex();
1589193323Sed    break;
1590224145Sdim  }
1591198090Srdivacky
1592224145Sdim  case lltok::LocalVarID: {
1593224145Sdim    // Type ::= %4
1594224145Sdim    if (Lex.getUIntVal() >= NumberedTypes.size())
1595224145Sdim      NumberedTypes.resize(Lex.getUIntVal()+1);
1596224145Sdim    std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1597249423Sdim
1598224145Sdim    // If the type hasn't been defined yet, create a forward definition and
1599224145Sdim    // remember where that forward def'n was seen (in case it never is defined).
1600224145Sdim    if (Entry.first == 0) {
1601226633Sdim      Entry.first = StructType::create(Context);
1602224145Sdim      Entry.second = Lex.getLoc();
1603193323Sed    }
1604224145Sdim    Result = Entry.first;
1605193323Sed    Lex.Lex();
1606193323Sed    break;
1607193323Sed  }
1608193323Sed  }
1609198090Srdivacky
1610198090Srdivacky  // Parse the type suffixes.
1611193323Sed  while (1) {
1612193323Sed    switch (Lex.getKind()) {
1613193323Sed    // End of type.
1614224145Sdim    default:
1615224145Sdim      if (!AllowVoid && Result->isVoidTy())
1616224145Sdim        return Error(TypeLoc, "void type only allowed for function results");
1617224145Sdim      return false;
1618193323Sed
1619224145Sdim    // Type ::= Type '*'
1620193323Sed    case lltok::star:
1621224145Sdim      if (Result->isLabelTy())
1622193323Sed        return TokError("basic block pointers are invalid");
1623224145Sdim      if (Result->isVoidTy())
1624224145Sdim        return TokError("pointers to void are invalid - use i8* instead");
1625224145Sdim      if (!PointerType::isValidElementType(Result))
1626193630Sed        return TokError("pointer to this type is invalid");
1627224145Sdim      Result = PointerType::getUnqual(Result);
1628193323Sed      Lex.Lex();
1629193323Sed      break;
1630193323Sed
1631224145Sdim    // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1632193323Sed    case lltok::kw_addrspace: {
1633224145Sdim      if (Result->isLabelTy())
1634193323Sed        return TokError("basic block pointers are invalid");
1635224145Sdim      if (Result->isVoidTy())
1636193323Sed        return TokError("pointers to void are invalid; use i8* instead");
1637224145Sdim      if (!PointerType::isValidElementType(Result))
1638193630Sed        return TokError("pointer to this type is invalid");
1639193323Sed      unsigned AddrSpace;
1640193323Sed      if (ParseOptionalAddrSpace(AddrSpace) ||
1641193323Sed          ParseToken(lltok::star, "expected '*' in address space"))
1642193323Sed        return true;
1643193323Sed
1644224145Sdim      Result = PointerType::get(Result, AddrSpace);
1645193323Sed      break;
1646193323Sed    }
1647198090Srdivacky
1648193323Sed    /// Types '(' ArgTypeListI ')' OptFuncAttrs
1649193323Sed    case lltok::lparen:
1650193323Sed      if (ParseFunctionType(Result))
1651193323Sed        return true;
1652193323Sed      break;
1653193323Sed    }
1654193323Sed  }
1655193323Sed}
1656193323Sed
1657193323Sed/// ParseParameterList
1658193323Sed///    ::= '(' ')'
1659193323Sed///    ::= '(' Arg (',' Arg)* ')'
1660193323Sed///  Arg
1661193323Sed///    ::= Type OptionalAttributes Value OptionalAttributes
1662193323Sedbool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1663193323Sed                                  PerFunctionState &PFS) {
1664193323Sed  if (ParseToken(lltok::lparen, "expected '(' in call"))
1665193323Sed    return true;
1666198090Srdivacky
1667249423Sdim  unsigned AttrIndex = 1;
1668193323Sed  while (Lex.getKind() != lltok::rparen) {
1669193323Sed    // If this isn't the first argument, we need a comma.
1670193323Sed    if (!ArgList.empty() &&
1671193323Sed        ParseToken(lltok::comma, "expected ',' in argument list"))
1672193323Sed      return true;
1673198090Srdivacky
1674193323Sed    // Parse the argument.
1675193323Sed    LocTy ArgLoc;
1676224145Sdim    Type *ArgTy = 0;
1677243830Sdim    AttrBuilder ArgAttrs;
1678193323Sed    Value *V;
1679200581Srdivacky    if (ParseType(ArgTy, ArgLoc))
1680193323Sed      return true;
1681200581Srdivacky
1682201360Srdivacky    // Otherwise, handle normal operands.
1683249423Sdim    if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1684201360Srdivacky      return true;
1685249423Sdim    ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1686249423Sdim                                                             AttrIndex++,
1687249423Sdim                                                             ArgAttrs)));
1688193323Sed  }
1689193323Sed
1690193323Sed  Lex.Lex();  // Lex the ')'.
1691193323Sed  return false;
1692193323Sed}
1693193323Sed
1694193323Sed
1695193323Sed
1696193323Sed/// ParseArgumentList - Parse the argument list for a function type or function
1697224145Sdim/// prototype.
1698193323Sed///   ::= '(' ArgTypeListI ')'
1699193323Sed/// ArgTypeListI
1700193323Sed///   ::= /*empty*/
1701193323Sed///   ::= '...'
1702193323Sed///   ::= ArgTypeList ',' '...'
1703193323Sed///   ::= ArgType (',' ArgType)*
1704193323Sed///
1705224145Sdimbool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1706224145Sdim                                 bool &isVarArg){
1707193323Sed  isVarArg = false;
1708193323Sed  assert(Lex.getKind() == lltok::lparen);
1709193323Sed  Lex.Lex(); // eat the (.
1710198090Srdivacky
1711193323Sed  if (Lex.getKind() == lltok::rparen) {
1712193323Sed    // empty
1713193323Sed  } else if (Lex.getKind() == lltok::dotdotdot) {
1714193323Sed    isVarArg = true;
1715193323Sed    Lex.Lex();
1716193323Sed  } else {
1717193323Sed    LocTy TypeLoc = Lex.getLoc();
1718224145Sdim    Type *ArgTy = 0;
1719243830Sdim    AttrBuilder Attrs;
1720193323Sed    std::string Name;
1721198090Srdivacky
1722224145Sdim    if (ParseType(ArgTy) ||
1723249423Sdim        ParseOptionalParamAttrs(Attrs)) return true;
1724198090Srdivacky
1725198090Srdivacky    if (ArgTy->isVoidTy())
1726193323Sed      return Error(TypeLoc, "argument can not have void type");
1727198090Srdivacky
1728224145Sdim    if (Lex.getKind() == lltok::LocalVar) {
1729193323Sed      Name = Lex.getStrVal();
1730193323Sed      Lex.Lex();
1731193323Sed    }
1732193323Sed
1733193630Sed    if (!FunctionType::isValidArgumentType(ArgTy))
1734193323Sed      return Error(TypeLoc, "invalid type for function argument");
1735198090Srdivacky
1736249423Sdim    unsigned AttrIndex = 1;
1737243830Sdim    ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1738249423Sdim                              AttributeSet::get(ArgTy->getContext(),
1739249423Sdim                                                AttrIndex++, Attrs), Name));
1740198090Srdivacky
1741193323Sed    while (EatIfPresent(lltok::comma)) {
1742193323Sed      // Handle ... at end of arg list.
1743193323Sed      if (EatIfPresent(lltok::dotdotdot)) {
1744193323Sed        isVarArg = true;
1745193323Sed        break;
1746193323Sed      }
1747198090Srdivacky
1748193323Sed      // Otherwise must be an argument type.
1749193323Sed      TypeLoc = Lex.getLoc();
1750249423Sdim      if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1751193323Sed
1752198090Srdivacky      if (ArgTy->isVoidTy())
1753193323Sed        return Error(TypeLoc, "argument can not have void type");
1754193323Sed
1755224145Sdim      if (Lex.getKind() == lltok::LocalVar) {
1756193323Sed        Name = Lex.getStrVal();
1757193323Sed        Lex.Lex();
1758193323Sed      } else {
1759193323Sed        Name = "";
1760193323Sed      }
1761193323Sed
1762224145Sdim      if (!ArgTy->isFirstClassType())
1763193323Sed        return Error(TypeLoc, "invalid type for function argument");
1764198090Srdivacky
1765243830Sdim      ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1766249423Sdim                                AttributeSet::get(ArgTy->getContext(),
1767249423Sdim                                                  AttrIndex++, Attrs),
1768243830Sdim                                Name));
1769193323Sed    }
1770193323Sed  }
1771198090Srdivacky
1772193323Sed  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1773193323Sed}
1774198090Srdivacky
1775193323Sed/// ParseFunctionType
1776193323Sed///  ::= Type ArgumentList OptionalAttrs
1777224145Sdimbool LLParser::ParseFunctionType(Type *&Result) {
1778193323Sed  assert(Lex.getKind() == lltok::lparen);
1779193323Sed
1780193323Sed  if (!FunctionType::isValidReturnType(Result))
1781193323Sed    return TokError("invalid function return type");
1782198090Srdivacky
1783224145Sdim  SmallVector<ArgInfo, 8> ArgList;
1784193323Sed  bool isVarArg;
1785224145Sdim  if (ParseArgumentList(ArgList, isVarArg))
1786193323Sed    return true;
1787198090Srdivacky
1788193323Sed  // Reject names on the arguments lists.
1789193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1790193323Sed    if (!ArgList[i].Name.empty())
1791193323Sed      return Error(ArgList[i].Loc, "argument name invalid in function type");
1792249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1))
1793224145Sdim      return Error(ArgList[i].Loc,
1794224145Sdim                   "argument attributes invalid in function type");
1795193323Sed  }
1796198090Srdivacky
1797224145Sdim  SmallVector<Type*, 16> ArgListTy;
1798193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1799224145Sdim    ArgListTy.push_back(ArgList[i].Ty);
1800198090Srdivacky
1801224145Sdim  Result = FunctionType::get(Result, ArgListTy, isVarArg);
1802193323Sed  return false;
1803193323Sed}
1804193323Sed
1805224145Sdim/// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1806224145Sdim/// other structs.
1807224145Sdimbool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1808224145Sdim  SmallVector<Type*, 8> Elts;
1809224145Sdim  if (ParseStructBody(Elts)) return true;
1810249423Sdim
1811224145Sdim  Result = StructType::get(Context, Elts, Packed);
1812224145Sdim  return false;
1813224145Sdim}
1814224145Sdim
1815224145Sdim/// ParseStructDefinition - Parse a struct in a 'type' definition.
1816224145Sdimbool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1817224145Sdim                                     std::pair<Type*, LocTy> &Entry,
1818224145Sdim                                     Type *&ResultTy) {
1819224145Sdim  // If the type was already defined, diagnose the redefinition.
1820224145Sdim  if (Entry.first && !Entry.second.isValid())
1821224145Sdim    return Error(TypeLoc, "redefinition of type");
1822249423Sdim
1823224145Sdim  // If we have opaque, just return without filling in the definition for the
1824224145Sdim  // struct.  This counts as a definition as far as the .ll file goes.
1825224145Sdim  if (EatIfPresent(lltok::kw_opaque)) {
1826224145Sdim    // This type is being defined, so clear the location to indicate this.
1827224145Sdim    Entry.second = SMLoc();
1828249423Sdim
1829224145Sdim    // If this type number has never been uttered, create it.
1830224145Sdim    if (Entry.first == 0)
1831226633Sdim      Entry.first = StructType::create(Context, Name);
1832224145Sdim    ResultTy = Entry.first;
1833224145Sdim    return false;
1834224145Sdim  }
1835249423Sdim
1836224145Sdim  // If the type starts with '<', then it is either a packed struct or a vector.
1837224145Sdim  bool isPacked = EatIfPresent(lltok::less);
1838224145Sdim
1839224145Sdim  // If we don't have a struct, then we have a random type alias, which we
1840224145Sdim  // accept for compatibility with old files.  These types are not allowed to be
1841224145Sdim  // forward referenced and not allowed to be recursive.
1842224145Sdim  if (Lex.getKind() != lltok::lbrace) {
1843224145Sdim    if (Entry.first)
1844224145Sdim      return Error(TypeLoc, "forward references to non-struct type");
1845249423Sdim
1846224145Sdim    ResultTy = 0;
1847224145Sdim    if (isPacked)
1848224145Sdim      return ParseArrayVectorType(ResultTy, true);
1849224145Sdim    return ParseType(ResultTy);
1850224145Sdim  }
1851249423Sdim
1852224145Sdim  // This type is being defined, so clear the location to indicate this.
1853224145Sdim  Entry.second = SMLoc();
1854249423Sdim
1855224145Sdim  // If this type number has never been uttered, create it.
1856224145Sdim  if (Entry.first == 0)
1857226633Sdim    Entry.first = StructType::create(Context, Name);
1858249423Sdim
1859224145Sdim  StructType *STy = cast<StructType>(Entry.first);
1860249423Sdim
1861224145Sdim  SmallVector<Type*, 8> Body;
1862224145Sdim  if (ParseStructBody(Body) ||
1863224145Sdim      (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1864224145Sdim    return true;
1865249423Sdim
1866224145Sdim  STy->setBody(Body, isPacked);
1867224145Sdim  ResultTy = STy;
1868224145Sdim  return false;
1869224145Sdim}
1870224145Sdim
1871224145Sdim
1872193323Sed/// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
1873224145Sdim///   StructType
1874193323Sed///     ::= '{' '}'
1875224145Sdim///     ::= '{' Type (',' Type)* '}'
1876193323Sed///     ::= '<' '{' '}' '>'
1877224145Sdim///     ::= '<' '{' Type (',' Type)* '}' '>'
1878224145Sdimbool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1879193323Sed  assert(Lex.getKind() == lltok::lbrace);
1880193323Sed  Lex.Lex(); // Consume the '{'
1881198090Srdivacky
1882224145Sdim  // Handle the empty struct.
1883224145Sdim  if (EatIfPresent(lltok::rbrace))
1884193323Sed    return false;
1885193323Sed
1886193323Sed  LocTy EltTyLoc = Lex.getLoc();
1887224145Sdim  Type *Ty = 0;
1888224145Sdim  if (ParseType(Ty)) return true;
1889224145Sdim  Body.push_back(Ty);
1890198090Srdivacky
1891224145Sdim  if (!StructType::isValidElementType(Ty))
1892193630Sed    return Error(EltTyLoc, "invalid element type for struct");
1893198090Srdivacky
1894193323Sed  while (EatIfPresent(lltok::comma)) {
1895193323Sed    EltTyLoc = Lex.getLoc();
1896224145Sdim    if (ParseType(Ty)) return true;
1897198090Srdivacky
1898224145Sdim    if (!StructType::isValidElementType(Ty))
1899193630Sed      return Error(EltTyLoc, "invalid element type for struct");
1900198090Srdivacky
1901224145Sdim    Body.push_back(Ty);
1902193323Sed  }
1903198090Srdivacky
1904224145Sdim  return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1905193323Sed}
1906193323Sed
1907193323Sed/// ParseArrayVectorType - Parse an array or vector type, assuming the first
1908193323Sed/// token has already been consumed.
1909224145Sdim///   Type
1910193323Sed///     ::= '[' APSINTVAL 'x' Types ']'
1911193323Sed///     ::= '<' APSINTVAL 'x' Types '>'
1912224145Sdimbool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1913193323Sed  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1914193323Sed      Lex.getAPSIntVal().getBitWidth() > 64)
1915193323Sed    return TokError("expected number in address space");
1916198090Srdivacky
1917193323Sed  LocTy SizeLoc = Lex.getLoc();
1918193323Sed  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1919193323Sed  Lex.Lex();
1920198090Srdivacky
1921193323Sed  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1922193323Sed      return true;
1923193323Sed
1924193323Sed  LocTy TypeLoc = Lex.getLoc();
1925224145Sdim  Type *EltTy = 0;
1926224145Sdim  if (ParseType(EltTy)) return true;
1927198090Srdivacky
1928193323Sed  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1929193323Sed                 "expected end of sequential type"))
1930193323Sed    return true;
1931198090Srdivacky
1932193323Sed  if (isVector) {
1933193323Sed    if (Size == 0)
1934193323Sed      return Error(SizeLoc, "zero element vector is illegal");
1935193323Sed    if ((unsigned)Size != Size)
1936193323Sed      return Error(SizeLoc, "size too large for vector");
1937193630Sed    if (!VectorType::isValidElementType(EltTy))
1938249423Sdim      return Error(TypeLoc, "invalid vector element type");
1939198090Srdivacky    Result = VectorType::get(EltTy, unsigned(Size));
1940193323Sed  } else {
1941193630Sed    if (!ArrayType::isValidElementType(EltTy))
1942193323Sed      return Error(TypeLoc, "invalid array element type");
1943224145Sdim    Result = ArrayType::get(EltTy, Size);
1944193323Sed  }
1945193323Sed  return false;
1946193323Sed}
1947193323Sed
1948193323Sed//===----------------------------------------------------------------------===//
1949193323Sed// Function Semantic Analysis.
1950193323Sed//===----------------------------------------------------------------------===//
1951193323Sed
1952198892SrdivackyLLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1953198892Srdivacky                                             int functionNumber)
1954198892Srdivacky  : P(p), F(f), FunctionNumber(functionNumber) {
1955193323Sed
1956193323Sed  // Insert unnamed arguments into the NumberedVals list.
1957193323Sed  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1958193323Sed       AI != E; ++AI)
1959193323Sed    if (!AI->hasName())
1960193323Sed      NumberedVals.push_back(AI);
1961193323Sed}
1962193323Sed
1963193323SedLLParser::PerFunctionState::~PerFunctionState() {
1964193323Sed  // If there were any forward referenced non-basicblock values, delete them.
1965193323Sed  for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1966193323Sed       I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1967193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1968195340Sed      I->second.first->replaceAllUsesWith(
1969198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1970193323Sed      delete I->second.first;
1971193323Sed      I->second.first = 0;
1972193323Sed    }
1973198090Srdivacky
1974193323Sed  for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1975193323Sed       I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1976193323Sed    if (!isa<BasicBlock>(I->second.first)) {
1977195340Sed      I->second.first->replaceAllUsesWith(
1978198090Srdivacky                           UndefValue::get(I->second.first->getType()));
1979193323Sed      delete I->second.first;
1980193323Sed      I->second.first = 0;
1981193323Sed    }
1982193323Sed}
1983193323Sed
1984198892Srdivackybool LLParser::PerFunctionState::FinishFunction() {
1985198892Srdivacky  // Check to see if someone took the address of labels in this block.
1986198892Srdivacky  if (!P.ForwardRefBlockAddresses.empty()) {
1987198892Srdivacky    ValID FunctionID;
1988198892Srdivacky    if (!F.getName().empty()) {
1989198892Srdivacky      FunctionID.Kind = ValID::t_GlobalName;
1990198892Srdivacky      FunctionID.StrVal = F.getName();
1991198892Srdivacky    } else {
1992198892Srdivacky      FunctionID.Kind = ValID::t_GlobalID;
1993198892Srdivacky      FunctionID.UIntVal = FunctionNumber;
1994198892Srdivacky    }
1995249423Sdim
1996198892Srdivacky    std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1997198892Srdivacky      FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1998198892Srdivacky    if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1999198892Srdivacky      // Resolve all these references.
2000198892Srdivacky      if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2001198892Srdivacky        return true;
2002249423Sdim
2003198892Srdivacky      P.ForwardRefBlockAddresses.erase(FRBAI);
2004198892Srdivacky    }
2005198892Srdivacky  }
2006249423Sdim
2007193323Sed  if (!ForwardRefVals.empty())
2008193323Sed    return P.Error(ForwardRefVals.begin()->second.second,
2009193323Sed                   "use of undefined value '%" + ForwardRefVals.begin()->first +
2010193323Sed                   "'");
2011193323Sed  if (!ForwardRefValIDs.empty())
2012193323Sed    return P.Error(ForwardRefValIDs.begin()->second.second,
2013193323Sed                   "use of undefined value '%" +
2014218893Sdim                   Twine(ForwardRefValIDs.begin()->first) + "'");
2015193323Sed  return false;
2016193323Sed}
2017193323Sed
2018193323Sed
2019193323Sed/// GetVal - Get a value with the specified name or ID, creating a
2020193323Sed/// forward reference record if needed.  This can return null if the value
2021193323Sed/// exists but does not have the right type.
2022193323SedValue *LLParser::PerFunctionState::GetVal(const std::string &Name,
2023226633Sdim                                          Type *Ty, LocTy Loc) {
2024193323Sed  // Look this name up in the normal function symbol table.
2025193323Sed  Value *Val = F.getValueSymbolTable().lookup(Name);
2026198090Srdivacky
2027193323Sed  // If this is a forward reference for the value, see if we already created a
2028193323Sed  // forward ref record.
2029193323Sed  if (Val == 0) {
2030193323Sed    std::map<std::string, std::pair<Value*, LocTy> >::iterator
2031193323Sed      I = ForwardRefVals.find(Name);
2032193323Sed    if (I != ForwardRefVals.end())
2033193323Sed      Val = I->second.first;
2034193323Sed  }
2035198090Srdivacky
2036193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
2037193323Sed  if (Val) {
2038193323Sed    if (Val->getType() == Ty) return Val;
2039198090Srdivacky    if (Ty->isLabelTy())
2040193323Sed      P.Error(Loc, "'%" + Name + "' is not a basic block");
2041193323Sed    else
2042193323Sed      P.Error(Loc, "'%" + Name + "' defined with type '" +
2043224145Sdim              getTypeString(Val->getType()) + "'");
2044193323Sed    return 0;
2045193323Sed  }
2046198090Srdivacky
2047193323Sed  // Don't make placeholders with invalid type.
2048224145Sdim  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2049193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
2050193323Sed    return 0;
2051193323Sed  }
2052198090Srdivacky
2053193323Sed  // Otherwise, create a new forward reference for this value and remember it.
2054193323Sed  Value *FwdVal;
2055198090Srdivacky  if (Ty->isLabelTy())
2056198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2057193323Sed  else
2058193323Sed    FwdVal = new Argument(Ty, Name);
2059198090Srdivacky
2060193323Sed  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2061193323Sed  return FwdVal;
2062193323Sed}
2063193323Sed
2064226633SdimValue *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2065193323Sed                                          LocTy Loc) {
2066193323Sed  // Look this name up in the normal function symbol table.
2067193323Sed  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2068198090Srdivacky
2069193323Sed  // If this is a forward reference for the value, see if we already created a
2070193323Sed  // forward ref record.
2071193323Sed  if (Val == 0) {
2072193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2073193323Sed      I = ForwardRefValIDs.find(ID);
2074193323Sed    if (I != ForwardRefValIDs.end())
2075193323Sed      Val = I->second.first;
2076193323Sed  }
2077198090Srdivacky
2078193323Sed  // If we have the value in the symbol table or fwd-ref table, return it.
2079193323Sed  if (Val) {
2080193323Sed    if (Val->getType() == Ty) return Val;
2081198090Srdivacky    if (Ty->isLabelTy())
2082218893Sdim      P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2083193323Sed    else
2084218893Sdim      P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2085224145Sdim              getTypeString(Val->getType()) + "'");
2086193323Sed    return 0;
2087193323Sed  }
2088198090Srdivacky
2089224145Sdim  if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2090193323Sed    P.Error(Loc, "invalid use of a non-first-class type");
2091193323Sed    return 0;
2092193323Sed  }
2093198090Srdivacky
2094193323Sed  // Otherwise, create a new forward reference for this value and remember it.
2095193323Sed  Value *FwdVal;
2096198090Srdivacky  if (Ty->isLabelTy())
2097198090Srdivacky    FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2098193323Sed  else
2099193323Sed    FwdVal = new Argument(Ty);
2100198090Srdivacky
2101193323Sed  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2102193323Sed  return FwdVal;
2103193323Sed}
2104193323Sed
2105193323Sed/// SetInstName - After an instruction is parsed and inserted into its
2106193323Sed/// basic block, this installs its name.
2107193323Sedbool LLParser::PerFunctionState::SetInstName(int NameID,
2108193323Sed                                             const std::string &NameStr,
2109193323Sed                                             LocTy NameLoc, Instruction *Inst) {
2110193323Sed  // If this instruction has void type, it cannot have a name or ID specified.
2111198090Srdivacky  if (Inst->getType()->isVoidTy()) {
2112193323Sed    if (NameID != -1 || !NameStr.empty())
2113193323Sed      return P.Error(NameLoc, "instructions returning void cannot have a name");
2114193323Sed    return false;
2115193323Sed  }
2116198090Srdivacky
2117193323Sed  // If this was a numbered instruction, verify that the instruction is the
2118193323Sed  // expected value and resolve any forward references.
2119193323Sed  if (NameStr.empty()) {
2120193323Sed    // If neither a name nor an ID was specified, just use the next ID.
2121193323Sed    if (NameID == -1)
2122193323Sed      NameID = NumberedVals.size();
2123198090Srdivacky
2124193323Sed    if (unsigned(NameID) != NumberedVals.size())
2125193323Sed      return P.Error(NameLoc, "instruction expected to be numbered '%" +
2126218893Sdim                     Twine(NumberedVals.size()) + "'");
2127198090Srdivacky
2128193323Sed    std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2129193323Sed      ForwardRefValIDs.find(NameID);
2130193323Sed    if (FI != ForwardRefValIDs.end()) {
2131193323Sed      if (FI->second.first->getType() != Inst->getType())
2132198090Srdivacky        return P.Error(NameLoc, "instruction forward referenced with type '" +
2133224145Sdim                       getTypeString(FI->second.first->getType()) + "'");
2134193323Sed      FI->second.first->replaceAllUsesWith(Inst);
2135198090Srdivacky      delete FI->second.first;
2136193323Sed      ForwardRefValIDs.erase(FI);
2137193323Sed    }
2138193323Sed
2139193323Sed    NumberedVals.push_back(Inst);
2140193323Sed    return false;
2141193323Sed  }
2142193323Sed
2143193323Sed  // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2144193323Sed  std::map<std::string, std::pair<Value*, LocTy> >::iterator
2145193323Sed    FI = ForwardRefVals.find(NameStr);
2146193323Sed  if (FI != ForwardRefVals.end()) {
2147193323Sed    if (FI->second.first->getType() != Inst->getType())
2148198090Srdivacky      return P.Error(NameLoc, "instruction forward referenced with type '" +
2149224145Sdim                     getTypeString(FI->second.first->getType()) + "'");
2150193323Sed    FI->second.first->replaceAllUsesWith(Inst);
2151198090Srdivacky    delete FI->second.first;
2152193323Sed    ForwardRefVals.erase(FI);
2153193323Sed  }
2154198090Srdivacky
2155193323Sed  // Set the name on the instruction.
2156193323Sed  Inst->setName(NameStr);
2157198090Srdivacky
2158218893Sdim  if (Inst->getName() != NameStr)
2159198090Srdivacky    return P.Error(NameLoc, "multiple definition of local value named '" +
2160193323Sed                   NameStr + "'");
2161193323Sed  return false;
2162193323Sed}
2163193323Sed
2164193323Sed/// GetBB - Get a basic block with the specified name or ID, creating a
2165193323Sed/// forward reference record if needed.
2166193323SedBasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2167193323Sed                                              LocTy Loc) {
2168198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(Name,
2169198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
2170193323Sed}
2171193323Sed
2172193323SedBasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2173198090Srdivacky  return cast_or_null<BasicBlock>(GetVal(ID,
2174198090Srdivacky                                        Type::getLabelTy(F.getContext()), Loc));
2175193323Sed}
2176193323Sed
2177193323Sed/// DefineBB - Define the specified basic block, which is either named or
2178193323Sed/// unnamed.  If there is an error, this returns null otherwise it returns
2179193323Sed/// the block being defined.
2180193323SedBasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2181193323Sed                                                 LocTy Loc) {
2182193323Sed  BasicBlock *BB;
2183193323Sed  if (Name.empty())
2184193323Sed    BB = GetBB(NumberedVals.size(), Loc);
2185193323Sed  else
2186193323Sed    BB = GetBB(Name, Loc);
2187193323Sed  if (BB == 0) return 0; // Already diagnosed error.
2188198090Srdivacky
2189193323Sed  // Move the block to the end of the function.  Forward ref'd blocks are
2190193323Sed  // inserted wherever they happen to be referenced.
2191193323Sed  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2192198090Srdivacky
2193193323Sed  // Remove the block from forward ref sets.
2194193323Sed  if (Name.empty()) {
2195193323Sed    ForwardRefValIDs.erase(NumberedVals.size());
2196193323Sed    NumberedVals.push_back(BB);
2197193323Sed  } else {
2198193323Sed    // BB forward references are already in the function symbol table.
2199193323Sed    ForwardRefVals.erase(Name);
2200193323Sed  }
2201198090Srdivacky
2202193323Sed  return BB;
2203193323Sed}
2204193323Sed
2205193323Sed//===----------------------------------------------------------------------===//
2206193323Sed// Constants.
2207193323Sed//===----------------------------------------------------------------------===//
2208193323Sed
2209193323Sed/// ParseValID - Parse an abstract value that doesn't necessarily have a
2210193323Sed/// type implied.  For example, if we parse "4" we don't know what integer type
2211193323Sed/// it has.  The value will later be combined with its type and checked for
2212202375Srdivacky/// sanity.  PFS is used to convert function-local operands of metadata (since
2213202375Srdivacky/// metadata operands are not just parsed here but also converted to values).
2214202375Srdivacky/// PFS can be null when we are not parsing metadata values inside a function.
2215202375Srdivackybool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2216193323Sed  ID.Loc = Lex.getLoc();
2217193323Sed  switch (Lex.getKind()) {
2218193323Sed  default: return TokError("expected value token");
2219193323Sed  case lltok::GlobalID:  // @42
2220193323Sed    ID.UIntVal = Lex.getUIntVal();
2221193323Sed    ID.Kind = ValID::t_GlobalID;
2222193323Sed    break;
2223193323Sed  case lltok::GlobalVar:  // @foo
2224193323Sed    ID.StrVal = Lex.getStrVal();
2225193323Sed    ID.Kind = ValID::t_GlobalName;
2226193323Sed    break;
2227193323Sed  case lltok::LocalVarID:  // %42
2228193323Sed    ID.UIntVal = Lex.getUIntVal();
2229193323Sed    ID.Kind = ValID::t_LocalID;
2230193323Sed    break;
2231193323Sed  case lltok::LocalVar:  // %foo
2232193323Sed    ID.StrVal = Lex.getStrVal();
2233193323Sed    ID.Kind = ValID::t_LocalName;
2234193323Sed    break;
2235210299Sed  case lltok::exclaim:   // !42, !{...}, or !"foo"
2236210299Sed    return ParseMetadataValue(ID, PFS);
2237193323Sed  case lltok::APSInt:
2238198090Srdivacky    ID.APSIntVal = Lex.getAPSIntVal();
2239193323Sed    ID.Kind = ValID::t_APSInt;
2240193323Sed    break;
2241193323Sed  case lltok::APFloat:
2242193323Sed    ID.APFloatVal = Lex.getAPFloatVal();
2243193323Sed    ID.Kind = ValID::t_APFloat;
2244193323Sed    break;
2245193323Sed  case lltok::kw_true:
2246198090Srdivacky    ID.ConstantVal = ConstantInt::getTrue(Context);
2247193323Sed    ID.Kind = ValID::t_Constant;
2248193323Sed    break;
2249193323Sed  case lltok::kw_false:
2250198090Srdivacky    ID.ConstantVal = ConstantInt::getFalse(Context);
2251193323Sed    ID.Kind = ValID::t_Constant;
2252193323Sed    break;
2253193323Sed  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2254193323Sed  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2255193323Sed  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2256198090Srdivacky
2257193323Sed  case lltok::lbrace: {
2258193323Sed    // ValID ::= '{' ConstVector '}'
2259193323Sed    Lex.Lex();
2260193323Sed    SmallVector<Constant*, 16> Elts;
2261193323Sed    if (ParseGlobalValueVector(Elts) ||
2262193323Sed        ParseToken(lltok::rbrace, "expected end of struct constant"))
2263193323Sed      return true;
2264198090Srdivacky
2265224145Sdim    ID.ConstantStructElts = new Constant*[Elts.size()];
2266224145Sdim    ID.UIntVal = Elts.size();
2267224145Sdim    memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2268224145Sdim    ID.Kind = ValID::t_ConstantStruct;
2269193323Sed    return false;
2270193323Sed  }
2271193323Sed  case lltok::less: {
2272193323Sed    // ValID ::= '<' ConstVector '>'         --> Vector.
2273193323Sed    // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2274193323Sed    Lex.Lex();
2275193323Sed    bool isPackedStruct = EatIfPresent(lltok::lbrace);
2276198090Srdivacky
2277193323Sed    SmallVector<Constant*, 16> Elts;
2278193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2279193323Sed    if (ParseGlobalValueVector(Elts) ||
2280193323Sed        (isPackedStruct &&
2281193323Sed         ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2282193323Sed        ParseToken(lltok::greater, "expected end of constant"))
2283193323Sed      return true;
2284198090Srdivacky
2285193323Sed    if (isPackedStruct) {
2286224145Sdim      ID.ConstantStructElts = new Constant*[Elts.size()];
2287224145Sdim      memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2288224145Sdim      ID.UIntVal = Elts.size();
2289224145Sdim      ID.Kind = ValID::t_PackedConstantStruct;
2290193323Sed      return false;
2291193323Sed    }
2292198090Srdivacky
2293193323Sed    if (Elts.empty())
2294193323Sed      return Error(ID.Loc, "constant vector must not be empty");
2295193323Sed
2296203954Srdivacky    if (!Elts[0]->getType()->isIntegerTy() &&
2297234353Sdim        !Elts[0]->getType()->isFloatingPointTy() &&
2298234353Sdim        !Elts[0]->getType()->isPointerTy())
2299193323Sed      return Error(FirstEltLoc,
2300234353Sdim            "vector elements must have integer, pointer or floating point type");
2301198090Srdivacky
2302193323Sed    // Verify that all the vector elements have the same type.
2303193323Sed    for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2304193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2305193323Sed        return Error(FirstEltLoc,
2306218893Sdim                     "vector element #" + Twine(i) +
2307224145Sdim                    " is not of type '" + getTypeString(Elts[0]->getType()));
2308198090Srdivacky
2309218893Sdim    ID.ConstantVal = ConstantVector::get(Elts);
2310193323Sed    ID.Kind = ValID::t_Constant;
2311193323Sed    return false;
2312193323Sed  }
2313193323Sed  case lltok::lsquare: {   // Array Constant
2314193323Sed    Lex.Lex();
2315193323Sed    SmallVector<Constant*, 16> Elts;
2316193323Sed    LocTy FirstEltLoc = Lex.getLoc();
2317193323Sed    if (ParseGlobalValueVector(Elts) ||
2318193323Sed        ParseToken(lltok::rsquare, "expected end of array constant"))
2319193323Sed      return true;
2320193323Sed
2321193323Sed    // Handle empty element.
2322193323Sed    if (Elts.empty()) {
2323193323Sed      // Use undef instead of an array because it's inconvenient to determine
2324193323Sed      // the element type at this point, there being no elements to examine.
2325193323Sed      ID.Kind = ValID::t_EmptyArray;
2326193323Sed      return false;
2327193323Sed    }
2328198090Srdivacky
2329193323Sed    if (!Elts[0]->getType()->isFirstClassType())
2330198090Srdivacky      return Error(FirstEltLoc, "invalid array element type: " +
2331224145Sdim                   getTypeString(Elts[0]->getType()));
2332198090Srdivacky
2333198090Srdivacky    ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2334198090Srdivacky
2335193323Sed    // Verify all elements are correct type!
2336193323Sed    for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2337193323Sed      if (Elts[i]->getType() != Elts[0]->getType())
2338193323Sed        return Error(FirstEltLoc,
2339218893Sdim                     "array element #" + Twine(i) +
2340224145Sdim                     " is not of type '" + getTypeString(Elts[0]->getType()));
2341193323Sed    }
2342198090Srdivacky
2343224145Sdim    ID.ConstantVal = ConstantArray::get(ATy, Elts);
2344193323Sed    ID.Kind = ValID::t_Constant;
2345193323Sed    return false;
2346193323Sed  }
2347193323Sed  case lltok::kw_c:  // c "foo"
2348193323Sed    Lex.Lex();
2349234353Sdim    ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2350234353Sdim                                                  false);
2351193323Sed    if (ParseToken(lltok::StringConstant, "expected string")) return true;
2352193323Sed    ID.Kind = ValID::t_Constant;
2353193323Sed    return false;
2354193323Sed
2355193323Sed  case lltok::kw_asm: {
2356249423Sdim    // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2357249423Sdim    //             STRINGCONSTANT
2358243830Sdim    bool HasSideEffect, AlignStack, AsmDialect;
2359193323Sed    Lex.Lex();
2360193323Sed    if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2361198396Srdivacky        ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2362243830Sdim        ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2363193323Sed        ParseStringConstant(ID.StrVal) ||
2364193323Sed        ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2365193323Sed        ParseToken(lltok::StringConstant, "expected constraint string"))
2366193323Sed      return true;
2367193323Sed    ID.StrVal2 = Lex.getStrVal();
2368243830Sdim    ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2369243830Sdim      (unsigned(AsmDialect)<<2);
2370193323Sed    ID.Kind = ValID::t_InlineAsm;
2371193323Sed    return false;
2372193323Sed  }
2373198090Srdivacky
2374198892Srdivacky  case lltok::kw_blockaddress: {
2375198892Srdivacky    // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2376198892Srdivacky    Lex.Lex();
2377198892Srdivacky
2378198892Srdivacky    ValID Fn, Label;
2379198892Srdivacky    LocTy FnLoc, LabelLoc;
2380249423Sdim
2381198892Srdivacky    if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2382198892Srdivacky        ParseValID(Fn) ||
2383198892Srdivacky        ParseToken(lltok::comma, "expected comma in block address expression")||
2384198892Srdivacky        ParseValID(Label) ||
2385198892Srdivacky        ParseToken(lltok::rparen, "expected ')' in block address expression"))
2386198892Srdivacky      return true;
2387249423Sdim
2388198892Srdivacky    if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2389198892Srdivacky      return Error(Fn.Loc, "expected function name in blockaddress");
2390198892Srdivacky    if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2391198892Srdivacky      return Error(Label.Loc, "expected basic block name in blockaddress");
2392249423Sdim
2393198892Srdivacky    // Make a global variable as a placeholder for this reference.
2394198892Srdivacky    GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2395198892Srdivacky                                           false, GlobalValue::InternalLinkage,
2396198892Srdivacky                                                0, "");
2397198892Srdivacky    ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2398198892Srdivacky    ID.ConstantVal = FwdRef;
2399198892Srdivacky    ID.Kind = ValID::t_Constant;
2400198892Srdivacky    return false;
2401198892Srdivacky  }
2402249423Sdim
2403193323Sed  case lltok::kw_trunc:
2404193323Sed  case lltok::kw_zext:
2405193323Sed  case lltok::kw_sext:
2406193323Sed  case lltok::kw_fptrunc:
2407193323Sed  case lltok::kw_fpext:
2408193323Sed  case lltok::kw_bitcast:
2409193323Sed  case lltok::kw_uitofp:
2410193323Sed  case lltok::kw_sitofp:
2411193323Sed  case lltok::kw_fptoui:
2412198090Srdivacky  case lltok::kw_fptosi:
2413193323Sed  case lltok::kw_inttoptr:
2414198090Srdivacky  case lltok::kw_ptrtoint: {
2415193323Sed    unsigned Opc = Lex.getUIntVal();
2416224145Sdim    Type *DestTy = 0;
2417193323Sed    Constant *SrcVal;
2418193323Sed    Lex.Lex();
2419193323Sed    if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2420193323Sed        ParseGlobalTypeAndValue(SrcVal) ||
2421194612Sed        ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2422193323Sed        ParseType(DestTy) ||
2423193323Sed        ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2424193323Sed      return true;
2425193323Sed    if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2426193323Sed      return Error(ID.Loc, "invalid cast opcode for cast from '" +
2427224145Sdim                   getTypeString(SrcVal->getType()) + "' to '" +
2428224145Sdim                   getTypeString(DestTy) + "'");
2429198090Srdivacky    ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2430195340Sed                                                 SrcVal, DestTy);
2431193323Sed    ID.Kind = ValID::t_Constant;
2432193323Sed    return false;
2433193323Sed  }
2434193323Sed  case lltok::kw_extractvalue: {
2435193323Sed    Lex.Lex();
2436193323Sed    Constant *Val;
2437193323Sed    SmallVector<unsigned, 4> Indices;
2438193323Sed    if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2439193323Sed        ParseGlobalTypeAndValue(Val) ||
2440193323Sed        ParseIndexList(Indices) ||
2441193323Sed        ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2442193323Sed      return true;
2443198892Srdivacky
2444203954Srdivacky    if (!Val->getType()->isAggregateType())
2445203954Srdivacky      return Error(ID.Loc, "extractvalue operand must be aggregate type");
2446224145Sdim    if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2447193323Sed      return Error(ID.Loc, "invalid indices for extractvalue");
2448224145Sdim    ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2449193323Sed    ID.Kind = ValID::t_Constant;
2450193323Sed    return false;
2451193323Sed  }
2452193323Sed  case lltok::kw_insertvalue: {
2453193323Sed    Lex.Lex();
2454193323Sed    Constant *Val0, *Val1;
2455193323Sed    SmallVector<unsigned, 4> Indices;
2456193323Sed    if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2457193323Sed        ParseGlobalTypeAndValue(Val0) ||
2458193323Sed        ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2459193323Sed        ParseGlobalTypeAndValue(Val1) ||
2460193323Sed        ParseIndexList(Indices) ||
2461193323Sed        ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2462193323Sed      return true;
2463203954Srdivacky    if (!Val0->getType()->isAggregateType())
2464203954Srdivacky      return Error(ID.Loc, "insertvalue operand must be aggregate type");
2465224145Sdim    if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2466193323Sed      return Error(ID.Loc, "invalid indices for insertvalue");
2467224145Sdim    ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2468193323Sed    ID.Kind = ValID::t_Constant;
2469193323Sed    return false;
2470193323Sed  }
2471193323Sed  case lltok::kw_icmp:
2472198090Srdivacky  case lltok::kw_fcmp: {
2473193323Sed    unsigned PredVal, Opc = Lex.getUIntVal();
2474193323Sed    Constant *Val0, *Val1;
2475193323Sed    Lex.Lex();
2476193323Sed    if (ParseCmpPredicate(PredVal, Opc) ||
2477193323Sed        ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2478193323Sed        ParseGlobalTypeAndValue(Val0) ||
2479193323Sed        ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2480193323Sed        ParseGlobalTypeAndValue(Val1) ||
2481193323Sed        ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2482193323Sed      return true;
2483198090Srdivacky
2484193323Sed    if (Val0->getType() != Val1->getType())
2485193323Sed      return Error(ID.Loc, "compare operands must have the same type");
2486198090Srdivacky
2487193323Sed    CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2488198090Srdivacky
2489193323Sed    if (Opc == Instruction::FCmp) {
2490203954Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2491193323Sed        return Error(ID.Loc, "fcmp requires floating point operands");
2492198090Srdivacky      ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2493198090Srdivacky    } else {
2494198090Srdivacky      assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2495203954Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy() &&
2496234353Sdim          !Val0->getType()->getScalarType()->isPointerTy())
2497193323Sed        return Error(ID.Loc, "icmp requires pointer or integer operands");
2498198090Srdivacky      ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2499193323Sed    }
2500193323Sed    ID.Kind = ValID::t_Constant;
2501193323Sed    return false;
2502193323Sed  }
2503198090Srdivacky
2504193323Sed  // Binary Operators.
2505193323Sed  case lltok::kw_add:
2506193574Sed  case lltok::kw_fadd:
2507193323Sed  case lltok::kw_sub:
2508193574Sed  case lltok::kw_fsub:
2509193323Sed  case lltok::kw_mul:
2510193574Sed  case lltok::kw_fmul:
2511193323Sed  case lltok::kw_udiv:
2512193323Sed  case lltok::kw_sdiv:
2513193323Sed  case lltok::kw_fdiv:
2514193323Sed  case lltok::kw_urem:
2515193323Sed  case lltok::kw_srem:
2516218893Sdim  case lltok::kw_frem:
2517218893Sdim  case lltok::kw_shl:
2518218893Sdim  case lltok::kw_lshr:
2519218893Sdim  case lltok::kw_ashr: {
2520198090Srdivacky    bool NUW = false;
2521198090Srdivacky    bool NSW = false;
2522198090Srdivacky    bool Exact = false;
2523193323Sed    unsigned Opc = Lex.getUIntVal();
2524193323Sed    Constant *Val0, *Val1;
2525193323Sed    Lex.Lex();
2526198090Srdivacky    LocTy ModifierLoc = Lex.getLoc();
2527218893Sdim    if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2528218893Sdim        Opc == Instruction::Mul || Opc == Instruction::Shl) {
2529198090Srdivacky      if (EatIfPresent(lltok::kw_nuw))
2530198090Srdivacky        NUW = true;
2531198090Srdivacky      if (EatIfPresent(lltok::kw_nsw)) {
2532198090Srdivacky        NSW = true;
2533198090Srdivacky        if (EatIfPresent(lltok::kw_nuw))
2534198090Srdivacky          NUW = true;
2535198090Srdivacky      }
2536218893Sdim    } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2537218893Sdim               Opc == Instruction::LShr || Opc == Instruction::AShr) {
2538198090Srdivacky      if (EatIfPresent(lltok::kw_exact))
2539198090Srdivacky        Exact = true;
2540198090Srdivacky    }
2541193323Sed    if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2542193323Sed        ParseGlobalTypeAndValue(Val0) ||
2543193323Sed        ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2544193323Sed        ParseGlobalTypeAndValue(Val1) ||
2545193323Sed        ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2546193323Sed      return true;
2547193323Sed    if (Val0->getType() != Val1->getType())
2548193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2549203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy()) {
2550198090Srdivacky      if (NUW)
2551198090Srdivacky        return Error(ModifierLoc, "nuw only applies to integer operations");
2552198090Srdivacky      if (NSW)
2553198090Srdivacky        return Error(ModifierLoc, "nsw only applies to integer operations");
2554198090Srdivacky    }
2555207618Srdivacky    // Check that the type is valid for the operator.
2556207618Srdivacky    switch (Opc) {
2557207618Srdivacky    case Instruction::Add:
2558207618Srdivacky    case Instruction::Sub:
2559207618Srdivacky    case Instruction::Mul:
2560207618Srdivacky    case Instruction::UDiv:
2561207618Srdivacky    case Instruction::SDiv:
2562207618Srdivacky    case Instruction::URem:
2563207618Srdivacky    case Instruction::SRem:
2564218893Sdim    case Instruction::Shl:
2565218893Sdim    case Instruction::AShr:
2566218893Sdim    case Instruction::LShr:
2567207618Srdivacky      if (!Val0->getType()->isIntOrIntVectorTy())
2568207618Srdivacky        return Error(ID.Loc, "constexpr requires integer operands");
2569207618Srdivacky      break;
2570207618Srdivacky    case Instruction::FAdd:
2571207618Srdivacky    case Instruction::FSub:
2572207618Srdivacky    case Instruction::FMul:
2573207618Srdivacky    case Instruction::FDiv:
2574207618Srdivacky    case Instruction::FRem:
2575207618Srdivacky      if (!Val0->getType()->isFPOrFPVectorTy())
2576207618Srdivacky        return Error(ID.Loc, "constexpr requires fp operands");
2577207618Srdivacky      break;
2578207618Srdivacky    default: llvm_unreachable("Unknown binary operator!");
2579207618Srdivacky    }
2580198090Srdivacky    unsigned Flags = 0;
2581198090Srdivacky    if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2582198090Srdivacky    if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2583218893Sdim    if (Exact) Flags |= PossiblyExactOperator::IsExact;
2584198090Srdivacky    Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2585198090Srdivacky    ID.ConstantVal = C;
2586193323Sed    ID.Kind = ValID::t_Constant;
2587193323Sed    return false;
2588193323Sed  }
2589198090Srdivacky
2590193323Sed  // Logical Operations
2591193323Sed  case lltok::kw_and:
2592193323Sed  case lltok::kw_or:
2593193323Sed  case lltok::kw_xor: {
2594193323Sed    unsigned Opc = Lex.getUIntVal();
2595193323Sed    Constant *Val0, *Val1;
2596193323Sed    Lex.Lex();
2597193323Sed    if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2598193323Sed        ParseGlobalTypeAndValue(Val0) ||
2599193323Sed        ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2600193323Sed        ParseGlobalTypeAndValue(Val1) ||
2601193323Sed        ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2602193323Sed      return true;
2603193323Sed    if (Val0->getType() != Val1->getType())
2604193323Sed      return Error(ID.Loc, "operands of constexpr must have same type");
2605203954Srdivacky    if (!Val0->getType()->isIntOrIntVectorTy())
2606193323Sed      return Error(ID.Loc,
2607193323Sed                   "constexpr requires integer or integer vector operands");
2608198090Srdivacky    ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2609193323Sed    ID.Kind = ValID::t_Constant;
2610193323Sed    return false;
2611198090Srdivacky  }
2612198090Srdivacky
2613193323Sed  case lltok::kw_getelementptr:
2614193323Sed  case lltok::kw_shufflevector:
2615193323Sed  case lltok::kw_insertelement:
2616193323Sed  case lltok::kw_extractelement:
2617193323Sed  case lltok::kw_select: {
2618193323Sed    unsigned Opc = Lex.getUIntVal();
2619193323Sed    SmallVector<Constant*, 16> Elts;
2620198090Srdivacky    bool InBounds = false;
2621193323Sed    Lex.Lex();
2622198090Srdivacky    if (Opc == Instruction::GetElementPtr)
2623198090Srdivacky      InBounds = EatIfPresent(lltok::kw_inbounds);
2624193323Sed    if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2625193323Sed        ParseGlobalValueVector(Elts) ||
2626193323Sed        ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2627193323Sed      return true;
2628198090Srdivacky
2629193323Sed    if (Opc == Instruction::GetElementPtr) {
2630234353Sdim      if (Elts.size() == 0 ||
2631234353Sdim          !Elts[0]->getType()->getScalarType()->isPointerTy())
2632193323Sed        return Error(ID.Loc, "getelementptr requires pointer operand");
2633198090Srdivacky
2634226633Sdim      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2635226633Sdim      if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2636193323Sed        return Error(ID.Loc, "invalid indices for getelementptr");
2637226633Sdim      ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2638226633Sdim                                                      InBounds);
2639193323Sed    } else if (Opc == Instruction::Select) {
2640193323Sed      if (Elts.size() != 3)
2641193323Sed        return Error(ID.Loc, "expected three operands to select");
2642193323Sed      if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2643193323Sed                                                              Elts[2]))
2644193323Sed        return Error(ID.Loc, Reason);
2645198090Srdivacky      ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2646193323Sed    } else if (Opc == Instruction::ShuffleVector) {
2647193323Sed      if (Elts.size() != 3)
2648193323Sed        return Error(ID.Loc, "expected three operands to shufflevector");
2649193323Sed      if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2650193323Sed        return Error(ID.Loc, "invalid operands to shufflevector");
2651195340Sed      ID.ConstantVal =
2652198090Srdivacky                 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2653193323Sed    } else if (Opc == Instruction::ExtractElement) {
2654193323Sed      if (Elts.size() != 2)
2655193323Sed        return Error(ID.Loc, "expected two operands to extractelement");
2656193323Sed      if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2657193323Sed        return Error(ID.Loc, "invalid extractelement operands");
2658198090Srdivacky      ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2659193323Sed    } else {
2660193323Sed      assert(Opc == Instruction::InsertElement && "Unknown opcode");
2661193323Sed      if (Elts.size() != 3)
2662193323Sed      return Error(ID.Loc, "expected three operands to insertelement");
2663193323Sed      if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2664193323Sed        return Error(ID.Loc, "invalid insertelement operands");
2665195340Sed      ID.ConstantVal =
2666198090Srdivacky                 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2667193323Sed    }
2668198090Srdivacky
2669193323Sed    ID.Kind = ValID::t_Constant;
2670193323Sed    return false;
2671193323Sed  }
2672193323Sed  }
2673198090Srdivacky
2674193323Sed  Lex.Lex();
2675193323Sed  return false;
2676193323Sed}
2677193323Sed
2678193323Sed/// ParseGlobalValue - Parse a global value with the specified type.
2679226633Sdimbool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2680202375Srdivacky  C = 0;
2681193323Sed  ValID ID;
2682202375Srdivacky  Value *V = NULL;
2683202375Srdivacky  bool Parsed = ParseValID(ID) ||
2684202375Srdivacky                ConvertValIDToValue(Ty, ID, V, NULL);
2685202375Srdivacky  if (V && !(C = dyn_cast<Constant>(V)))
2686202375Srdivacky    return Error(ID.Loc, "global values must be constants");
2687202375Srdivacky  return Parsed;
2688193323Sed}
2689193323Sed
2690202375Srdivackybool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2691224145Sdim  Type *Ty = 0;
2692224145Sdim  return ParseType(Ty) ||
2693224145Sdim         ParseGlobalValue(Ty, V);
2694202375Srdivacky}
2695202375Srdivacky
2696202375Srdivacky/// ParseGlobalValueVector
2697202375Srdivacky///   ::= /*empty*/
2698202375Srdivacky///   ::= TypeAndValue (',' TypeAndValue)*
2699202375Srdivackybool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2700202375Srdivacky  // Empty list.
2701202375Srdivacky  if (Lex.getKind() == lltok::rbrace ||
2702202375Srdivacky      Lex.getKind() == lltok::rsquare ||
2703202375Srdivacky      Lex.getKind() == lltok::greater ||
2704202375Srdivacky      Lex.getKind() == lltok::rparen)
2705202375Srdivacky    return false;
2706202375Srdivacky
2707202375Srdivacky  Constant *C;
2708202375Srdivacky  if (ParseGlobalTypeAndValue(C)) return true;
2709202375Srdivacky  Elts.push_back(C);
2710202375Srdivacky
2711202375Srdivacky  while (EatIfPresent(lltok::comma)) {
2712202375Srdivacky    if (ParseGlobalTypeAndValue(C)) return true;
2713202375Srdivacky    Elts.push_back(C);
2714202375Srdivacky  }
2715202375Srdivacky
2716202375Srdivacky  return false;
2717202375Srdivacky}
2718202375Srdivacky
2719212904Sdimbool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2720212904Sdim  assert(Lex.getKind() == lltok::lbrace);
2721212904Sdim  Lex.Lex();
2722212904Sdim
2723212904Sdim  SmallVector<Value*, 16> Elts;
2724212904Sdim  if (ParseMDNodeVector(Elts, PFS) ||
2725212904Sdim      ParseToken(lltok::rbrace, "expected end of metadata node"))
2726212904Sdim    return true;
2727212904Sdim
2728221345Sdim  ID.MDNodeVal = MDNode::get(Context, Elts);
2729212904Sdim  ID.Kind = ValID::t_MDNode;
2730212904Sdim  return false;
2731212904Sdim}
2732212904Sdim
2733210299Sed/// ParseMetadataValue
2734210299Sed///  ::= !42
2735210299Sed///  ::= !{...}
2736210299Sed///  ::= !"string"
2737210299Sedbool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2738210299Sed  assert(Lex.getKind() == lltok::exclaim);
2739210299Sed  Lex.Lex();
2740202375Srdivacky
2741210299Sed  // MDNode:
2742210299Sed  // !{ ... }
2743212904Sdim  if (Lex.getKind() == lltok::lbrace)
2744212904Sdim    return ParseMetadataListValue(ID, PFS);
2745210299Sed
2746210299Sed  // Standalone metadata reference
2747210299Sed  // !42
2748210299Sed  if (Lex.getKind() == lltok::APSInt) {
2749210299Sed    if (ParseMDNodeID(ID.MDNodeVal)) return true;
2750210299Sed    ID.Kind = ValID::t_MDNode;
2751210299Sed    return false;
2752210299Sed  }
2753210299Sed
2754210299Sed  // MDString:
2755210299Sed  //   ::= '!' STRINGCONSTANT
2756210299Sed  if (ParseMDString(ID.MDStringVal)) return true;
2757210299Sed  ID.Kind = ValID::t_MDString;
2758210299Sed  return false;
2759210299Sed}
2760210299Sed
2761210299Sed
2762202375Srdivacky//===----------------------------------------------------------------------===//
2763202375Srdivacky// Function Parsing.
2764202375Srdivacky//===----------------------------------------------------------------------===//
2765202375Srdivacky
2766226633Sdimbool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2767202375Srdivacky                                   PerFunctionState *PFS) {
2768204642Srdivacky  if (Ty->isFunctionTy())
2769193323Sed    return Error(ID.Loc, "functions are not values, refer to them as pointers");
2770198090Srdivacky
2771193323Sed  switch (ID.Kind) {
2772202375Srdivacky  case ValID::t_LocalID:
2773202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2774202375Srdivacky    V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2775202375Srdivacky    return (V == 0);
2776202375Srdivacky  case ValID::t_LocalName:
2777202375Srdivacky    if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2778202375Srdivacky    V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2779202375Srdivacky    return (V == 0);
2780202375Srdivacky  case ValID::t_InlineAsm: {
2781226633Sdim    PointerType *PTy = dyn_cast<PointerType>(Ty);
2782249423Sdim    FunctionType *FTy =
2783202375Srdivacky      PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2784202375Srdivacky    if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2785202375Srdivacky      return Error(ID.Loc, "invalid type for inline asm constraint string");
2786243830Sdim    V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2787243830Sdim                       (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2788202375Srdivacky    return false;
2789202375Srdivacky  }
2790201360Srdivacky  case ValID::t_MDNode:
2791202375Srdivacky    if (!Ty->isMetadataTy())
2792202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2793202375Srdivacky    V = ID.MDNodeVal;
2794202375Srdivacky    return false;
2795201360Srdivacky  case ValID::t_MDString:
2796202375Srdivacky    if (!Ty->isMetadataTy())
2797202375Srdivacky      return Error(ID.Loc, "metadata value must have metadata type");
2798202375Srdivacky    V = ID.MDStringVal;
2799202375Srdivacky    return false;
2800193323Sed  case ValID::t_GlobalName:
2801193323Sed    V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2802193323Sed    return V == 0;
2803193323Sed  case ValID::t_GlobalID:
2804193323Sed    V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2805193323Sed    return V == 0;
2806193323Sed  case ValID::t_APSInt:
2807204642Srdivacky    if (!Ty->isIntegerTy())
2808193323Sed      return Error(ID.Loc, "integer constant must have integer type");
2809218893Sdim    ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2810198090Srdivacky    V = ConstantInt::get(Context, ID.APSIntVal);
2811193323Sed    return false;
2812193323Sed  case ValID::t_APFloat:
2813203954Srdivacky    if (!Ty->isFloatingPointTy() ||
2814193323Sed        !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2815193323Sed      return Error(ID.Loc, "floating point constant invalid for type");
2816198090Srdivacky
2817234353Sdim    // The lexer has no type info, so builds all half, float, and double FP
2818234353Sdim    // constants as double.  Fix this here.  Long double does not need this.
2819234353Sdim    if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2820193323Sed      bool Ignored;
2821234353Sdim      if (Ty->isHalfTy())
2822234353Sdim        ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2823234353Sdim                              &Ignored);
2824234353Sdim      else if (Ty->isFloatTy())
2825234353Sdim        ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2826234353Sdim                              &Ignored);
2827193323Sed    }
2828198090Srdivacky    V = ConstantFP::get(Context, ID.APFloatVal);
2829198090Srdivacky
2830193323Sed    if (V->getType() != Ty)
2831193323Sed      return Error(ID.Loc, "floating point constant does not have type '" +
2832224145Sdim                   getTypeString(Ty) + "'");
2833198090Srdivacky
2834193323Sed    return false;
2835193323Sed  case ValID::t_Null:
2836204642Srdivacky    if (!Ty->isPointerTy())
2837193323Sed      return Error(ID.Loc, "null must be a pointer type");
2838198090Srdivacky    V = ConstantPointerNull::get(cast<PointerType>(Ty));
2839193323Sed    return false;
2840193323Sed  case ValID::t_Undef:
2841193323Sed    // FIXME: LabelTy should not be a first-class type.
2842224145Sdim    if (!Ty->isFirstClassType() || Ty->isLabelTy())
2843193323Sed      return Error(ID.Loc, "invalid type for undef constant");
2844198090Srdivacky    V = UndefValue::get(Ty);
2845193323Sed    return false;
2846193323Sed  case ValID::t_EmptyArray:
2847204642Srdivacky    if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2848193323Sed      return Error(ID.Loc, "invalid empty array initializer");
2849198090Srdivacky    V = UndefValue::get(Ty);
2850193323Sed    return false;
2851193323Sed  case ValID::t_Zero:
2852193323Sed    // FIXME: LabelTy should not be a first-class type.
2853198090Srdivacky    if (!Ty->isFirstClassType() || Ty->isLabelTy())
2854193323Sed      return Error(ID.Loc, "invalid type for null constant");
2855198090Srdivacky    V = Constant::getNullValue(Ty);
2856193323Sed    return false;
2857193323Sed  case ValID::t_Constant:
2858212904Sdim    if (ID.ConstantVal->getType() != Ty)
2859193323Sed      return Error(ID.Loc, "constant expression type mismatch");
2860203954Srdivacky
2861193323Sed    V = ID.ConstantVal;
2862193323Sed    return false;
2863224145Sdim  case ValID::t_ConstantStruct:
2864224145Sdim  case ValID::t_PackedConstantStruct:
2865226633Sdim    if (StructType *ST = dyn_cast<StructType>(Ty)) {
2866224145Sdim      if (ST->getNumElements() != ID.UIntVal)
2867224145Sdim        return Error(ID.Loc,
2868224145Sdim                     "initializer with struct type has wrong # elements");
2869224145Sdim      if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2870224145Sdim        return Error(ID.Loc, "packed'ness of initializer and type don't match");
2871249423Sdim
2872224145Sdim      // Verify that the elements are compatible with the structtype.
2873224145Sdim      for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2874224145Sdim        if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2875224145Sdim          return Error(ID.Loc, "element " + Twine(i) +
2876224145Sdim                    " of struct initializer doesn't match struct element type");
2877249423Sdim
2878226633Sdim      V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2879226633Sdim                                               ID.UIntVal));
2880224145Sdim    } else
2881224145Sdim      return Error(ID.Loc, "constant expression type mismatch");
2882224145Sdim    return false;
2883193323Sed  }
2884234353Sdim  llvm_unreachable("Invalid ValID");
2885193323Sed}
2886198090Srdivacky
2887226633Sdimbool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2888193323Sed  V = 0;
2889193323Sed  ValID ID;
2890224145Sdim  return ParseValID(ID, PFS) ||
2891224145Sdim         ConvertValIDToValue(Ty, ID, V, PFS);
2892193323Sed}
2893193323Sed
2894224145Sdimbool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2895224145Sdim  Type *Ty = 0;
2896224145Sdim  return ParseType(Ty) ||
2897224145Sdim         ParseValue(Ty, V, PFS);
2898193323Sed}
2899193323Sed
2900198892Srdivackybool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2901198892Srdivacky                                      PerFunctionState &PFS) {
2902198892Srdivacky  Value *V;
2903198892Srdivacky  Loc = Lex.getLoc();
2904198892Srdivacky  if (ParseTypeAndValue(V, PFS)) return true;
2905198892Srdivacky  if (!isa<BasicBlock>(V))
2906198892Srdivacky    return Error(Loc, "expected a basic block");
2907198892Srdivacky  BB = cast<BasicBlock>(V);
2908198892Srdivacky  return false;
2909198892Srdivacky}
2910198892Srdivacky
2911198892Srdivacky
2912193323Sed/// FunctionHeader
2913193323Sed///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2914218893Sdim///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2915193323Sed///       OptionalAlign OptGC
2916193323Sedbool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2917193323Sed  // Parse the linkage.
2918193323Sed  LocTy LinkageLoc = Lex.getLoc();
2919193323Sed  unsigned Linkage;
2920198090Srdivacky
2921234353Sdim  unsigned Visibility;
2922243830Sdim  AttrBuilder RetAttrs;
2923198090Srdivacky  CallingConv::ID CC;
2924224145Sdim  Type *RetType = 0;
2925193323Sed  LocTy RetTypeLoc = Lex.getLoc();
2926193323Sed  if (ParseOptionalLinkage(Linkage) ||
2927193323Sed      ParseOptionalVisibility(Visibility) ||
2928193323Sed      ParseOptionalCallingConv(CC) ||
2929249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
2930193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2931193323Sed    return true;
2932193323Sed
2933193323Sed  // Verify that the linkage is ok.
2934193323Sed  switch ((GlobalValue::LinkageTypes)Linkage) {
2935193323Sed  case GlobalValue::ExternalLinkage:
2936193323Sed    break; // always ok.
2937193323Sed  case GlobalValue::DLLImportLinkage:
2938193323Sed  case GlobalValue::ExternalWeakLinkage:
2939193323Sed    if (isDefine)
2940193323Sed      return Error(LinkageLoc, "invalid linkage for function definition");
2941193323Sed    break;
2942193323Sed  case GlobalValue::PrivateLinkage:
2943198090Srdivacky  case GlobalValue::LinkerPrivateLinkage:
2944210299Sed  case GlobalValue::LinkerPrivateWeakLinkage:
2945193323Sed  case GlobalValue::InternalLinkage:
2946193323Sed  case GlobalValue::AvailableExternallyLinkage:
2947193323Sed  case GlobalValue::LinkOnceAnyLinkage:
2948193323Sed  case GlobalValue::LinkOnceODRLinkage:
2949243830Sdim  case GlobalValue::LinkOnceODRAutoHideLinkage:
2950193323Sed  case GlobalValue::WeakAnyLinkage:
2951193323Sed  case GlobalValue::WeakODRLinkage:
2952193323Sed  case GlobalValue::DLLExportLinkage:
2953193323Sed    if (!isDefine)
2954193323Sed      return Error(LinkageLoc, "invalid linkage for function declaration");
2955193323Sed    break;
2956193323Sed  case GlobalValue::AppendingLinkage:
2957193323Sed  case GlobalValue::CommonLinkage:
2958193323Sed    return Error(LinkageLoc, "invalid function linkage type");
2959193323Sed  }
2960198090Srdivacky
2961224145Sdim  if (!FunctionType::isValidReturnType(RetType))
2962193323Sed    return Error(RetTypeLoc, "invalid function return type");
2963198090Srdivacky
2964193323Sed  LocTy NameLoc = Lex.getLoc();
2965193323Sed
2966193323Sed  std::string FunctionName;
2967193323Sed  if (Lex.getKind() == lltok::GlobalVar) {
2968193323Sed    FunctionName = Lex.getStrVal();
2969193323Sed  } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
2970193323Sed    unsigned NameID = Lex.getUIntVal();
2971193323Sed
2972193323Sed    if (NameID != NumberedVals.size())
2973193323Sed      return TokError("function expected to be numbered '%" +
2974218893Sdim                      Twine(NumberedVals.size()) + "'");
2975193323Sed  } else {
2976193323Sed    return TokError("expected function name");
2977193323Sed  }
2978198090Srdivacky
2979193323Sed  Lex.Lex();
2980198090Srdivacky
2981193323Sed  if (Lex.getKind() != lltok::lparen)
2982193323Sed    return TokError("expected '(' in function argument list");
2983198090Srdivacky
2984224145Sdim  SmallVector<ArgInfo, 8> ArgList;
2985193323Sed  bool isVarArg;
2986243830Sdim  AttrBuilder FuncAttrs;
2987249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
2988249423Sdim  LocTy NoBuiltinLoc;
2989193323Sed  std::string Section;
2990193323Sed  unsigned Alignment;
2991193323Sed  std::string GC;
2992218893Sdim  bool UnnamedAddr;
2993218893Sdim  LocTy UnnamedAddrLoc;
2994193323Sed
2995224145Sdim  if (ParseArgumentList(ArgList, isVarArg) ||
2996218893Sdim      ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2997218893Sdim                         &UnnamedAddrLoc) ||
2998249423Sdim      ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
2999249423Sdim                                 NoBuiltinLoc) ||
3000193323Sed      (EatIfPresent(lltok::kw_section) &&
3001193323Sed       ParseStringConstant(Section)) ||
3002193323Sed      ParseOptionalAlignment(Alignment) ||
3003193323Sed      (EatIfPresent(lltok::kw_gc) &&
3004193323Sed       ParseStringConstant(GC)))
3005193323Sed    return true;
3006193323Sed
3007249423Sdim  if (FuncAttrs.contains(Attribute::NoBuiltin))
3008249423Sdim    return Error(NoBuiltinLoc, "'nobuiltin' attribute not valid on function");
3009249423Sdim
3010193323Sed  // If the alignment was parsed as an attribute, move to the alignment field.
3011243830Sdim  if (FuncAttrs.hasAlignmentAttr()) {
3012243830Sdim    Alignment = FuncAttrs.getAlignment();
3013249423Sdim    FuncAttrs.removeAttribute(Attribute::Alignment);
3014193323Sed  }
3015198090Srdivacky
3016193323Sed  // Okay, if we got here, the function is syntactically valid.  Convert types
3017193323Sed  // and do semantic checks.
3018224145Sdim  std::vector<Type*> ParamTypeList;
3019249423Sdim  SmallVector<AttributeSet, 8> Attrs;
3020198090Srdivacky
3021243830Sdim  if (RetAttrs.hasAttributes())
3022249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3023249423Sdim                                      AttributeSet::ReturnIndex,
3024249423Sdim                                      RetAttrs));
3025198090Srdivacky
3026193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3027224145Sdim    ParamTypeList.push_back(ArgList[i].Ty);
3028249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3029249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
3030249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3031249423Sdim    }
3032193323Sed  }
3033193323Sed
3034243830Sdim  if (FuncAttrs.hasAttributes())
3035249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3036249423Sdim                                      AttributeSet::FunctionIndex,
3037249423Sdim                                      FuncAttrs));
3038193323Sed
3039249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
3040198090Srdivacky
3041249423Sdim  if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3042198090Srdivacky    return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3043198090Srdivacky
3044226633Sdim  FunctionType *FT =
3045198090Srdivacky    FunctionType::get(RetType, ParamTypeList, isVarArg);
3046226633Sdim  PointerType *PFT = PointerType::getUnqual(FT);
3047193323Sed
3048193323Sed  Fn = 0;
3049193323Sed  if (!FunctionName.empty()) {
3050193323Sed    // If this was a definition of a forward reference, remove the definition
3051193323Sed    // from the forward reference table and fill in the forward ref.
3052193323Sed    std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3053193323Sed      ForwardRefVals.find(FunctionName);
3054193323Sed    if (FRVI != ForwardRefVals.end()) {
3055193323Sed      Fn = M->getFunction(FunctionName);
3056243830Sdim      if (!Fn)
3057243830Sdim        return Error(FRVI->second.second, "invalid forward reference to "
3058243830Sdim                     "function as global value!");
3059207618Srdivacky      if (Fn->getType() != PFT)
3060207618Srdivacky        return Error(FRVI->second.second, "invalid forward reference to "
3061207618Srdivacky                     "function '" + FunctionName + "' with wrong type!");
3062249423Sdim
3063193323Sed      ForwardRefVals.erase(FRVI);
3064193323Sed    } else if ((Fn = M->getFunction(FunctionName))) {
3065224145Sdim      // Reject redefinitions.
3066224145Sdim      return Error(NameLoc, "invalid redefinition of function '" +
3067224145Sdim                   FunctionName + "'");
3068198892Srdivacky    } else if (M->getNamedValue(FunctionName)) {
3069198892Srdivacky      return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3070193323Sed    }
3071198090Srdivacky
3072198090Srdivacky  } else {
3073193323Sed    // If this is a definition of a forward referenced function, make sure the
3074193323Sed    // types agree.
3075193323Sed    std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3076193323Sed      = ForwardRefValIDs.find(NumberedVals.size());
3077193323Sed    if (I != ForwardRefValIDs.end()) {
3078193323Sed      Fn = cast<Function>(I->second.first);
3079193323Sed      if (Fn->getType() != PFT)
3080193323Sed        return Error(NameLoc, "type of definition and forward reference of '@" +
3081218893Sdim                     Twine(NumberedVals.size()) + "' disagree");
3082193323Sed      ForwardRefValIDs.erase(I);
3083193323Sed    }
3084193323Sed  }
3085193323Sed
3086193323Sed  if (Fn == 0)
3087193323Sed    Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3088193323Sed  else // Move the forward-reference to the correct spot in the module.
3089193323Sed    M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3090193323Sed
3091193323Sed  if (FunctionName.empty())
3092193323Sed    NumberedVals.push_back(Fn);
3093198090Srdivacky
3094193323Sed  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3095193323Sed  Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3096193323Sed  Fn->setCallingConv(CC);
3097193323Sed  Fn->setAttributes(PAL);
3098218893Sdim  Fn->setUnnamedAddr(UnnamedAddr);
3099193323Sed  Fn->setAlignment(Alignment);
3100193323Sed  Fn->setSection(Section);
3101193323Sed  if (!GC.empty()) Fn->setGC(GC.c_str());
3102249423Sdim  ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3103198090Srdivacky
3104193323Sed  // Add all of the arguments we parsed to the function.
3105193323Sed  Function::arg_iterator ArgIt = Fn->arg_begin();
3106193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3107193323Sed    // If the argument has a name, insert it into the argument symbol table.
3108193323Sed    if (ArgList[i].Name.empty()) continue;
3109198090Srdivacky
3110193323Sed    // Set the name, if it conflicted, it will be auto-renamed.
3111193323Sed    ArgIt->setName(ArgList[i].Name);
3112198090Srdivacky
3113218893Sdim    if (ArgIt->getName() != ArgList[i].Name)
3114193323Sed      return Error(ArgList[i].Loc, "redefinition of argument '%" +
3115193323Sed                   ArgList[i].Name + "'");
3116193323Sed  }
3117198090Srdivacky
3118193323Sed  return false;
3119193323Sed}
3120193323Sed
3121193323Sed
3122193323Sed/// ParseFunctionBody
3123193323Sed///   ::= '{' BasicBlock+ '}'
3124193323Sed///
3125193323Sedbool LLParser::ParseFunctionBody(Function &Fn) {
3126224145Sdim  if (Lex.getKind() != lltok::lbrace)
3127193323Sed    return TokError("expected '{' in function body");
3128193323Sed  Lex.Lex();  // eat the {.
3129198090Srdivacky
3130198892Srdivacky  int FunctionNumber = -1;
3131198892Srdivacky  if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3132249423Sdim
3133198892Srdivacky  PerFunctionState PFS(*this, Fn, FunctionNumber);
3134198090Srdivacky
3135202375Srdivacky  // We need at least one basic block.
3136224145Sdim  if (Lex.getKind() == lltok::rbrace)
3137202375Srdivacky    return TokError("function body requires at least one basic block");
3138249423Sdim
3139224145Sdim  while (Lex.getKind() != lltok::rbrace)
3140193323Sed    if (ParseBasicBlock(PFS)) return true;
3141198090Srdivacky
3142193323Sed  // Eat the }.
3143193323Sed  Lex.Lex();
3144198090Srdivacky
3145193323Sed  // Verify function is ok.
3146198892Srdivacky  return PFS.FinishFunction();
3147193323Sed}
3148193323Sed
3149193323Sed/// ParseBasicBlock
3150193323Sed///   ::= LabelStr? Instruction*
3151193323Sedbool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3152193323Sed  // If this basic block starts out with a name, remember it.
3153193323Sed  std::string Name;
3154193323Sed  LocTy NameLoc = Lex.getLoc();
3155193323Sed  if (Lex.getKind() == lltok::LabelStr) {
3156193323Sed    Name = Lex.getStrVal();
3157193323Sed    Lex.Lex();
3158193323Sed  }
3159198090Srdivacky
3160193323Sed  BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3161193323Sed  if (BB == 0) return true;
3162198090Srdivacky
3163193323Sed  std::string NameStr;
3164198090Srdivacky
3165193323Sed  // Parse the instructions in this block until we get a terminator.
3166193323Sed  Instruction *Inst;
3167201360Srdivacky  SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
3168193323Sed  do {
3169193323Sed    // This instruction may have three possibilities for a name: a) none
3170193323Sed    // specified, b) name specified "%foo =", c) number specified: "%4 =".
3171193323Sed    LocTy NameLoc = Lex.getLoc();
3172193323Sed    int NameID = -1;
3173193323Sed    NameStr = "";
3174198090Srdivacky
3175193323Sed    if (Lex.getKind() == lltok::LocalVarID) {
3176193323Sed      NameID = Lex.getUIntVal();
3177193323Sed      Lex.Lex();
3178193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3179193323Sed        return true;
3180224145Sdim    } else if (Lex.getKind() == lltok::LocalVar) {
3181193323Sed      NameStr = Lex.getStrVal();
3182193323Sed      Lex.Lex();
3183193323Sed      if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3184193323Sed        return true;
3185193323Sed    }
3186198090Srdivacky
3187201360Srdivacky    switch (ParseInstruction(Inst, BB, PFS)) {
3188234353Sdim    default: llvm_unreachable("Unknown ParseInstruction result!");
3189201360Srdivacky    case InstError: return true;
3190201360Srdivacky    case InstNormal:
3191207618Srdivacky      BB->getInstList().push_back(Inst);
3192207618Srdivacky
3193201360Srdivacky      // With a normal result, we check to see if the instruction is followed by
3194201360Srdivacky      // a comma and metadata.
3195201360Srdivacky      if (EatIfPresent(lltok::comma))
3196212904Sdim        if (ParseInstructionMetadata(Inst, &PFS))
3197201360Srdivacky          return true;
3198201360Srdivacky      break;
3199201360Srdivacky    case InstExtraComma:
3200207618Srdivacky      BB->getInstList().push_back(Inst);
3201207618Srdivacky
3202201360Srdivacky      // If the instruction parser ate an extra comma at the end of it, it
3203201360Srdivacky      // *must* be followed by metadata.
3204212904Sdim      if (ParseInstructionMetadata(Inst, &PFS))
3205201360Srdivacky        return true;
3206249423Sdim      break;
3207201360Srdivacky    }
3208198090Srdivacky
3209193323Sed    // Set the name on the instruction.
3210193323Sed    if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3211193323Sed  } while (!isa<TerminatorInst>(Inst));
3212198090Srdivacky
3213193323Sed  return false;
3214193323Sed}
3215193323Sed
3216193323Sed//===----------------------------------------------------------------------===//
3217193323Sed// Instruction Parsing.
3218193323Sed//===----------------------------------------------------------------------===//
3219193323Sed
3220193323Sed/// ParseInstruction - Parse one of the many different instructions.
3221193323Sed///
3222201360Srdivackyint LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3223201360Srdivacky                               PerFunctionState &PFS) {
3224193323Sed  lltok::Kind Token = Lex.getKind();
3225193323Sed  if (Token == lltok::Eof)
3226193323Sed    return TokError("found end of file when expecting more instructions");
3227193323Sed  LocTy Loc = Lex.getLoc();
3228193323Sed  unsigned KeywordVal = Lex.getUIntVal();
3229193323Sed  Lex.Lex();  // Eat the keyword.
3230198090Srdivacky
3231193323Sed  switch (Token) {
3232193323Sed  default:                    return Error(Loc, "expected instruction opcode");
3233193323Sed  // Terminator Instructions.
3234198090Srdivacky  case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3235193323Sed  case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
3236193323Sed  case lltok::kw_br:          return ParseBr(Inst, PFS);
3237193323Sed  case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
3238198892Srdivacky  case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
3239193323Sed  case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
3240226633Sdim  case lltok::kw_resume:      return ParseResume(Inst, PFS);
3241193323Sed  // Binary Operators.
3242193323Sed  case lltok::kw_add:
3243193323Sed  case lltok::kw_sub:
3244218893Sdim  case lltok::kw_mul:
3245218893Sdim  case lltok::kw_shl: {
3246218893Sdim    bool NUW = EatIfPresent(lltok::kw_nuw);
3247218893Sdim    bool NSW = EatIfPresent(lltok::kw_nsw);
3248218893Sdim    if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3249249423Sdim
3250218893Sdim    if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3251249423Sdim
3252218893Sdim    if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3253218893Sdim    if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3254218893Sdim    return false;
3255198090Srdivacky  }
3256193574Sed  case lltok::kw_fadd:
3257193574Sed  case lltok::kw_fsub:
3258249423Sdim  case lltok::kw_fmul:
3259249423Sdim  case lltok::kw_fdiv:
3260249423Sdim  case lltok::kw_frem: {
3261249423Sdim    FastMathFlags FMF = EatFastMathFlagsIfPresent();
3262249423Sdim    int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3263249423Sdim    if (Res != 0)
3264249423Sdim      return Res;
3265249423Sdim    if (FMF.any())
3266249423Sdim      Inst->setFastMathFlags(FMF);
3267249423Sdim    return 0;
3268249423Sdim  }
3269193574Sed
3270218893Sdim  case lltok::kw_sdiv:
3271218893Sdim  case lltok::kw_udiv:
3272218893Sdim  case lltok::kw_lshr:
3273218893Sdim  case lltok::kw_ashr: {
3274218893Sdim    bool Exact = EatIfPresent(lltok::kw_exact);
3275218893Sdim
3276218893Sdim    if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3277218893Sdim    if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3278218893Sdim    return false;
3279198090Srdivacky  }
3280198090Srdivacky
3281193323Sed  case lltok::kw_urem:
3282193323Sed  case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3283193323Sed  case lltok::kw_and:
3284193323Sed  case lltok::kw_or:
3285193323Sed  case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
3286193323Sed  case lltok::kw_icmp:
3287198090Srdivacky  case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
3288193323Sed  // Casts.
3289193323Sed  case lltok::kw_trunc:
3290193323Sed  case lltok::kw_zext:
3291193323Sed  case lltok::kw_sext:
3292193323Sed  case lltok::kw_fptrunc:
3293193323Sed  case lltok::kw_fpext:
3294193323Sed  case lltok::kw_bitcast:
3295193323Sed  case lltok::kw_uitofp:
3296193323Sed  case lltok::kw_sitofp:
3297193323Sed  case lltok::kw_fptoui:
3298198090Srdivacky  case lltok::kw_fptosi:
3299193323Sed  case lltok::kw_inttoptr:
3300193323Sed  case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
3301193323Sed  // Other.
3302193323Sed  case lltok::kw_select:         return ParseSelect(Inst, PFS);
3303193323Sed  case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
3304193323Sed  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3305193323Sed  case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
3306193323Sed  case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
3307193323Sed  case lltok::kw_phi:            return ParsePHI(Inst, PFS);
3308226633Sdim  case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
3309193323Sed  case lltok::kw_call:           return ParseCall(Inst, PFS, false);
3310193323Sed  case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
3311193323Sed  // Memory.
3312198396Srdivacky  case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
3313234353Sdim  case lltok::kw_load:           return ParseLoad(Inst, PFS);
3314234353Sdim  case lltok::kw_store:          return ParseStore(Inst, PFS);
3315226633Sdim  case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
3316226633Sdim  case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
3317226633Sdim  case lltok::kw_fence:          return ParseFence(Inst, PFS);
3318193323Sed  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3319193323Sed  case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
3320193323Sed  case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
3321193323Sed  }
3322193323Sed}
3323193323Sed
3324193323Sed/// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3325193323Sedbool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3326198090Srdivacky  if (Opc == Instruction::FCmp) {
3327193323Sed    switch (Lex.getKind()) {
3328249423Sdim    default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3329193323Sed    case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3330193323Sed    case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3331193323Sed    case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3332193323Sed    case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3333193323Sed    case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3334193323Sed    case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3335193323Sed    case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3336193323Sed    case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3337193323Sed    case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3338193323Sed    case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3339193323Sed    case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3340193323Sed    case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3341193323Sed    case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3342193323Sed    case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3343193323Sed    case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3344193323Sed    case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3345193323Sed    }
3346193323Sed  } else {
3347193323Sed    switch (Lex.getKind()) {
3348249423Sdim    default: return TokError("expected icmp predicate (e.g. 'eq')");
3349193323Sed    case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
3350193323Sed    case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
3351193323Sed    case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3352193323Sed    case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3353193323Sed    case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3354193323Sed    case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3355193323Sed    case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3356193323Sed    case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3357193323Sed    case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3358193323Sed    case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3359193323Sed    }
3360193323Sed  }
3361193323Sed  Lex.Lex();
3362193323Sed  return false;
3363193323Sed}
3364193323Sed
3365193323Sed//===----------------------------------------------------------------------===//
3366193323Sed// Terminator Instructions.
3367193323Sed//===----------------------------------------------------------------------===//
3368193323Sed
3369193323Sed/// ParseRet - Parse a return instruction.
3370201360Srdivacky///   ::= 'ret' void (',' !dbg, !1)*
3371201360Srdivacky///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
3372224145Sdimbool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3373224145Sdim                        PerFunctionState &PFS) {
3374224145Sdim  SMLoc TypeLoc = Lex.getLoc();
3375224145Sdim  Type *Ty = 0;
3376193323Sed  if (ParseType(Ty, true /*void allowed*/)) return true;
3377198090Srdivacky
3378224145Sdim  Type *ResType = PFS.getFunction().getReturnType();
3379249423Sdim
3380198090Srdivacky  if (Ty->isVoidTy()) {
3381224145Sdim    if (!ResType->isVoidTy())
3382224145Sdim      return Error(TypeLoc, "value doesn't match function result type '" +
3383224145Sdim                   getTypeString(ResType) + "'");
3384249423Sdim
3385198090Srdivacky    Inst = ReturnInst::Create(Context);
3386193323Sed    return false;
3387193323Sed  }
3388198090Srdivacky
3389193323Sed  Value *RV;
3390193323Sed  if (ParseValue(Ty, RV, PFS)) return true;
3391198090Srdivacky
3392224145Sdim  if (ResType != RV->getType())
3393224145Sdim    return Error(TypeLoc, "value doesn't match function result type '" +
3394224145Sdim                 getTypeString(ResType) + "'");
3395249423Sdim
3396198090Srdivacky  Inst = ReturnInst::Create(Context, RV);
3397224145Sdim  return false;
3398193323Sed}
3399193323Sed
3400193323Sed
3401193323Sed/// ParseBr
3402193323Sed///   ::= 'br' TypeAndValue
3403193323Sed///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3404193323Sedbool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3405193323Sed  LocTy Loc, Loc2;
3406198892Srdivacky  Value *Op0;
3407198892Srdivacky  BasicBlock *Op1, *Op2;
3408193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3409198090Srdivacky
3410193323Sed  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3411193323Sed    Inst = BranchInst::Create(BB);
3412193323Sed    return false;
3413193323Sed  }
3414198090Srdivacky
3415198090Srdivacky  if (Op0->getType() != Type::getInt1Ty(Context))
3416193323Sed    return Error(Loc, "branch condition must have 'i1' type");
3417198090Srdivacky
3418193323Sed  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3419198892Srdivacky      ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3420193323Sed      ParseToken(lltok::comma, "expected ',' after true destination") ||
3421198892Srdivacky      ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3422193323Sed    return true;
3423198090Srdivacky
3424198892Srdivacky  Inst = BranchInst::Create(Op1, Op2, Op0);
3425193323Sed  return false;
3426193323Sed}
3427193323Sed
3428193323Sed/// ParseSwitch
3429193323Sed///  Instruction
3430193323Sed///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3431193323Sed///  JumpTable
3432193323Sed///    ::= (TypeAndValue ',' TypeAndValue)*
3433193323Sedbool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3434193323Sed  LocTy CondLoc, BBLoc;
3435198892Srdivacky  Value *Cond;
3436198892Srdivacky  BasicBlock *DefaultBB;
3437193323Sed  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3438193323Sed      ParseToken(lltok::comma, "expected ',' after switch condition") ||
3439198892Srdivacky      ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3440193323Sed      ParseToken(lltok::lsquare, "expected '[' with switch table"))
3441193323Sed    return true;
3442193323Sed
3443204642Srdivacky  if (!Cond->getType()->isIntegerTy())
3444193323Sed    return Error(CondLoc, "switch condition must have integer type");
3445198090Srdivacky
3446193323Sed  // Parse the jump table pairs.
3447193323Sed  SmallPtrSet<Value*, 32> SeenCases;
3448193323Sed  SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3449193323Sed  while (Lex.getKind() != lltok::rsquare) {
3450198892Srdivacky    Value *Constant;
3451198892Srdivacky    BasicBlock *DestBB;
3452198090Srdivacky
3453193323Sed    if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3454193323Sed        ParseToken(lltok::comma, "expected ',' after case value") ||
3455198892Srdivacky        ParseTypeAndBasicBlock(DestBB, PFS))
3456193323Sed      return true;
3457249423Sdim
3458193323Sed    if (!SeenCases.insert(Constant))
3459193323Sed      return Error(CondLoc, "duplicate case value in switch");
3460193323Sed    if (!isa<ConstantInt>(Constant))
3461193323Sed      return Error(CondLoc, "case value is not a constant integer");
3462198090Srdivacky
3463198892Srdivacky    Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3464193323Sed  }
3465198090Srdivacky
3466193323Sed  Lex.Lex();  // Eat the ']'.
3467198090Srdivacky
3468198892Srdivacky  SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3469193323Sed  for (unsigned i = 0, e = Table.size(); i != e; ++i)
3470193323Sed    SI->addCase(Table[i].first, Table[i].second);
3471193323Sed  Inst = SI;
3472193323Sed  return false;
3473193323Sed}
3474193323Sed
3475198892Srdivacky/// ParseIndirectBr
3476198892Srdivacky///  Instruction
3477198892Srdivacky///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3478198892Srdivackybool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3479198892Srdivacky  LocTy AddrLoc;
3480198892Srdivacky  Value *Address;
3481198892Srdivacky  if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3482198892Srdivacky      ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3483198892Srdivacky      ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3484198892Srdivacky    return true;
3485249423Sdim
3486204642Srdivacky  if (!Address->getType()->isPointerTy())
3487198892Srdivacky    return Error(AddrLoc, "indirectbr address must have pointer type");
3488249423Sdim
3489198892Srdivacky  // Parse the destination list.
3490198892Srdivacky  SmallVector<BasicBlock*, 16> DestList;
3491249423Sdim
3492198892Srdivacky  if (Lex.getKind() != lltok::rsquare) {
3493198892Srdivacky    BasicBlock *DestBB;
3494198892Srdivacky    if (ParseTypeAndBasicBlock(DestBB, PFS))
3495198892Srdivacky      return true;
3496198892Srdivacky    DestList.push_back(DestBB);
3497249423Sdim
3498198892Srdivacky    while (EatIfPresent(lltok::comma)) {
3499198892Srdivacky      if (ParseTypeAndBasicBlock(DestBB, PFS))
3500198892Srdivacky        return true;
3501198892Srdivacky      DestList.push_back(DestBB);
3502198892Srdivacky    }
3503198892Srdivacky  }
3504249423Sdim
3505198892Srdivacky  if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3506198892Srdivacky    return true;
3507198892Srdivacky
3508198892Srdivacky  IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3509198892Srdivacky  for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3510198892Srdivacky    IBI->addDestination(DestList[i]);
3511198892Srdivacky  Inst = IBI;
3512198892Srdivacky  return false;
3513198892Srdivacky}
3514198892Srdivacky
3515198892Srdivacky
3516193323Sed/// ParseInvoke
3517193323Sed///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3518193323Sed///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3519193323Sedbool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3520193323Sed  LocTy CallLoc = Lex.getLoc();
3521243830Sdim  AttrBuilder RetAttrs, FnAttrs;
3522249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
3523249423Sdim  LocTy NoBuiltinLoc;
3524198090Srdivacky  CallingConv::ID CC;
3525224145Sdim  Type *RetType = 0;
3526193323Sed  LocTy RetTypeLoc;
3527193323Sed  ValID CalleeID;
3528193323Sed  SmallVector<ParamInfo, 16> ArgList;
3529193323Sed
3530198892Srdivacky  BasicBlock *NormalBB, *UnwindBB;
3531193323Sed  if (ParseOptionalCallingConv(CC) ||
3532249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
3533193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3534193323Sed      ParseValID(CalleeID) ||
3535193323Sed      ParseParameterList(ArgList, PFS) ||
3536249423Sdim      ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3537249423Sdim                                 NoBuiltinLoc) ||
3538193323Sed      ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3539198892Srdivacky      ParseTypeAndBasicBlock(NormalBB, PFS) ||
3540193323Sed      ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3541198892Srdivacky      ParseTypeAndBasicBlock(UnwindBB, PFS))
3542193323Sed    return true;
3543198090Srdivacky
3544193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3545193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3546193323Sed  // rest of the function argument types from the arguments that are present.
3547226633Sdim  PointerType *PFTy = 0;
3548226633Sdim  FunctionType *Ty = 0;
3549193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3550193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3551193323Sed    // Pull out the types of all of the arguments...
3552224145Sdim    std::vector<Type*> ParamTypes;
3553193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3554193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3555198090Srdivacky
3556193323Sed    if (!FunctionType::isValidReturnType(RetType))
3557193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3558198090Srdivacky
3559198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3560198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3561193323Sed  }
3562198090Srdivacky
3563193323Sed  // Look up the callee.
3564193323Sed  Value *Callee;
3565202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3566198090Srdivacky
3567249423Sdim  // Set up the Attribute for the function.
3568249423Sdim  SmallVector<AttributeSet, 8> Attrs;
3569243830Sdim  if (RetAttrs.hasAttributes())
3570249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3571249423Sdim                                      AttributeSet::ReturnIndex,
3572249423Sdim                                      RetAttrs));
3573198090Srdivacky
3574193323Sed  SmallVector<Value*, 8> Args;
3575198090Srdivacky
3576193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3577193323Sed  // correctly.  Also, gather any parameter attributes.
3578193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3579193323Sed  FunctionType::param_iterator E = Ty->param_end();
3580193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3581226633Sdim    Type *ExpectedTy = 0;
3582193323Sed    if (I != E) {
3583193323Sed      ExpectedTy = *I++;
3584193323Sed    } else if (!Ty->isVarArg()) {
3585193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3586193323Sed    }
3587198090Srdivacky
3588193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3589193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3590224145Sdim                   getTypeString(ExpectedTy) + "'");
3591193323Sed    Args.push_back(ArgList[i].V);
3592249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3593249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
3594249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3595249423Sdim    }
3596193323Sed  }
3597198090Srdivacky
3598193323Sed  if (I != E)
3599193323Sed    return Error(CallLoc, "not enough parameters specified for call");
3600198090Srdivacky
3601243830Sdim  if (FnAttrs.hasAttributes())
3602249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3603249423Sdim                                      AttributeSet::FunctionIndex,
3604249423Sdim                                      FnAttrs));
3605198090Srdivacky
3606249423Sdim  // Finish off the Attribute and check them
3607249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
3608198090Srdivacky
3609224145Sdim  InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3610193323Sed  II->setCallingConv(CC);
3611193323Sed  II->setAttributes(PAL);
3612249423Sdim  ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3613193323Sed  Inst = II;
3614193323Sed  return false;
3615193323Sed}
3616193323Sed
3617226633Sdim/// ParseResume
3618226633Sdim///   ::= 'resume' TypeAndValue
3619226633Sdimbool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3620226633Sdim  Value *Exn; LocTy ExnLoc;
3621226633Sdim  if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3622226633Sdim    return true;
3623193323Sed
3624226633Sdim  ResumeInst *RI = ResumeInst::Create(Exn);
3625226633Sdim  Inst = RI;
3626226633Sdim  return false;
3627226633Sdim}
3628193323Sed
3629193323Sed//===----------------------------------------------------------------------===//
3630193323Sed// Binary Operators.
3631193323Sed//===----------------------------------------------------------------------===//
3632193323Sed
3633193323Sed/// ParseArithmetic
3634193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value
3635193323Sed///
3636193323Sed/// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
3637193323Sed/// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3638193323Sedbool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3639193323Sed                               unsigned Opc, unsigned OperandType) {
3640193323Sed  LocTy Loc; Value *LHS, *RHS;
3641193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3642193323Sed      ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3643193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3644193323Sed    return true;
3645193323Sed
3646193323Sed  bool Valid;
3647193323Sed  switch (OperandType) {
3648198090Srdivacky  default: llvm_unreachable("Unknown operand type!");
3649193323Sed  case 0: // int or FP.
3650203954Srdivacky    Valid = LHS->getType()->isIntOrIntVectorTy() ||
3651203954Srdivacky            LHS->getType()->isFPOrFPVectorTy();
3652193323Sed    break;
3653203954Srdivacky  case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3654203954Srdivacky  case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3655193323Sed  }
3656198090Srdivacky
3657193323Sed  if (!Valid)
3658193323Sed    return Error(Loc, "invalid operand type for instruction");
3659198090Srdivacky
3660193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3661193323Sed  return false;
3662193323Sed}
3663193323Sed
3664193323Sed/// ParseLogical
3665193323Sed///  ::= ArithmeticOps TypeAndValue ',' Value {
3666193323Sedbool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3667193323Sed                            unsigned Opc) {
3668193323Sed  LocTy Loc; Value *LHS, *RHS;
3669193323Sed  if (ParseTypeAndValue(LHS, Loc, PFS) ||
3670193323Sed      ParseToken(lltok::comma, "expected ',' in logical operation") ||
3671193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3672193323Sed    return true;
3673193323Sed
3674203954Srdivacky  if (!LHS->getType()->isIntOrIntVectorTy())
3675193323Sed    return Error(Loc,"instruction requires integer or integer vector operands");
3676193323Sed
3677193323Sed  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3678193323Sed  return false;
3679193323Sed}
3680193323Sed
3681193323Sed
3682193323Sed/// ParseCompare
3683193323Sed///  ::= 'icmp' IPredicates TypeAndValue ',' Value
3684193323Sed///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
3685193323Sedbool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3686193323Sed                            unsigned Opc) {
3687193323Sed  // Parse the integer/fp comparison predicate.
3688193323Sed  LocTy Loc;
3689193323Sed  unsigned Pred;
3690193323Sed  Value *LHS, *RHS;
3691193323Sed  if (ParseCmpPredicate(Pred, Opc) ||
3692193323Sed      ParseTypeAndValue(LHS, Loc, PFS) ||
3693193323Sed      ParseToken(lltok::comma, "expected ',' after compare value") ||
3694193323Sed      ParseValue(LHS->getType(), RHS, PFS))
3695193323Sed    return true;
3696198090Srdivacky
3697193323Sed  if (Opc == Instruction::FCmp) {
3698203954Srdivacky    if (!LHS->getType()->isFPOrFPVectorTy())
3699193323Sed      return Error(Loc, "fcmp requires floating point operands");
3700193323Sed    Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3701198090Srdivacky  } else {
3702198090Srdivacky    assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3703203954Srdivacky    if (!LHS->getType()->isIntOrIntVectorTy() &&
3704234353Sdim        !LHS->getType()->getScalarType()->isPointerTy())
3705193323Sed      return Error(Loc, "icmp requires integer operands");
3706193323Sed    Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3707193323Sed  }
3708193323Sed  return false;
3709193323Sed}
3710193323Sed
3711193323Sed//===----------------------------------------------------------------------===//
3712193323Sed// Other Instructions.
3713193323Sed//===----------------------------------------------------------------------===//
3714193323Sed
3715193323Sed
3716193323Sed/// ParseCast
3717193323Sed///   ::= CastOpc TypeAndValue 'to' Type
3718193323Sedbool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3719193323Sed                         unsigned Opc) {
3720224145Sdim  LocTy Loc;
3721224145Sdim  Value *Op;
3722224145Sdim  Type *DestTy = 0;
3723193323Sed  if (ParseTypeAndValue(Op, Loc, PFS) ||
3724193323Sed      ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3725193323Sed      ParseType(DestTy))
3726193323Sed    return true;
3727198090Srdivacky
3728193323Sed  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3729193323Sed    CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3730193323Sed    return Error(Loc, "invalid cast opcode for cast from '" +
3731224145Sdim                 getTypeString(Op->getType()) + "' to '" +
3732224145Sdim                 getTypeString(DestTy) + "'");
3733193323Sed  }
3734193323Sed  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3735193323Sed  return false;
3736193323Sed}
3737193323Sed
3738193323Sed/// ParseSelect
3739193323Sed///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3740193323Sedbool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3741193323Sed  LocTy Loc;
3742193323Sed  Value *Op0, *Op1, *Op2;
3743193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3744193323Sed      ParseToken(lltok::comma, "expected ',' after select condition") ||
3745193323Sed      ParseTypeAndValue(Op1, PFS) ||
3746193323Sed      ParseToken(lltok::comma, "expected ',' after select value") ||
3747193323Sed      ParseTypeAndValue(Op2, PFS))
3748193323Sed    return true;
3749198090Srdivacky
3750193323Sed  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3751193323Sed    return Error(Loc, Reason);
3752198090Srdivacky
3753193323Sed  Inst = SelectInst::Create(Op0, Op1, Op2);
3754193323Sed  return false;
3755193323Sed}
3756193323Sed
3757193323Sed/// ParseVA_Arg
3758193323Sed///   ::= 'va_arg' TypeAndValue ',' Type
3759193323Sedbool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3760193323Sed  Value *Op;
3761224145Sdim  Type *EltTy = 0;
3762193323Sed  LocTy TypeLoc;
3763193323Sed  if (ParseTypeAndValue(Op, PFS) ||
3764193323Sed      ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3765193323Sed      ParseType(EltTy, TypeLoc))
3766193323Sed    return true;
3767198090Srdivacky
3768193323Sed  if (!EltTy->isFirstClassType())
3769193323Sed    return Error(TypeLoc, "va_arg requires operand with first class type");
3770193323Sed
3771193323Sed  Inst = new VAArgInst(Op, EltTy);
3772193323Sed  return false;
3773193323Sed}
3774193323Sed
3775193323Sed/// ParseExtractElement
3776193323Sed///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
3777193323Sedbool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3778193323Sed  LocTy Loc;
3779193323Sed  Value *Op0, *Op1;
3780193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3781193323Sed      ParseToken(lltok::comma, "expected ',' after extract value") ||
3782193323Sed      ParseTypeAndValue(Op1, PFS))
3783193323Sed    return true;
3784198090Srdivacky
3785193323Sed  if (!ExtractElementInst::isValidOperands(Op0, Op1))
3786193323Sed    return Error(Loc, "invalid extractelement operands");
3787198090Srdivacky
3788198090Srdivacky  Inst = ExtractElementInst::Create(Op0, Op1);
3789193323Sed  return false;
3790193323Sed}
3791193323Sed
3792193323Sed/// ParseInsertElement
3793193323Sed///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3794193323Sedbool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3795193323Sed  LocTy Loc;
3796193323Sed  Value *Op0, *Op1, *Op2;
3797193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3798193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3799193323Sed      ParseTypeAndValue(Op1, PFS) ||
3800193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3801193323Sed      ParseTypeAndValue(Op2, PFS))
3802193323Sed    return true;
3803198090Srdivacky
3804193323Sed  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3805198090Srdivacky    return Error(Loc, "invalid insertelement operands");
3806198090Srdivacky
3807193323Sed  Inst = InsertElementInst::Create(Op0, Op1, Op2);
3808193323Sed  return false;
3809193323Sed}
3810193323Sed
3811193323Sed/// ParseShuffleVector
3812193323Sed///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3813193323Sedbool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3814193323Sed  LocTy Loc;
3815193323Sed  Value *Op0, *Op1, *Op2;
3816193323Sed  if (ParseTypeAndValue(Op0, Loc, PFS) ||
3817193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3818193323Sed      ParseTypeAndValue(Op1, PFS) ||
3819193323Sed      ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3820193323Sed      ParseTypeAndValue(Op2, PFS))
3821193323Sed    return true;
3822198090Srdivacky
3823193323Sed  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3824234353Sdim    return Error(Loc, "invalid shufflevector operands");
3825198090Srdivacky
3826193323Sed  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3827193323Sed  return false;
3828193323Sed}
3829193323Sed
3830193323Sed/// ParsePHI
3831198396Srdivacky///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3832201360Srdivackyint LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3833224145Sdim  Type *Ty = 0;  LocTy TypeLoc;
3834193323Sed  Value *Op0, *Op1;
3835198090Srdivacky
3836224145Sdim  if (ParseType(Ty, TypeLoc) ||
3837193323Sed      ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3838193323Sed      ParseValue(Ty, Op0, PFS) ||
3839193323Sed      ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3840198090Srdivacky      ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3841193323Sed      ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3842193323Sed    return true;
3843198090Srdivacky
3844201360Srdivacky  bool AteExtraComma = false;
3845193323Sed  SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3846193323Sed  while (1) {
3847193323Sed    PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3848198090Srdivacky
3849193323Sed    if (!EatIfPresent(lltok::comma))
3850193323Sed      break;
3851193323Sed
3852201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
3853201360Srdivacky      AteExtraComma = true;
3854198396Srdivacky      break;
3855201360Srdivacky    }
3856198396Srdivacky
3857193323Sed    if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3858193323Sed        ParseValue(Ty, Op0, PFS) ||
3859193323Sed        ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3860198090Srdivacky        ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3861193323Sed        ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3862193323Sed      return true;
3863193323Sed  }
3864198090Srdivacky
3865193323Sed  if (!Ty->isFirstClassType())
3866193323Sed    return Error(TypeLoc, "phi node must have first class type");
3867193323Sed
3868221345Sdim  PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3869193323Sed  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3870193323Sed    PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3871193323Sed  Inst = PN;
3872201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
3873193323Sed}
3874193323Sed
3875226633Sdim/// ParseLandingPad
3876226633Sdim///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3877226633Sdim/// Clause
3878226633Sdim///   ::= 'catch' TypeAndValue
3879226633Sdim///   ::= 'filter'
3880226633Sdim///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3881226633Sdimbool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3882226633Sdim  Type *Ty = 0; LocTy TyLoc;
3883226633Sdim  Value *PersFn; LocTy PersFnLoc;
3884226633Sdim
3885226633Sdim  if (ParseType(Ty, TyLoc) ||
3886226633Sdim      ParseToken(lltok::kw_personality, "expected 'personality'") ||
3887226633Sdim      ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3888226633Sdim    return true;
3889226633Sdim
3890226633Sdim  LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3891226633Sdim  LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3892226633Sdim
3893226633Sdim  while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3894226633Sdim    LandingPadInst::ClauseType CT;
3895226633Sdim    if (EatIfPresent(lltok::kw_catch))
3896226633Sdim      CT = LandingPadInst::Catch;
3897226633Sdim    else if (EatIfPresent(lltok::kw_filter))
3898226633Sdim      CT = LandingPadInst::Filter;
3899226633Sdim    else
3900226633Sdim      return TokError("expected 'catch' or 'filter' clause type");
3901226633Sdim
3902226633Sdim    Value *V; LocTy VLoc;
3903226633Sdim    if (ParseTypeAndValue(V, VLoc, PFS)) {
3904226633Sdim      delete LP;
3905226633Sdim      return true;
3906226633Sdim    }
3907226633Sdim
3908226633Sdim    // A 'catch' type expects a non-array constant. A filter clause expects an
3909226633Sdim    // array constant.
3910226633Sdim    if (CT == LandingPadInst::Catch) {
3911226633Sdim      if (isa<ArrayType>(V->getType()))
3912226633Sdim        Error(VLoc, "'catch' clause has an invalid type");
3913226633Sdim    } else {
3914226633Sdim      if (!isa<ArrayType>(V->getType()))
3915226633Sdim        Error(VLoc, "'filter' clause has an invalid type");
3916226633Sdim    }
3917226633Sdim
3918226633Sdim    LP->addClause(V);
3919226633Sdim  }
3920226633Sdim
3921226633Sdim  Inst = LP;
3922226633Sdim  return false;
3923226633Sdim}
3924226633Sdim
3925193323Sed/// ParseCall
3926193323Sed///   ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3927193323Sed///       ParameterList OptionalAttrs
3928193323Sedbool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3929193323Sed                         bool isTail) {
3930243830Sdim  AttrBuilder RetAttrs, FnAttrs;
3931249423Sdim  std::vector<unsigned> FwdRefAttrGrps;
3932249423Sdim  LocTy NoBuiltinLoc;
3933198090Srdivacky  CallingConv::ID CC;
3934224145Sdim  Type *RetType = 0;
3935193323Sed  LocTy RetTypeLoc;
3936193323Sed  ValID CalleeID;
3937193323Sed  SmallVector<ParamInfo, 16> ArgList;
3938193323Sed  LocTy CallLoc = Lex.getLoc();
3939198090Srdivacky
3940193323Sed  if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3941193323Sed      ParseOptionalCallingConv(CC) ||
3942249423Sdim      ParseOptionalReturnAttrs(RetAttrs) ||
3943193323Sed      ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3944193323Sed      ParseValID(CalleeID) ||
3945193323Sed      ParseParameterList(ArgList, PFS) ||
3946249423Sdim      ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3947249423Sdim                                 NoBuiltinLoc))
3948193323Sed    return true;
3949198090Srdivacky
3950193323Sed  // If RetType is a non-function pointer type, then this is the short syntax
3951193323Sed  // for the call, which means that RetType is just the return type.  Infer the
3952193323Sed  // rest of the function argument types from the arguments that are present.
3953226633Sdim  PointerType *PFTy = 0;
3954226633Sdim  FunctionType *Ty = 0;
3955193323Sed  if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3956193323Sed      !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3957193323Sed    // Pull out the types of all of the arguments...
3958224145Sdim    std::vector<Type*> ParamTypes;
3959193323Sed    for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3960193323Sed      ParamTypes.push_back(ArgList[i].V->getType());
3961198090Srdivacky
3962193323Sed    if (!FunctionType::isValidReturnType(RetType))
3963193323Sed      return Error(RetTypeLoc, "Invalid result type for LLVM function");
3964198090Srdivacky
3965198090Srdivacky    Ty = FunctionType::get(RetType, ParamTypes, false);
3966198090Srdivacky    PFTy = PointerType::getUnqual(Ty);
3967193323Sed  }
3968198090Srdivacky
3969193323Sed  // Look up the callee.
3970193323Sed  Value *Callee;
3971202375Srdivacky  if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3972198090Srdivacky
3973249423Sdim  // Set up the Attribute for the function.
3974249423Sdim  SmallVector<AttributeSet, 8> Attrs;
3975243830Sdim  if (RetAttrs.hasAttributes())
3976249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
3977249423Sdim                                      AttributeSet::ReturnIndex,
3978249423Sdim                                      RetAttrs));
3979198090Srdivacky
3980193323Sed  SmallVector<Value*, 8> Args;
3981198090Srdivacky
3982193323Sed  // Loop through FunctionType's arguments and ensure they are specified
3983193323Sed  // correctly.  Also, gather any parameter attributes.
3984193323Sed  FunctionType::param_iterator I = Ty->param_begin();
3985193323Sed  FunctionType::param_iterator E = Ty->param_end();
3986193323Sed  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3987226633Sdim    Type *ExpectedTy = 0;
3988193323Sed    if (I != E) {
3989193323Sed      ExpectedTy = *I++;
3990193323Sed    } else if (!Ty->isVarArg()) {
3991193323Sed      return Error(ArgList[i].Loc, "too many arguments specified");
3992193323Sed    }
3993198090Srdivacky
3994193323Sed    if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3995193323Sed      return Error(ArgList[i].Loc, "argument is not of expected type '" +
3996224145Sdim                   getTypeString(ExpectedTy) + "'");
3997193323Sed    Args.push_back(ArgList[i].V);
3998249423Sdim    if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3999249423Sdim      AttrBuilder B(ArgList[i].Attrs, i + 1);
4000249423Sdim      Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4001249423Sdim    }
4002193323Sed  }
4003198090Srdivacky
4004193323Sed  if (I != E)
4005193323Sed    return Error(CallLoc, "not enough parameters specified for call");
4006193323Sed
4007243830Sdim  if (FnAttrs.hasAttributes())
4008249423Sdim    Attrs.push_back(AttributeSet::get(RetType->getContext(),
4009249423Sdim                                      AttributeSet::FunctionIndex,
4010249423Sdim                                      FnAttrs));
4011193323Sed
4012249423Sdim  // Finish off the Attribute and check them
4013249423Sdim  AttributeSet PAL = AttributeSet::get(Context, Attrs);
4014198090Srdivacky
4015224145Sdim  CallInst *CI = CallInst::Create(Callee, Args);
4016193323Sed  CI->setTailCall(isTail);
4017193323Sed  CI->setCallingConv(CC);
4018193323Sed  CI->setAttributes(PAL);
4019249423Sdim  ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4020193323Sed  Inst = CI;
4021193323Sed  return false;
4022193323Sed}
4023193323Sed
4024193323Sed//===----------------------------------------------------------------------===//
4025193323Sed// Memory Instructions.
4026193323Sed//===----------------------------------------------------------------------===//
4027193323Sed
4028193323Sed/// ParseAlloc
4029198090Srdivacky///   ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
4030224145Sdimint LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4031193323Sed  Value *Size = 0;
4032195340Sed  LocTy SizeLoc;
4033193323Sed  unsigned Alignment = 0;
4034224145Sdim  Type *Ty = 0;
4035193323Sed  if (ParseType(Ty)) return true;
4036193323Sed
4037201360Srdivacky  bool AteExtraComma = false;
4038193323Sed  if (EatIfPresent(lltok::comma)) {
4039201360Srdivacky    if (Lex.getKind() == lltok::kw_align) {
4040201360Srdivacky      if (ParseOptionalAlignment(Alignment)) return true;
4041201360Srdivacky    } else if (Lex.getKind() == lltok::MetadataVar) {
4042201360Srdivacky      AteExtraComma = true;
4043198090Srdivacky    } else {
4044201360Srdivacky      if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4045201360Srdivacky          ParseOptionalCommaAlign(Alignment, AteExtraComma))
4046201360Srdivacky        return true;
4047193323Sed    }
4048193323Sed  }
4049193323Sed
4050210299Sed  if (Size && !Size->getType()->isIntegerTy())
4051210299Sed    return Error(SizeLoc, "element count must have integer type");
4052193323Sed
4053224145Sdim  Inst = new AllocaInst(Ty, Size, Alignment);
4054224145Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4055193323Sed}
4056193323Sed
4057193323Sed/// ParseLoad
4058226633Sdim///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4059249423Sdim///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
4060226633Sdim///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4061234353Sdimint LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4062193323Sed  Value *Val; LocTy Loc;
4063198090Srdivacky  unsigned Alignment = 0;
4064201360Srdivacky  bool AteExtraComma = false;
4065226633Sdim  bool isAtomic = false;
4066226633Sdim  AtomicOrdering Ordering = NotAtomic;
4067226633Sdim  SynchronizationScope Scope = CrossThread;
4068226633Sdim
4069226633Sdim  if (Lex.getKind() == lltok::kw_atomic) {
4070226633Sdim    isAtomic = true;
4071226633Sdim    Lex.Lex();
4072226633Sdim  }
4073226633Sdim
4074234353Sdim  bool isVolatile = false;
4075226633Sdim  if (Lex.getKind() == lltok::kw_volatile) {
4076226633Sdim    isVolatile = true;
4077226633Sdim    Lex.Lex();
4078226633Sdim  }
4079226633Sdim
4080201360Srdivacky  if (ParseTypeAndValue(Val, Loc, PFS) ||
4081226633Sdim      ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4082201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
4083201360Srdivacky    return true;
4084193323Sed
4085204642Srdivacky  if (!Val->getType()->isPointerTy() ||
4086193323Sed      !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4087193323Sed    return Error(Loc, "load operand must be a pointer to a first class type");
4088226633Sdim  if (isAtomic && !Alignment)
4089226633Sdim    return Error(Loc, "atomic load must have explicit non-zero alignment");
4090226633Sdim  if (Ordering == Release || Ordering == AcquireRelease)
4091226633Sdim    return Error(Loc, "atomic load cannot use Release ordering");
4092198090Srdivacky
4093226633Sdim  Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4094201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4095193323Sed}
4096193323Sed
4097193323Sed/// ParseStore
4098226633Sdim
4099226633Sdim///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4100226633Sdim///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4101226633Sdim///       'singlethread'? AtomicOrdering (',' 'align' i32)?
4102234353Sdimint LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4103193323Sed  Value *Val, *Ptr; LocTy Loc, PtrLoc;
4104198090Srdivacky  unsigned Alignment = 0;
4105201360Srdivacky  bool AteExtraComma = false;
4106226633Sdim  bool isAtomic = false;
4107226633Sdim  AtomicOrdering Ordering = NotAtomic;
4108226633Sdim  SynchronizationScope Scope = CrossThread;
4109226633Sdim
4110226633Sdim  if (Lex.getKind() == lltok::kw_atomic) {
4111226633Sdim    isAtomic = true;
4112226633Sdim    Lex.Lex();
4113226633Sdim  }
4114226633Sdim
4115234353Sdim  bool isVolatile = false;
4116226633Sdim  if (Lex.getKind() == lltok::kw_volatile) {
4117226633Sdim    isVolatile = true;
4118226633Sdim    Lex.Lex();
4119226633Sdim  }
4120226633Sdim
4121193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
4122193323Sed      ParseToken(lltok::comma, "expected ',' after store operand") ||
4123201360Srdivacky      ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4124226633Sdim      ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4125201360Srdivacky      ParseOptionalCommaAlign(Alignment, AteExtraComma))
4126193323Sed    return true;
4127198090Srdivacky
4128204642Srdivacky  if (!Ptr->getType()->isPointerTy())
4129193323Sed    return Error(PtrLoc, "store operand must be a pointer");
4130193323Sed  if (!Val->getType()->isFirstClassType())
4131193323Sed    return Error(Loc, "store operand must be a first class value");
4132193323Sed  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4133193323Sed    return Error(Loc, "stored value and pointer type do not match");
4134226633Sdim  if (isAtomic && !Alignment)
4135226633Sdim    return Error(Loc, "atomic store must have explicit non-zero alignment");
4136226633Sdim  if (Ordering == Acquire || Ordering == AcquireRelease)
4137226633Sdim    return Error(Loc, "atomic store cannot use Acquire ordering");
4138198090Srdivacky
4139226633Sdim  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4140201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4141193323Sed}
4142193323Sed
4143226633Sdim/// ParseCmpXchg
4144226633Sdim///   ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4145226633Sdim///       'singlethread'? AtomicOrdering
4146226633Sdimint LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4147226633Sdim  Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4148226633Sdim  bool AteExtraComma = false;
4149226633Sdim  AtomicOrdering Ordering = NotAtomic;
4150226633Sdim  SynchronizationScope Scope = CrossThread;
4151226633Sdim  bool isVolatile = false;
4152226633Sdim
4153226633Sdim  if (EatIfPresent(lltok::kw_volatile))
4154226633Sdim    isVolatile = true;
4155226633Sdim
4156226633Sdim  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4157226633Sdim      ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4158226633Sdim      ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4159226633Sdim      ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4160226633Sdim      ParseTypeAndValue(New, NewLoc, PFS) ||
4161226633Sdim      ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4162226633Sdim    return true;
4163226633Sdim
4164226633Sdim  if (Ordering == Unordered)
4165226633Sdim    return TokError("cmpxchg cannot be unordered");
4166226633Sdim  if (!Ptr->getType()->isPointerTy())
4167226633Sdim    return Error(PtrLoc, "cmpxchg operand must be a pointer");
4168226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4169226633Sdim    return Error(CmpLoc, "compare value and pointer type do not match");
4170226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4171226633Sdim    return Error(NewLoc, "new value and pointer type do not match");
4172226633Sdim  if (!New->getType()->isIntegerTy())
4173226633Sdim    return Error(NewLoc, "cmpxchg operand must be an integer");
4174226633Sdim  unsigned Size = New->getType()->getPrimitiveSizeInBits();
4175226633Sdim  if (Size < 8 || (Size & (Size - 1)))
4176226633Sdim    return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4177226633Sdim                         " integer");
4178226633Sdim
4179226633Sdim  AtomicCmpXchgInst *CXI =
4180226633Sdim    new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4181226633Sdim  CXI->setVolatile(isVolatile);
4182226633Sdim  Inst = CXI;
4183226633Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4184226633Sdim}
4185226633Sdim
4186226633Sdim/// ParseAtomicRMW
4187226633Sdim///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4188226633Sdim///       'singlethread'? AtomicOrdering
4189226633Sdimint LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4190226633Sdim  Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4191226633Sdim  bool AteExtraComma = false;
4192226633Sdim  AtomicOrdering Ordering = NotAtomic;
4193226633Sdim  SynchronizationScope Scope = CrossThread;
4194226633Sdim  bool isVolatile = false;
4195226633Sdim  AtomicRMWInst::BinOp Operation;
4196226633Sdim
4197226633Sdim  if (EatIfPresent(lltok::kw_volatile))
4198226633Sdim    isVolatile = true;
4199226633Sdim
4200226633Sdim  switch (Lex.getKind()) {
4201226633Sdim  default: return TokError("expected binary operation in atomicrmw");
4202226633Sdim  case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4203226633Sdim  case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4204226633Sdim  case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4205226633Sdim  case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4206226633Sdim  case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4207226633Sdim  case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4208226633Sdim  case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4209226633Sdim  case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4210226633Sdim  case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4211226633Sdim  case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4212226633Sdim  case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4213226633Sdim  }
4214226633Sdim  Lex.Lex();  // Eat the operation.
4215226633Sdim
4216226633Sdim  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4217226633Sdim      ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4218226633Sdim      ParseTypeAndValue(Val, ValLoc, PFS) ||
4219226633Sdim      ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4220226633Sdim    return true;
4221226633Sdim
4222226633Sdim  if (Ordering == Unordered)
4223226633Sdim    return TokError("atomicrmw cannot be unordered");
4224226633Sdim  if (!Ptr->getType()->isPointerTy())
4225226633Sdim    return Error(PtrLoc, "atomicrmw operand must be a pointer");
4226226633Sdim  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4227226633Sdim    return Error(ValLoc, "atomicrmw value and pointer type do not match");
4228226633Sdim  if (!Val->getType()->isIntegerTy())
4229226633Sdim    return Error(ValLoc, "atomicrmw operand must be an integer");
4230226633Sdim  unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4231226633Sdim  if (Size < 8 || (Size & (Size - 1)))
4232226633Sdim    return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4233226633Sdim                         " integer");
4234226633Sdim
4235226633Sdim  AtomicRMWInst *RMWI =
4236226633Sdim    new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4237226633Sdim  RMWI->setVolatile(isVolatile);
4238226633Sdim  Inst = RMWI;
4239226633Sdim  return AteExtraComma ? InstExtraComma : InstNormal;
4240226633Sdim}
4241226633Sdim
4242226633Sdim/// ParseFence
4243226633Sdim///   ::= 'fence' 'singlethread'? AtomicOrdering
4244226633Sdimint LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4245226633Sdim  AtomicOrdering Ordering = NotAtomic;
4246226633Sdim  SynchronizationScope Scope = CrossThread;
4247226633Sdim  if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4248226633Sdim    return true;
4249226633Sdim
4250226633Sdim  if (Ordering == Unordered)
4251226633Sdim    return TokError("fence cannot be unordered");
4252226633Sdim  if (Ordering == Monotonic)
4253226633Sdim    return TokError("fence cannot be monotonic");
4254226633Sdim
4255226633Sdim  Inst = new FenceInst(Context, Ordering, Scope);
4256226633Sdim  return InstNormal;
4257226633Sdim}
4258226633Sdim
4259193323Sed/// ParseGetElementPtr
4260198090Srdivacky///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4261201360Srdivackyint LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4262234353Sdim  Value *Ptr = 0;
4263234353Sdim  Value *Val = 0;
4264234353Sdim  LocTy Loc, EltLoc;
4265198090Srdivacky
4266198090Srdivacky  bool InBounds = EatIfPresent(lltok::kw_inbounds);
4267198090Srdivacky
4268193323Sed  if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4269198090Srdivacky
4270251662Sdim  Type *BaseType = Ptr->getType();
4271251662Sdim  PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4272251662Sdim  if (!BasePointerType)
4273193323Sed    return Error(Loc, "base of getelementptr must be a pointer");
4274198090Srdivacky
4275193323Sed  SmallVector<Value*, 16> Indices;
4276201360Srdivacky  bool AteExtraComma = false;
4277193323Sed  while (EatIfPresent(lltok::comma)) {
4278201360Srdivacky    if (Lex.getKind() == lltok::MetadataVar) {
4279201360Srdivacky      AteExtraComma = true;
4280198090Srdivacky      break;
4281201360Srdivacky    }
4282193323Sed    if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4283234353Sdim    if (!Val->getType()->getScalarType()->isIntegerTy())
4284193323Sed      return Error(EltLoc, "getelementptr index must be an integer");
4285234353Sdim    if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4286234353Sdim      return Error(EltLoc, "getelementptr index type missmatch");
4287234353Sdim    if (Val->getType()->isVectorTy()) {
4288234353Sdim      unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4289234353Sdim      unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4290234353Sdim      if (ValNumEl != PtrNumEl)
4291234353Sdim        return Error(EltLoc,
4292234353Sdim          "getelementptr vector index has a wrong number of elements");
4293234353Sdim    }
4294193323Sed    Indices.push_back(Val);
4295193323Sed  }
4296198090Srdivacky
4297251662Sdim  if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4298251662Sdim    return Error(Loc, "base element of getelementptr must be sized");
4299251662Sdim
4300251662Sdim  if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4301193323Sed    return Error(Loc, "invalid getelementptr indices");
4302226633Sdim  Inst = GetElementPtrInst::Create(Ptr, Indices);
4303198090Srdivacky  if (InBounds)
4304198090Srdivacky    cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4305201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4306193323Sed}
4307193323Sed
4308193323Sed/// ParseExtractValue
4309193323Sed///   ::= 'extractvalue' TypeAndValue (',' uint32)+
4310201360Srdivackyint LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4311193323Sed  Value *Val; LocTy Loc;
4312193323Sed  SmallVector<unsigned, 4> Indices;
4313201360Srdivacky  bool AteExtraComma;
4314193323Sed  if (ParseTypeAndValue(Val, Loc, PFS) ||
4315201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
4316193323Sed    return true;
4317193323Sed
4318203954Srdivacky  if (!Val->getType()->isAggregateType())
4319203954Srdivacky    return Error(Loc, "extractvalue operand must be aggregate type");
4320193323Sed
4321224145Sdim  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4322193323Sed    return Error(Loc, "invalid indices for extractvalue");
4323224145Sdim  Inst = ExtractValueInst::Create(Val, Indices);
4324201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4325193323Sed}
4326193323Sed
4327193323Sed/// ParseInsertValue
4328193323Sed///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4329201360Srdivackyint LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4330193323Sed  Value *Val0, *Val1; LocTy Loc0, Loc1;
4331193323Sed  SmallVector<unsigned, 4> Indices;
4332201360Srdivacky  bool AteExtraComma;
4333193323Sed  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4334193323Sed      ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4335193323Sed      ParseTypeAndValue(Val1, Loc1, PFS) ||
4336201360Srdivacky      ParseIndexList(Indices, AteExtraComma))
4337193323Sed    return true;
4338249423Sdim
4339203954Srdivacky  if (!Val0->getType()->isAggregateType())
4340203954Srdivacky    return Error(Loc0, "insertvalue operand must be aggregate type");
4341198090Srdivacky
4342224145Sdim  if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4343193323Sed    return Error(Loc0, "invalid indices for insertvalue");
4344224145Sdim  Inst = InsertValueInst::Create(Val0, Val1, Indices);
4345201360Srdivacky  return AteExtraComma ? InstExtraComma : InstNormal;
4346193323Sed}
4347193323Sed
4348193323Sed//===----------------------------------------------------------------------===//
4349193323Sed// Embedded metadata.
4350193323Sed//===----------------------------------------------------------------------===//
4351193323Sed
4352193323Sed/// ParseMDNodeVector
4353193323Sed///   ::= Element (',' Element)*
4354193323Sed/// Element
4355193323Sed///   ::= 'null' | TypeAndValue
4356202375Srdivackybool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4357202375Srdivacky                                 PerFunctionState *PFS) {
4358210299Sed  // Check for an empty list.
4359210299Sed  if (Lex.getKind() == lltok::rbrace)
4360210299Sed    return false;
4361210299Sed
4362193323Sed  do {
4363201360Srdivacky    // Null is a special case since it is typeless.
4364201360Srdivacky    if (EatIfPresent(lltok::kw_null)) {
4365201360Srdivacky      Elts.push_back(0);
4366201360Srdivacky      continue;
4367201360Srdivacky    }
4368249423Sdim
4369198090Srdivacky    Value *V = 0;
4370224145Sdim    if (ParseTypeAndValue(V, PFS)) return true;
4371193323Sed    Elts.push_back(V);
4372193323Sed  } while (EatIfPresent(lltok::comma));
4373193323Sed
4374193323Sed  return false;
4375193323Sed}
4376