LLVM API Documentation

LLParser.cpp
Go to the documentation of this file.
00001 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the parser class for .ll files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "LLParser.h"
00015 #include "llvm/ADT/SmallPtrSet.h"
00016 #include "llvm/IR/AutoUpgrade.h"
00017 #include "llvm/IR/CallingConv.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/InlineAsm.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/LLVMContext.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Operator.h"
00025 #include "llvm/IR/ValueSymbolTable.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/SaveAndRestore.h"
00028 #include "llvm/Support/raw_ostream.h"
00029 using namespace llvm;
00030 
00031 static std::string getTypeString(Type *T) {
00032   std::string Result;
00033   raw_string_ostream Tmp(Result);
00034   Tmp << *T;
00035   return Tmp.str();
00036 }
00037 
00038 /// Run: module ::= toplevelentity*
00039 bool LLParser::Run() {
00040   // Prime the lexer.
00041   Lex.Lex();
00042 
00043   return ParseTopLevelEntities() ||
00044          ValidateEndOfModule();
00045 }
00046 
00047 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
00048 /// module.
00049 bool LLParser::ValidateEndOfModule() {
00050   // Handle any instruction metadata forward references.
00051   if (!ForwardRefInstMetadata.empty()) {
00052     for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
00053          I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
00054          I != E; ++I) {
00055       Instruction *Inst = I->first;
00056       const std::vector<MDRef> &MDList = I->second;
00057 
00058       for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
00059         unsigned SlotNo = MDList[i].MDSlot;
00060 
00061         if (SlotNo >= NumberedMetadata.size() ||
00062             NumberedMetadata[SlotNo] == nullptr)
00063           return Error(MDList[i].Loc, "use of undefined metadata '!" +
00064                        Twine(SlotNo) + "'");
00065         Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
00066       }
00067     }
00068     ForwardRefInstMetadata.clear();
00069   }
00070 
00071   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
00072     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
00073 
00074   // Handle any function attribute group forward references.
00075   for (std::map<Value*, std::vector<unsigned> >::iterator
00076          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
00077          I != E; ++I) {
00078     Value *V = I->first;
00079     std::vector<unsigned> &Vec = I->second;
00080     AttrBuilder B;
00081 
00082     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
00083          VI != VE; ++VI)
00084       B.merge(NumberedAttrBuilders[*VI]);
00085 
00086     if (Function *Fn = dyn_cast<Function>(V)) {
00087       AttributeSet AS = Fn->getAttributes();
00088       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
00089       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
00090                                AS.getFnAttributes());
00091 
00092       FnAttrs.merge(B);
00093 
00094       // If the alignment was parsed as an attribute, move to the alignment
00095       // field.
00096       if (FnAttrs.hasAlignmentAttr()) {
00097         Fn->setAlignment(FnAttrs.getAlignment());
00098         FnAttrs.removeAttribute(Attribute::Alignment);
00099       }
00100 
00101       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
00102                             AttributeSet::get(Context,
00103                                               AttributeSet::FunctionIndex,
00104                                               FnAttrs));
00105       Fn->setAttributes(AS);
00106     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
00107       AttributeSet AS = CI->getAttributes();
00108       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
00109       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
00110                                AS.getFnAttributes());
00111       FnAttrs.merge(B);
00112       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
00113                             AttributeSet::get(Context,
00114                                               AttributeSet::FunctionIndex,
00115                                               FnAttrs));
00116       CI->setAttributes(AS);
00117     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
00118       AttributeSet AS = II->getAttributes();
00119       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
00120       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
00121                                AS.getFnAttributes());
00122       FnAttrs.merge(B);
00123       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
00124                             AttributeSet::get(Context,
00125                                               AttributeSet::FunctionIndex,
00126                                               FnAttrs));
00127       II->setAttributes(AS);
00128     } else {
00129       llvm_unreachable("invalid object with forward attribute group reference");
00130     }
00131   }
00132 
00133   // If there are entries in ForwardRefBlockAddresses at this point, the
00134   // function was never defined.
00135   if (!ForwardRefBlockAddresses.empty())
00136     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
00137                  "expected function name in blockaddress");
00138 
00139   for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
00140     if (NumberedTypes[i].second.isValid())
00141       return Error(NumberedTypes[i].second,
00142                    "use of undefined type '%" + Twine(i) + "'");
00143 
00144   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
00145        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
00146     if (I->second.second.isValid())
00147       return Error(I->second.second,
00148                    "use of undefined type named '" + I->getKey() + "'");
00149 
00150   if (!ForwardRefComdats.empty())
00151     return Error(ForwardRefComdats.begin()->second,
00152                  "use of undefined comdat '$" +
00153                      ForwardRefComdats.begin()->first + "'");
00154 
00155   if (!ForwardRefVals.empty())
00156     return Error(ForwardRefVals.begin()->second.second,
00157                  "use of undefined value '@" + ForwardRefVals.begin()->first +
00158                  "'");
00159 
00160   if (!ForwardRefValIDs.empty())
00161     return Error(ForwardRefValIDs.begin()->second.second,
00162                  "use of undefined value '@" +
00163                  Twine(ForwardRefValIDs.begin()->first) + "'");
00164 
00165   if (!ForwardRefMDNodes.empty())
00166     return Error(ForwardRefMDNodes.begin()->second.second,
00167                  "use of undefined metadata '!" +
00168                  Twine(ForwardRefMDNodes.begin()->first) + "'");
00169 
00170 
00171   // Look for intrinsic functions and CallInst that need to be upgraded
00172   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
00173     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
00174 
00175   UpgradeDebugInfo(*M);
00176 
00177   return false;
00178 }
00179 
00180 //===----------------------------------------------------------------------===//
00181 // Top-Level Entities
00182 //===----------------------------------------------------------------------===//
00183 
00184 bool LLParser::ParseTopLevelEntities() {
00185   while (1) {
00186     switch (Lex.getKind()) {
00187     default:         return TokError("expected top-level entity");
00188     case lltok::Eof: return false;
00189     case lltok::kw_declare: if (ParseDeclare()) return true; break;
00190     case lltok::kw_define:  if (ParseDefine()) return true; break;
00191     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
00192     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
00193     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
00194     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
00195     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
00196     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
00197     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
00198     case lltok::ComdatVar:  if (parseComdat()) return true; break;
00199     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
00200     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
00201 
00202     // The Global variable production with no name can have many different
00203     // optional leading prefixes, the production is:
00204     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00205     //               OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
00206     //               ('constant'|'global') ...
00207     case lltok::kw_private:             // OptionalLinkage
00208     case lltok::kw_internal:            // OptionalLinkage
00209     case lltok::kw_weak:                // OptionalLinkage
00210     case lltok::kw_weak_odr:            // OptionalLinkage
00211     case lltok::kw_linkonce:            // OptionalLinkage
00212     case lltok::kw_linkonce_odr:        // OptionalLinkage
00213     case lltok::kw_appending:           // OptionalLinkage
00214     case lltok::kw_common:              // OptionalLinkage
00215     case lltok::kw_extern_weak:         // OptionalLinkage
00216     case lltok::kw_external:            // OptionalLinkage
00217     case lltok::kw_default:             // OptionalVisibility
00218     case lltok::kw_hidden:              // OptionalVisibility
00219     case lltok::kw_protected:           // OptionalVisibility
00220     case lltok::kw_dllimport:           // OptionalDLLStorageClass
00221     case lltok::kw_dllexport:           // OptionalDLLStorageClass
00222     case lltok::kw_thread_local:        // OptionalThreadLocal
00223     case lltok::kw_addrspace:           // OptionalAddrSpace
00224     case lltok::kw_constant:            // GlobalType
00225     case lltok::kw_global: {            // GlobalType
00226       unsigned Linkage, Visibility, DLLStorageClass;
00227       bool UnnamedAddr;
00228       GlobalVariable::ThreadLocalMode TLM;
00229       bool HasLinkage;
00230       if (ParseOptionalLinkage(Linkage, HasLinkage) ||
00231           ParseOptionalVisibility(Visibility) ||
00232           ParseOptionalDLLStorageClass(DLLStorageClass) ||
00233           ParseOptionalThreadLocal(TLM) ||
00234           parseOptionalUnnamedAddr(UnnamedAddr) ||
00235           ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
00236                       DLLStorageClass, TLM, UnnamedAddr))
00237         return true;
00238       break;
00239     }
00240 
00241     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
00242     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
00243     case lltok::kw_uselistorder_bb:
00244                                  if (ParseUseListOrderBB()) return true; break;
00245     }
00246   }
00247 }
00248 
00249 
00250 /// toplevelentity
00251 ///   ::= 'module' 'asm' STRINGCONSTANT
00252 bool LLParser::ParseModuleAsm() {
00253   assert(Lex.getKind() == lltok::kw_module);
00254   Lex.Lex();
00255 
00256   std::string AsmStr;
00257   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
00258       ParseStringConstant(AsmStr)) return true;
00259 
00260   M->appendModuleInlineAsm(AsmStr);
00261   return false;
00262 }
00263 
00264 /// toplevelentity
00265 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
00266 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
00267 bool LLParser::ParseTargetDefinition() {
00268   assert(Lex.getKind() == lltok::kw_target);
00269   std::string Str;
00270   switch (Lex.Lex()) {
00271   default: return TokError("unknown target property");
00272   case lltok::kw_triple:
00273     Lex.Lex();
00274     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
00275         ParseStringConstant(Str))
00276       return true;
00277     M->setTargetTriple(Str);
00278     return false;
00279   case lltok::kw_datalayout:
00280     Lex.Lex();
00281     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
00282         ParseStringConstant(Str))
00283       return true;
00284     M->setDataLayout(Str);
00285     return false;
00286   }
00287 }
00288 
00289 /// toplevelentity
00290 ///   ::= 'deplibs' '=' '[' ']'
00291 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
00292 /// FIXME: Remove in 4.0. Currently parse, but ignore.
00293 bool LLParser::ParseDepLibs() {
00294   assert(Lex.getKind() == lltok::kw_deplibs);
00295   Lex.Lex();
00296   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
00297       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
00298     return true;
00299 
00300   if (EatIfPresent(lltok::rsquare))
00301     return false;
00302 
00303   do {
00304     std::string Str;
00305     if (ParseStringConstant(Str)) return true;
00306   } while (EatIfPresent(lltok::comma));
00307 
00308   return ParseToken(lltok::rsquare, "expected ']' at end of list");
00309 }
00310 
00311 /// ParseUnnamedType:
00312 ///   ::= LocalVarID '=' 'type' type
00313 bool LLParser::ParseUnnamedType() {
00314   LocTy TypeLoc = Lex.getLoc();
00315   unsigned TypeID = Lex.getUIntVal();
00316   Lex.Lex(); // eat LocalVarID;
00317 
00318   if (ParseToken(lltok::equal, "expected '=' after name") ||
00319       ParseToken(lltok::kw_type, "expected 'type' after '='"))
00320     return true;
00321 
00322   if (TypeID >= NumberedTypes.size())
00323     NumberedTypes.resize(TypeID+1);
00324 
00325   Type *Result = nullptr;
00326   if (ParseStructDefinition(TypeLoc, "",
00327                             NumberedTypes[TypeID], Result)) return true;
00328 
00329   if (!isa<StructType>(Result)) {
00330     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
00331     if (Entry.first)
00332       return Error(TypeLoc, "non-struct types may not be recursive");
00333     Entry.first = Result;
00334     Entry.second = SMLoc();
00335   }
00336 
00337   return false;
00338 }
00339 
00340 
00341 /// toplevelentity
00342 ///   ::= LocalVar '=' 'type' type
00343 bool LLParser::ParseNamedType() {
00344   std::string Name = Lex.getStrVal();
00345   LocTy NameLoc = Lex.getLoc();
00346   Lex.Lex();  // eat LocalVar.
00347 
00348   if (ParseToken(lltok::equal, "expected '=' after name") ||
00349       ParseToken(lltok::kw_type, "expected 'type' after name"))
00350     return true;
00351 
00352   Type *Result = nullptr;
00353   if (ParseStructDefinition(NameLoc, Name,
00354                             NamedTypes[Name], Result)) return true;
00355 
00356   if (!isa<StructType>(Result)) {
00357     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
00358     if (Entry.first)
00359       return Error(NameLoc, "non-struct types may not be recursive");
00360     Entry.first = Result;
00361     Entry.second = SMLoc();
00362   }
00363 
00364   return false;
00365 }
00366 
00367 
00368 /// toplevelentity
00369 ///   ::= 'declare' FunctionHeader
00370 bool LLParser::ParseDeclare() {
00371   assert(Lex.getKind() == lltok::kw_declare);
00372   Lex.Lex();
00373 
00374   Function *F;
00375   return ParseFunctionHeader(F, false);
00376 }
00377 
00378 /// toplevelentity
00379 ///   ::= 'define' FunctionHeader '{' ...
00380 bool LLParser::ParseDefine() {
00381   assert(Lex.getKind() == lltok::kw_define);
00382   Lex.Lex();
00383 
00384   Function *F;
00385   return ParseFunctionHeader(F, true) ||
00386          ParseFunctionBody(*F);
00387 }
00388 
00389 /// ParseGlobalType
00390 ///   ::= 'constant'
00391 ///   ::= 'global'
00392 bool LLParser::ParseGlobalType(bool &IsConstant) {
00393   if (Lex.getKind() == lltok::kw_constant)
00394     IsConstant = true;
00395   else if (Lex.getKind() == lltok::kw_global)
00396     IsConstant = false;
00397   else {
00398     IsConstant = false;
00399     return TokError("expected 'global' or 'constant'");
00400   }
00401   Lex.Lex();
00402   return false;
00403 }
00404 
00405 /// ParseUnnamedGlobal:
00406 ///   OptionalVisibility ALIAS ...
00407 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00408 ///                                                     ...   -> global variable
00409 ///   GlobalID '=' OptionalVisibility ALIAS ...
00410 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00411 ///                                                     ...   -> global variable
00412 bool LLParser::ParseUnnamedGlobal() {
00413   unsigned VarID = NumberedVals.size();
00414   std::string Name;
00415   LocTy NameLoc = Lex.getLoc();
00416 
00417   // Handle the GlobalID form.
00418   if (Lex.getKind() == lltok::GlobalID) {
00419     if (Lex.getUIntVal() != VarID)
00420       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
00421                    Twine(VarID) + "'");
00422     Lex.Lex(); // eat GlobalID;
00423 
00424     if (ParseToken(lltok::equal, "expected '=' after name"))
00425       return true;
00426   }
00427 
00428   bool HasLinkage;
00429   unsigned Linkage, Visibility, DLLStorageClass;
00430   GlobalVariable::ThreadLocalMode TLM;
00431   bool UnnamedAddr;
00432   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
00433       ParseOptionalVisibility(Visibility) ||
00434       ParseOptionalDLLStorageClass(DLLStorageClass) ||
00435       ParseOptionalThreadLocal(TLM) ||
00436       parseOptionalUnnamedAddr(UnnamedAddr))
00437     return true;
00438 
00439   if (Lex.getKind() != lltok::kw_alias)
00440     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
00441                        DLLStorageClass, TLM, UnnamedAddr);
00442   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
00443                     UnnamedAddr);
00444 }
00445 
00446 /// ParseNamedGlobal:
00447 ///   GlobalVar '=' OptionalVisibility ALIAS ...
00448 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00449 ///                                                     ...   -> global variable
00450 bool LLParser::ParseNamedGlobal() {
00451   assert(Lex.getKind() == lltok::GlobalVar);
00452   LocTy NameLoc = Lex.getLoc();
00453   std::string Name = Lex.getStrVal();
00454   Lex.Lex();
00455 
00456   bool HasLinkage;
00457   unsigned Linkage, Visibility, DLLStorageClass;
00458   GlobalVariable::ThreadLocalMode TLM;
00459   bool UnnamedAddr;
00460   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
00461       ParseOptionalLinkage(Linkage, HasLinkage) ||
00462       ParseOptionalVisibility(Visibility) ||
00463       ParseOptionalDLLStorageClass(DLLStorageClass) ||
00464       ParseOptionalThreadLocal(TLM) ||
00465       parseOptionalUnnamedAddr(UnnamedAddr))
00466     return true;
00467 
00468   if (Lex.getKind() != lltok::kw_alias)
00469     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
00470                        DLLStorageClass, TLM, UnnamedAddr);
00471 
00472   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
00473                     UnnamedAddr);
00474 }
00475 
00476 bool LLParser::parseComdat() {
00477   assert(Lex.getKind() == lltok::ComdatVar);
00478   std::string Name = Lex.getStrVal();
00479   LocTy NameLoc = Lex.getLoc();
00480   Lex.Lex();
00481 
00482   if (ParseToken(lltok::equal, "expected '=' here"))
00483     return true;
00484 
00485   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
00486     return TokError("expected comdat type");
00487 
00488   Comdat::SelectionKind SK;
00489   switch (Lex.getKind()) {
00490   default:
00491     return TokError("unknown selection kind");
00492   case lltok::kw_any:
00493     SK = Comdat::Any;
00494     break;
00495   case lltok::kw_exactmatch:
00496     SK = Comdat::ExactMatch;
00497     break;
00498   case lltok::kw_largest:
00499     SK = Comdat::Largest;
00500     break;
00501   case lltok::kw_noduplicates:
00502     SK = Comdat::NoDuplicates;
00503     break;
00504   case lltok::kw_samesize:
00505     SK = Comdat::SameSize;
00506     break;
00507   }
00508   Lex.Lex();
00509 
00510   // See if the comdat was forward referenced, if so, use the comdat.
00511   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
00512   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
00513   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
00514     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
00515 
00516   Comdat *C;
00517   if (I != ComdatSymTab.end())
00518     C = &I->second;
00519   else
00520     C = M->getOrInsertComdat(Name);
00521   C->setSelectionKind(SK);
00522 
00523   return false;
00524 }
00525 
00526 // MDString:
00527 //   ::= '!' STRINGCONSTANT
00528 bool LLParser::ParseMDString(MDString *&Result) {
00529   std::string Str;
00530   if (ParseStringConstant(Str)) return true;
00531   llvm::UpgradeMDStringConstant(Str);
00532   Result = MDString::get(Context, Str);
00533   return false;
00534 }
00535 
00536 // MDNode:
00537 //   ::= '!' MDNodeNumber
00538 //
00539 /// This version of ParseMDNodeID returns the slot number and null in the case
00540 /// of a forward reference.
00541 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
00542   // !{ ..., !42, ... }
00543   if (ParseUInt32(SlotNo)) return true;
00544 
00545   // Check existing MDNode.
00546   if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
00547     Result = NumberedMetadata[SlotNo];
00548   else
00549     Result = nullptr;
00550   return false;
00551 }
00552 
00553 bool LLParser::ParseMDNodeID(MDNode *&Result) {
00554   // !{ ..., !42, ... }
00555   unsigned MID = 0;
00556   if (ParseMDNodeID(Result, MID)) return true;
00557 
00558   // If not a forward reference, just return it now.
00559   if (Result) return false;
00560 
00561   // Otherwise, create MDNode forward reference.
00562   MDNode *FwdNode = MDNode::getTemporary(Context, None);
00563   ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
00564 
00565   if (NumberedMetadata.size() <= MID)
00566     NumberedMetadata.resize(MID+1);
00567   NumberedMetadata[MID] = FwdNode;
00568   Result = FwdNode;
00569   return false;
00570 }
00571 
00572 /// ParseNamedMetadata:
00573 ///   !foo = !{ !1, !2 }
00574 bool LLParser::ParseNamedMetadata() {
00575   assert(Lex.getKind() == lltok::MetadataVar);
00576   std::string Name = Lex.getStrVal();
00577   Lex.Lex();
00578 
00579   if (ParseToken(lltok::equal, "expected '=' here") ||
00580       ParseToken(lltok::exclaim, "Expected '!' here") ||
00581       ParseToken(lltok::lbrace, "Expected '{' here"))
00582     return true;
00583 
00584   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
00585   if (Lex.getKind() != lltok::rbrace)
00586     do {
00587       if (ParseToken(lltok::exclaim, "Expected '!' here"))
00588         return true;
00589 
00590       MDNode *N = nullptr;
00591       if (ParseMDNodeID(N)) return true;
00592       NMD->addOperand(N);
00593     } while (EatIfPresent(lltok::comma));
00594 
00595   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
00596     return true;
00597 
00598   return false;
00599 }
00600 
00601 /// ParseStandaloneMetadata:
00602 ///   !42 = !{...}
00603 bool LLParser::ParseStandaloneMetadata() {
00604   assert(Lex.getKind() == lltok::exclaim);
00605   Lex.Lex();
00606   unsigned MetadataID = 0;
00607 
00608   LocTy TyLoc;
00609   Type *Ty = nullptr;
00610   SmallVector<Value *, 16> Elts;
00611   if (ParseUInt32(MetadataID) ||
00612       ParseToken(lltok::equal, "expected '=' here") ||
00613       ParseType(Ty, TyLoc) ||
00614       ParseToken(lltok::exclaim, "Expected '!' here") ||
00615       ParseToken(lltok::lbrace, "Expected '{' here") ||
00616       ParseMDNodeVector(Elts, nullptr) ||
00617       ParseToken(lltok::rbrace, "expected end of metadata node"))
00618     return true;
00619 
00620   MDNode *Init = MDNode::get(Context, Elts);
00621 
00622   // See if this was forward referenced, if so, handle it.
00623   std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
00624     FI = ForwardRefMDNodes.find(MetadataID);
00625   if (FI != ForwardRefMDNodes.end()) {
00626     MDNode *Temp = FI->second.first;
00627     Temp->replaceAllUsesWith(Init);
00628     MDNode::deleteTemporary(Temp);
00629     ForwardRefMDNodes.erase(FI);
00630 
00631     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
00632   } else {
00633     if (MetadataID >= NumberedMetadata.size())
00634       NumberedMetadata.resize(MetadataID+1);
00635 
00636     if (NumberedMetadata[MetadataID] != nullptr)
00637       return TokError("Metadata id is already used");
00638     NumberedMetadata[MetadataID] = Init;
00639   }
00640 
00641   return false;
00642 }
00643 
00644 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
00645   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
00646          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
00647 }
00648 
00649 /// ParseAlias:
00650 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
00651 ///                     OptionalDLLStorageClass OptionalThreadLocal
00652 ///                     OptionalUnNammedAddr 'alias' Aliasee
00653 ///
00654 /// Aliasee
00655 ///   ::= TypeAndValue
00656 ///
00657 /// Everything through OptionalUnNammedAddr has already been parsed.
00658 ///
00659 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
00660                           unsigned Visibility, unsigned DLLStorageClass,
00661                           GlobalVariable::ThreadLocalMode TLM,
00662                           bool UnnamedAddr) {
00663   assert(Lex.getKind() == lltok::kw_alias);
00664   Lex.Lex();
00665 
00666   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
00667 
00668   if(!GlobalAlias::isValidLinkage(Linkage))
00669     return Error(NameLoc, "invalid linkage type for alias");
00670 
00671   if (!isValidVisibilityForLinkage(Visibility, L))
00672     return Error(NameLoc,
00673                  "symbol with local linkage must have default visibility");
00674 
00675   Constant *Aliasee;
00676   LocTy AliaseeLoc = Lex.getLoc();
00677   if (Lex.getKind() != lltok::kw_bitcast &&
00678       Lex.getKind() != lltok::kw_getelementptr &&
00679       Lex.getKind() != lltok::kw_addrspacecast &&
00680       Lex.getKind() != lltok::kw_inttoptr) {
00681     if (ParseGlobalTypeAndValue(Aliasee))
00682       return true;
00683   } else {
00684     // The bitcast dest type is not present, it is implied by the dest type.
00685     ValID ID;
00686     if (ParseValID(ID))
00687       return true;
00688     if (ID.Kind != ValID::t_Constant)
00689       return Error(AliaseeLoc, "invalid aliasee");
00690     Aliasee = ID.ConstantVal;
00691   }
00692 
00693   Type *AliaseeType = Aliasee->getType();
00694   auto *PTy = dyn_cast<PointerType>(AliaseeType);
00695   if (!PTy)
00696     return Error(AliaseeLoc, "An alias must have pointer type");
00697   Type *Ty = PTy->getElementType();
00698   unsigned AddrSpace = PTy->getAddressSpace();
00699 
00700   // Okay, create the alias but do not insert it into the module yet.
00701   std::unique_ptr<GlobalAlias> GA(
00702       GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
00703                           Name, Aliasee, /*Parent*/ nullptr));
00704   GA->setThreadLocalMode(TLM);
00705   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
00706   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
00707   GA->setUnnamedAddr(UnnamedAddr);
00708 
00709   // See if this value already exists in the symbol table.  If so, it is either
00710   // a redefinition or a definition of a forward reference.
00711   if (GlobalValue *Val = M->getNamedValue(Name)) {
00712     // See if this was a redefinition.  If so, there is no entry in
00713     // ForwardRefVals.
00714     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
00715       I = ForwardRefVals.find(Name);
00716     if (I == ForwardRefVals.end())
00717       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
00718 
00719     // Otherwise, this was a definition of forward ref.  Verify that types
00720     // agree.
00721     if (Val->getType() != GA->getType())
00722       return Error(NameLoc,
00723               "forward reference and definition of alias have different types");
00724 
00725     // If they agree, just RAUW the old value with the alias and remove the
00726     // forward ref info.
00727     Val->replaceAllUsesWith(GA.get());
00728     Val->eraseFromParent();
00729     ForwardRefVals.erase(I);
00730   }
00731 
00732   // Insert into the module, we know its name won't collide now.
00733   M->getAliasList().push_back(GA.get());
00734   assert(GA->getName() == Name && "Should not be a name conflict!");
00735 
00736   // The module owns this now
00737   GA.release();
00738 
00739   return false;
00740 }
00741 
00742 /// ParseGlobal
00743 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00744 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
00745 ///       OptionalExternallyInitialized GlobalType Type Const
00746 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
00747 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
00748 ///       OptionalExternallyInitialized GlobalType Type Const
00749 ///
00750 /// Everything up to and including OptionalUnNammedAddr has been parsed
00751 /// already.
00752 ///
00753 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
00754                            unsigned Linkage, bool HasLinkage,
00755                            unsigned Visibility, unsigned DLLStorageClass,
00756                            GlobalVariable::ThreadLocalMode TLM,
00757                            bool UnnamedAddr) {
00758   if (!isValidVisibilityForLinkage(Visibility, Linkage))
00759     return Error(NameLoc,
00760                  "symbol with local linkage must have default visibility");
00761 
00762   unsigned AddrSpace;
00763   bool IsConstant, IsExternallyInitialized;
00764   LocTy IsExternallyInitializedLoc;
00765   LocTy TyLoc;
00766 
00767   Type *Ty = nullptr;
00768   if (ParseOptionalAddrSpace(AddrSpace) ||
00769       ParseOptionalToken(lltok::kw_externally_initialized,
00770                          IsExternallyInitialized,
00771                          &IsExternallyInitializedLoc) ||
00772       ParseGlobalType(IsConstant) ||
00773       ParseType(Ty, TyLoc))
00774     return true;
00775 
00776   // If the linkage is specified and is external, then no initializer is
00777   // present.
00778   Constant *Init = nullptr;
00779   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
00780                       Linkage != GlobalValue::ExternalLinkage)) {
00781     if (ParseGlobalValue(Ty, Init))
00782       return true;
00783   }
00784 
00785   if (Ty->isFunctionTy() || Ty->isLabelTy())
00786     return Error(TyLoc, "invalid type for global variable");
00787 
00788   GlobalVariable *GV = nullptr;
00789 
00790   // See if the global was forward referenced, if so, use the global.
00791   if (!Name.empty()) {
00792     if (GlobalValue *GVal = M->getNamedValue(Name)) {
00793       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
00794         return Error(NameLoc, "redefinition of global '@" + Name + "'");
00795       GV = cast<GlobalVariable>(GVal);
00796     }
00797   } else {
00798     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
00799       I = ForwardRefValIDs.find(NumberedVals.size());
00800     if (I != ForwardRefValIDs.end()) {
00801       GV = cast<GlobalVariable>(I->second.first);
00802       ForwardRefValIDs.erase(I);
00803     }
00804   }
00805 
00806   if (!GV) {
00807     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
00808                             Name, nullptr, GlobalVariable::NotThreadLocal,
00809                             AddrSpace);
00810   } else {
00811     if (GV->getType()->getElementType() != Ty)
00812       return Error(TyLoc,
00813             "forward reference and definition of global have different types");
00814 
00815     // Move the forward-reference to the correct spot in the module.
00816     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
00817   }
00818 
00819   if (Name.empty())
00820     NumberedVals.push_back(GV);
00821 
00822   // Set the parsed properties on the global.
00823   if (Init)
00824     GV->setInitializer(Init);
00825   GV->setConstant(IsConstant);
00826   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
00827   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
00828   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
00829   GV->setExternallyInitialized(IsExternallyInitialized);
00830   GV->setThreadLocalMode(TLM);
00831   GV->setUnnamedAddr(UnnamedAddr);
00832 
00833   // Parse attributes on the global.
00834   while (Lex.getKind() == lltok::comma) {
00835     Lex.Lex();
00836 
00837     if (Lex.getKind() == lltok::kw_section) {
00838       Lex.Lex();
00839       GV->setSection(Lex.getStrVal());
00840       if (ParseToken(lltok::StringConstant, "expected global section string"))
00841         return true;
00842     } else if (Lex.getKind() == lltok::kw_align) {
00843       unsigned Alignment;
00844       if (ParseOptionalAlignment(Alignment)) return true;
00845       GV->setAlignment(Alignment);
00846     } else {
00847       Comdat *C;
00848       if (parseOptionalComdat(C))
00849         return true;
00850       if (C)
00851         GV->setComdat(C);
00852       else
00853         return TokError("unknown global variable property!");
00854     }
00855   }
00856 
00857   return false;
00858 }
00859 
00860 /// ParseUnnamedAttrGrp
00861 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
00862 bool LLParser::ParseUnnamedAttrGrp() {
00863   assert(Lex.getKind() == lltok::kw_attributes);
00864   LocTy AttrGrpLoc = Lex.getLoc();
00865   Lex.Lex();
00866 
00867   assert(Lex.getKind() == lltok::AttrGrpID);
00868   unsigned VarID = Lex.getUIntVal();
00869   std::vector<unsigned> unused;
00870   LocTy BuiltinLoc;
00871   Lex.Lex();
00872 
00873   if (ParseToken(lltok::equal, "expected '=' here") ||
00874       ParseToken(lltok::lbrace, "expected '{' here") ||
00875       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
00876                                  BuiltinLoc) ||
00877       ParseToken(lltok::rbrace, "expected end of attribute group"))
00878     return true;
00879 
00880   if (!NumberedAttrBuilders[VarID].hasAttributes())
00881     return Error(AttrGrpLoc, "attribute group has no attributes");
00882 
00883   return false;
00884 }
00885 
00886 /// ParseFnAttributeValuePairs
00887 ///   ::= <attr> | <attr> '=' <value>
00888 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
00889                                           std::vector<unsigned> &FwdRefAttrGrps,
00890                                           bool inAttrGrp, LocTy &BuiltinLoc) {
00891   bool HaveError = false;
00892 
00893   B.clear();
00894 
00895   while (true) {
00896     lltok::Kind Token = Lex.getKind();
00897     if (Token == lltok::kw_builtin)
00898       BuiltinLoc = Lex.getLoc();
00899     switch (Token) {
00900     default:
00901       if (!inAttrGrp) return HaveError;
00902       return Error(Lex.getLoc(), "unterminated attribute group");
00903     case lltok::rbrace:
00904       // Finished.
00905       return false;
00906 
00907     case lltok::AttrGrpID: {
00908       // Allow a function to reference an attribute group:
00909       //
00910       //   define void @foo() #1 { ... }
00911       if (inAttrGrp)
00912         HaveError |=
00913           Error(Lex.getLoc(),
00914               "cannot have an attribute group reference in an attribute group");
00915 
00916       unsigned AttrGrpNum = Lex.getUIntVal();
00917       if (inAttrGrp) break;
00918 
00919       // Save the reference to the attribute group. We'll fill it in later.
00920       FwdRefAttrGrps.push_back(AttrGrpNum);
00921       break;
00922     }
00923     // Target-dependent attributes:
00924     case lltok::StringConstant: {
00925       std::string Attr = Lex.getStrVal();
00926       Lex.Lex();
00927       std::string Val;
00928       if (EatIfPresent(lltok::equal) &&
00929           ParseStringConstant(Val))
00930         return true;
00931 
00932       B.addAttribute(Attr, Val);
00933       continue;
00934     }
00935 
00936     // Target-independent attributes:
00937     case lltok::kw_align: {
00938       // As a hack, we allow function alignment to be initially parsed as an
00939       // attribute on a function declaration/definition or added to an attribute
00940       // group and later moved to the alignment field.
00941       unsigned Alignment;
00942       if (inAttrGrp) {
00943         Lex.Lex();
00944         if (ParseToken(lltok::equal, "expected '=' here") ||
00945             ParseUInt32(Alignment))
00946           return true;
00947       } else {
00948         if (ParseOptionalAlignment(Alignment))
00949           return true;
00950       }
00951       B.addAlignmentAttr(Alignment);
00952       continue;
00953     }
00954     case lltok::kw_alignstack: {
00955       unsigned Alignment;
00956       if (inAttrGrp) {
00957         Lex.Lex();
00958         if (ParseToken(lltok::equal, "expected '=' here") ||
00959             ParseUInt32(Alignment))
00960           return true;
00961       } else {
00962         if (ParseOptionalStackAlignment(Alignment))
00963           return true;
00964       }
00965       B.addStackAlignmentAttr(Alignment);
00966       continue;
00967     }
00968     case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
00969     case lltok::kw_builtin:           B.addAttribute(Attribute::Builtin); break;
00970     case lltok::kw_cold:              B.addAttribute(Attribute::Cold); break;
00971     case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
00972     case lltok::kw_jumptable:         B.addAttribute(Attribute::JumpTable); break;
00973     case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
00974     case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
00975     case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
00976     case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
00977     case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
00978     case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
00979     case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
00980     case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
00981     case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
00982     case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
00983     case lltok::kw_optnone:           B.addAttribute(Attribute::OptimizeNone); break;
00984     case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
00985     case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
00986     case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
00987     case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
00988     case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
00989     case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
00990     case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
00991     case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
00992     case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
00993     case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
00994     case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
00995 
00996     // Error handling.
00997     case lltok::kw_inreg:
00998     case lltok::kw_signext:
00999     case lltok::kw_zeroext:
01000       HaveError |=
01001         Error(Lex.getLoc(),
01002               "invalid use of attribute on a function");
01003       break;
01004     case lltok::kw_byval:
01005     case lltok::kw_dereferenceable:
01006     case lltok::kw_inalloca:
01007     case lltok::kw_nest:
01008     case lltok::kw_noalias:
01009     case lltok::kw_nocapture:
01010     case lltok::kw_nonnull:
01011     case lltok::kw_returned:
01012     case lltok::kw_sret:
01013       HaveError |=
01014         Error(Lex.getLoc(),
01015               "invalid use of parameter-only attribute on a function");
01016       break;
01017     }
01018 
01019     Lex.Lex();
01020   }
01021 }
01022 
01023 //===----------------------------------------------------------------------===//
01024 // GlobalValue Reference/Resolution Routines.
01025 //===----------------------------------------------------------------------===//
01026 
01027 /// GetGlobalVal - Get a value with the specified name or ID, creating a
01028 /// forward reference record if needed.  This can return null if the value
01029 /// exists but does not have the right type.
01030 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
01031                                     LocTy Loc) {
01032   PointerType *PTy = dyn_cast<PointerType>(Ty);
01033   if (!PTy) {
01034     Error(Loc, "global variable reference must have pointer type");
01035     return nullptr;
01036   }
01037 
01038   // Look this name up in the normal function symbol table.
01039   GlobalValue *Val =
01040     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
01041 
01042   // If this is a forward reference for the value, see if we already created a
01043   // forward ref record.
01044   if (!Val) {
01045     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
01046       I = ForwardRefVals.find(Name);
01047     if (I != ForwardRefVals.end())
01048       Val = I->second.first;
01049   }
01050 
01051   // If we have the value in the symbol table or fwd-ref table, return it.
01052   if (Val) {
01053     if (Val->getType() == Ty) return Val;
01054     Error(Loc, "'@" + Name + "' defined with type '" +
01055           getTypeString(Val->getType()) + "'");
01056     return nullptr;
01057   }
01058 
01059   // Otherwise, create a new forward reference for this value and remember it.
01060   GlobalValue *FwdVal;
01061   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
01062     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
01063   else
01064     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
01065                                 GlobalValue::ExternalWeakLinkage, nullptr, Name,
01066                                 nullptr, GlobalVariable::NotThreadLocal,
01067                                 PTy->getAddressSpace());
01068 
01069   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
01070   return FwdVal;
01071 }
01072 
01073 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
01074   PointerType *PTy = dyn_cast<PointerType>(Ty);
01075   if (!PTy) {
01076     Error(Loc, "global variable reference must have pointer type");
01077     return nullptr;
01078   }
01079 
01080   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
01081 
01082   // If this is a forward reference for the value, see if we already created a
01083   // forward ref record.
01084   if (!Val) {
01085     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
01086       I = ForwardRefValIDs.find(ID);
01087     if (I != ForwardRefValIDs.end())
01088       Val = I->second.first;
01089   }
01090 
01091   // If we have the value in the symbol table or fwd-ref table, return it.
01092   if (Val) {
01093     if (Val->getType() == Ty) return Val;
01094     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
01095           getTypeString(Val->getType()) + "'");
01096     return nullptr;
01097   }
01098 
01099   // Otherwise, create a new forward reference for this value and remember it.
01100   GlobalValue *FwdVal;
01101   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
01102     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
01103   else
01104     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
01105                                 GlobalValue::ExternalWeakLinkage, nullptr, "");
01106 
01107   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
01108   return FwdVal;
01109 }
01110 
01111 
01112 //===----------------------------------------------------------------------===//
01113 // Comdat Reference/Resolution Routines.
01114 //===----------------------------------------------------------------------===//
01115 
01116 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
01117   // Look this name up in the comdat symbol table.
01118   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
01119   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
01120   if (I != ComdatSymTab.end())
01121     return &I->second;
01122 
01123   // Otherwise, create a new forward reference for this value and remember it.
01124   Comdat *C = M->getOrInsertComdat(Name);
01125   ForwardRefComdats[Name] = Loc;
01126   return C;
01127 }
01128 
01129 
01130 //===----------------------------------------------------------------------===//
01131 // Helper Routines.
01132 //===----------------------------------------------------------------------===//
01133 
01134 /// ParseToken - If the current token has the specified kind, eat it and return
01135 /// success.  Otherwise, emit the specified error and return failure.
01136 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
01137   if (Lex.getKind() != T)
01138     return TokError(ErrMsg);
01139   Lex.Lex();
01140   return false;
01141 }
01142 
01143 /// ParseStringConstant
01144 ///   ::= StringConstant
01145 bool LLParser::ParseStringConstant(std::string &Result) {
01146   if (Lex.getKind() != lltok::StringConstant)
01147     return TokError("expected string constant");
01148   Result = Lex.getStrVal();
01149   Lex.Lex();
01150   return false;
01151 }
01152 
01153 /// ParseUInt32
01154 ///   ::= uint32
01155 bool LLParser::ParseUInt32(unsigned &Val) {
01156   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
01157     return TokError("expected integer");
01158   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
01159   if (Val64 != unsigned(Val64))
01160     return TokError("expected 32-bit integer (too large)");
01161   Val = Val64;
01162   Lex.Lex();
01163   return false;
01164 }
01165 
01166 /// ParseUInt64
01167 ///   ::= uint64
01168 bool LLParser::ParseUInt64(uint64_t &Val) {
01169   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
01170     return TokError("expected integer");
01171   Val = Lex.getAPSIntVal().getLimitedValue();
01172   Lex.Lex();
01173   return false;
01174 }
01175 
01176 /// ParseTLSModel
01177 ///   := 'localdynamic'
01178 ///   := 'initialexec'
01179 ///   := 'localexec'
01180 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
01181   switch (Lex.getKind()) {
01182     default:
01183       return TokError("expected localdynamic, initialexec or localexec");
01184     case lltok::kw_localdynamic:
01185       TLM = GlobalVariable::LocalDynamicTLSModel;
01186       break;
01187     case lltok::kw_initialexec:
01188       TLM = GlobalVariable::InitialExecTLSModel;
01189       break;
01190     case lltok::kw_localexec:
01191       TLM = GlobalVariable::LocalExecTLSModel;
01192       break;
01193   }
01194 
01195   Lex.Lex();
01196   return false;
01197 }
01198 
01199 /// ParseOptionalThreadLocal
01200 ///   := /*empty*/
01201 ///   := 'thread_local'
01202 ///   := 'thread_local' '(' tlsmodel ')'
01203 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
01204   TLM = GlobalVariable::NotThreadLocal;
01205   if (!EatIfPresent(lltok::kw_thread_local))
01206     return false;
01207 
01208   TLM = GlobalVariable::GeneralDynamicTLSModel;
01209   if (Lex.getKind() == lltok::lparen) {
01210     Lex.Lex();
01211     return ParseTLSModel(TLM) ||
01212       ParseToken(lltok::rparen, "expected ')' after thread local model");
01213   }
01214   return false;
01215 }
01216 
01217 /// ParseOptionalAddrSpace
01218 ///   := /*empty*/
01219 ///   := 'addrspace' '(' uint32 ')'
01220 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
01221   AddrSpace = 0;
01222   if (!EatIfPresent(lltok::kw_addrspace))
01223     return false;
01224   return ParseToken(lltok::lparen, "expected '(' in address space") ||
01225          ParseUInt32(AddrSpace) ||
01226          ParseToken(lltok::rparen, "expected ')' in address space");
01227 }
01228 
01229 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
01230 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
01231   bool HaveError = false;
01232 
01233   B.clear();
01234 
01235   while (1) {
01236     lltok::Kind Token = Lex.getKind();
01237     switch (Token) {
01238     default:  // End of attributes.
01239       return HaveError;
01240     case lltok::kw_align: {
01241       unsigned Alignment;
01242       if (ParseOptionalAlignment(Alignment))
01243         return true;
01244       B.addAlignmentAttr(Alignment);
01245       continue;
01246     }
01247     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
01248     case lltok::kw_dereferenceable: {
01249       uint64_t Bytes;
01250       if (ParseOptionalDereferenceableBytes(Bytes))
01251         return true;
01252       B.addDereferenceableAttr(Bytes);
01253       continue;
01254     }
01255     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
01256     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
01257     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
01258     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
01259     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
01260     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
01261     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
01262     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
01263     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
01264     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
01265     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
01266     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
01267 
01268     case lltok::kw_alignstack:
01269     case lltok::kw_alwaysinline:
01270     case lltok::kw_builtin:
01271     case lltok::kw_inlinehint:
01272     case lltok::kw_jumptable:
01273     case lltok::kw_minsize:
01274     case lltok::kw_naked:
01275     case lltok::kw_nobuiltin:
01276     case lltok::kw_noduplicate:
01277     case lltok::kw_noimplicitfloat:
01278     case lltok::kw_noinline:
01279     case lltok::kw_nonlazybind:
01280     case lltok::kw_noredzone:
01281     case lltok::kw_noreturn:
01282     case lltok::kw_nounwind:
01283     case lltok::kw_optnone:
01284     case lltok::kw_optsize:
01285     case lltok::kw_returns_twice:
01286     case lltok::kw_sanitize_address:
01287     case lltok::kw_sanitize_memory:
01288     case lltok::kw_sanitize_thread:
01289     case lltok::kw_ssp:
01290     case lltok::kw_sspreq:
01291     case lltok::kw_sspstrong:
01292     case lltok::kw_uwtable:
01293       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
01294       break;
01295     }
01296 
01297     Lex.Lex();
01298   }
01299 }
01300 
01301 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
01302 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
01303   bool HaveError = false;
01304 
01305   B.clear();
01306 
01307   while (1) {
01308     lltok::Kind Token = Lex.getKind();
01309     switch (Token) {
01310     default:  // End of attributes.
01311       return HaveError;
01312     case lltok::kw_dereferenceable: {
01313       uint64_t Bytes;
01314       if (ParseOptionalDereferenceableBytes(Bytes))
01315         return true;
01316       B.addDereferenceableAttr(Bytes);
01317       continue;
01318     }
01319     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
01320     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
01321     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
01322     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
01323     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
01324 
01325     // Error handling.
01326     case lltok::kw_align:
01327     case lltok::kw_byval:
01328     case lltok::kw_inalloca:
01329     case lltok::kw_nest:
01330     case lltok::kw_nocapture:
01331     case lltok::kw_returned:
01332     case lltok::kw_sret:
01333       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
01334       break;
01335 
01336     case lltok::kw_alignstack:
01337     case lltok::kw_alwaysinline:
01338     case lltok::kw_builtin:
01339     case lltok::kw_cold:
01340     case lltok::kw_inlinehint:
01341     case lltok::kw_jumptable:
01342     case lltok::kw_minsize:
01343     case lltok::kw_naked:
01344     case lltok::kw_nobuiltin:
01345     case lltok::kw_noduplicate:
01346     case lltok::kw_noimplicitfloat:
01347     case lltok::kw_noinline:
01348     case lltok::kw_nonlazybind:
01349     case lltok::kw_noredzone:
01350     case lltok::kw_noreturn:
01351     case lltok::kw_nounwind:
01352     case lltok::kw_optnone:
01353     case lltok::kw_optsize:
01354     case lltok::kw_returns_twice:
01355     case lltok::kw_sanitize_address:
01356     case lltok::kw_sanitize_memory:
01357     case lltok::kw_sanitize_thread:
01358     case lltok::kw_ssp:
01359     case lltok::kw_sspreq:
01360     case lltok::kw_sspstrong:
01361     case lltok::kw_uwtable:
01362       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
01363       break;
01364 
01365     case lltok::kw_readnone:
01366     case lltok::kw_readonly:
01367       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
01368     }
01369 
01370     Lex.Lex();
01371   }
01372 }
01373 
01374 /// ParseOptionalLinkage
01375 ///   ::= /*empty*/
01376 ///   ::= 'private'
01377 ///   ::= 'internal'
01378 ///   ::= 'weak'
01379 ///   ::= 'weak_odr'
01380 ///   ::= 'linkonce'
01381 ///   ::= 'linkonce_odr'
01382 ///   ::= 'available_externally'
01383 ///   ::= 'appending'
01384 ///   ::= 'common'
01385 ///   ::= 'extern_weak'
01386 ///   ::= 'external'
01387 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
01388   HasLinkage = false;
01389   switch (Lex.getKind()) {
01390   default:                       Res=GlobalValue::ExternalLinkage; return false;
01391   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
01392   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
01393   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
01394   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
01395   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
01396   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
01397   case lltok::kw_available_externally:
01398     Res = GlobalValue::AvailableExternallyLinkage;
01399     break;
01400   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
01401   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
01402   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
01403   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
01404   }
01405   Lex.Lex();
01406   HasLinkage = true;
01407   return false;
01408 }
01409 
01410 /// ParseOptionalVisibility
01411 ///   ::= /*empty*/
01412 ///   ::= 'default'
01413 ///   ::= 'hidden'
01414 ///   ::= 'protected'
01415 ///
01416 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
01417   switch (Lex.getKind()) {
01418   default:                  Res = GlobalValue::DefaultVisibility; return false;
01419   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
01420   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
01421   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
01422   }
01423   Lex.Lex();
01424   return false;
01425 }
01426 
01427 /// ParseOptionalDLLStorageClass
01428 ///   ::= /*empty*/
01429 ///   ::= 'dllimport'
01430 ///   ::= 'dllexport'
01431 ///
01432 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
01433   switch (Lex.getKind()) {
01434   default:                  Res = GlobalValue::DefaultStorageClass; return false;
01435   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
01436   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
01437   }
01438   Lex.Lex();
01439   return false;
01440 }
01441 
01442 /// ParseOptionalCallingConv
01443 ///   ::= /*empty*/
01444 ///   ::= 'ccc'
01445 ///   ::= 'fastcc'
01446 ///   ::= 'kw_intel_ocl_bicc'
01447 ///   ::= 'coldcc'
01448 ///   ::= 'x86_stdcallcc'
01449 ///   ::= 'x86_fastcallcc'
01450 ///   ::= 'x86_thiscallcc'
01451 ///   ::= 'arm_apcscc'
01452 ///   ::= 'arm_aapcscc'
01453 ///   ::= 'arm_aapcs_vfpcc'
01454 ///   ::= 'msp430_intrcc'
01455 ///   ::= 'ptx_kernel'
01456 ///   ::= 'ptx_device'
01457 ///   ::= 'spir_func'
01458 ///   ::= 'spir_kernel'
01459 ///   ::= 'x86_64_sysvcc'
01460 ///   ::= 'x86_64_win64cc'
01461 ///   ::= 'webkit_jscc'
01462 ///   ::= 'anyregcc'
01463 ///   ::= 'preserve_mostcc'
01464 ///   ::= 'preserve_allcc'
01465 ///   ::= 'cc' UINT
01466 ///
01467 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
01468   switch (Lex.getKind()) {
01469   default:                       CC = CallingConv::C; return false;
01470   case lltok::kw_ccc:            CC = CallingConv::C; break;
01471   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
01472   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
01473   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
01474   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
01475   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
01476   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
01477   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
01478   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
01479   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
01480   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
01481   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
01482   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
01483   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
01484   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
01485   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
01486   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
01487   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
01488   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
01489   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
01490   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
01491   case lltok::kw_cc: {
01492       Lex.Lex();
01493       return ParseUInt32(CC);
01494     }
01495   }
01496 
01497   Lex.Lex();
01498   return false;
01499 }
01500 
01501 /// ParseInstructionMetadata
01502 ///   ::= !dbg !42 (',' !dbg !57)*
01503 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
01504                                         PerFunctionState *PFS) {
01505   do {
01506     if (Lex.getKind() != lltok::MetadataVar)
01507       return TokError("expected metadata after comma");
01508 
01509     std::string Name = Lex.getStrVal();
01510     unsigned MDK = M->getMDKindID(Name);
01511     Lex.Lex();
01512 
01513     MDNode *Node;
01514     SMLoc Loc = Lex.getLoc();
01515 
01516     if (ParseToken(lltok::exclaim, "expected '!' here"))
01517       return true;
01518 
01519     // This code is similar to that of ParseMetadataValue, however it needs to
01520     // have special-case code for a forward reference; see the comments on
01521     // ForwardRefInstMetadata for details. Also, MDStrings are not supported
01522     // at the top level here.
01523     if (Lex.getKind() == lltok::lbrace) {
01524       ValID ID;
01525       if (ParseMetadataListValue(ID, PFS))
01526         return true;
01527       assert(ID.Kind == ValID::t_MDNode);
01528       Inst->setMetadata(MDK, ID.MDNodeVal);
01529     } else {
01530       unsigned NodeID = 0;
01531       if (ParseMDNodeID(Node, NodeID))
01532         return true;
01533       if (Node) {
01534         // If we got the node, add it to the instruction.
01535         Inst->setMetadata(MDK, Node);
01536       } else {
01537         MDRef R = { Loc, MDK, NodeID };
01538         // Otherwise, remember that this should be resolved later.
01539         ForwardRefInstMetadata[Inst].push_back(R);
01540       }
01541     }
01542 
01543     if (MDK == LLVMContext::MD_tbaa)
01544       InstsWithTBAATag.push_back(Inst);
01545 
01546     // If this is the end of the list, we're done.
01547   } while (EatIfPresent(lltok::comma));
01548   return false;
01549 }
01550 
01551 /// ParseOptionalAlignment
01552 ///   ::= /* empty */
01553 ///   ::= 'align' 4
01554 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
01555   Alignment = 0;
01556   if (!EatIfPresent(lltok::kw_align))
01557     return false;
01558   LocTy AlignLoc = Lex.getLoc();
01559   if (ParseUInt32(Alignment)) return true;
01560   if (!isPowerOf2_32(Alignment))
01561     return Error(AlignLoc, "alignment is not a power of two");
01562   if (Alignment > Value::MaximumAlignment)
01563     return Error(AlignLoc, "huge alignments are not supported yet");
01564   return false;
01565 }
01566 
01567 /// ParseOptionalDereferenceableBytes
01568 ///   ::= /* empty */
01569 ///   ::= 'dereferenceable' '(' 4 ')'
01570 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
01571   Bytes = 0;
01572   if (!EatIfPresent(lltok::kw_dereferenceable))
01573     return false;
01574   LocTy ParenLoc = Lex.getLoc();
01575   if (!EatIfPresent(lltok::lparen))
01576     return Error(ParenLoc, "expected '('");
01577   LocTy DerefLoc = Lex.getLoc();
01578   if (ParseUInt64(Bytes)) return true;
01579   ParenLoc = Lex.getLoc();
01580   if (!EatIfPresent(lltok::rparen))
01581     return Error(ParenLoc, "expected ')'");
01582   if (!Bytes)
01583     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
01584   return false;
01585 }
01586 
01587 /// ParseOptionalCommaAlign
01588 ///   ::=
01589 ///   ::= ',' align 4
01590 ///
01591 /// This returns with AteExtraComma set to true if it ate an excess comma at the
01592 /// end.
01593 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
01594                                        bool &AteExtraComma) {
01595   AteExtraComma = false;
01596   while (EatIfPresent(lltok::comma)) {
01597     // Metadata at the end is an early exit.
01598     if (Lex.getKind() == lltok::MetadataVar) {
01599       AteExtraComma = true;
01600       return false;
01601     }
01602 
01603     if (Lex.getKind() != lltok::kw_align)
01604       return Error(Lex.getLoc(), "expected metadata or 'align'");
01605 
01606     if (ParseOptionalAlignment(Alignment)) return true;
01607   }
01608 
01609   return false;
01610 }
01611 
01612 /// ParseScopeAndOrdering
01613 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
01614 ///   else: ::=
01615 ///
01616 /// This sets Scope and Ordering to the parsed values.
01617 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
01618                                      AtomicOrdering &Ordering) {
01619   if (!isAtomic)
01620     return false;
01621 
01622   Scope = CrossThread;
01623   if (EatIfPresent(lltok::kw_singlethread))
01624     Scope = SingleThread;
01625 
01626   return ParseOrdering(Ordering);
01627 }
01628 
01629 /// ParseOrdering
01630 ///   ::= AtomicOrdering
01631 ///
01632 /// This sets Ordering to the parsed value.
01633 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
01634   switch (Lex.getKind()) {
01635   default: return TokError("Expected ordering on atomic instruction");
01636   case lltok::kw_unordered: Ordering = Unordered; break;
01637   case lltok::kw_monotonic: Ordering = Monotonic; break;
01638   case lltok::kw_acquire: Ordering = Acquire; break;
01639   case lltok::kw_release: Ordering = Release; break;
01640   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
01641   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
01642   }
01643   Lex.Lex();
01644   return false;
01645 }
01646 
01647 /// ParseOptionalStackAlignment
01648 ///   ::= /* empty */
01649 ///   ::= 'alignstack' '(' 4 ')'
01650 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
01651   Alignment = 0;
01652   if (!EatIfPresent(lltok::kw_alignstack))
01653     return false;
01654   LocTy ParenLoc = Lex.getLoc();
01655   if (!EatIfPresent(lltok::lparen))
01656     return Error(ParenLoc, "expected '('");
01657   LocTy AlignLoc = Lex.getLoc();
01658   if (ParseUInt32(Alignment)) return true;
01659   ParenLoc = Lex.getLoc();
01660   if (!EatIfPresent(lltok::rparen))
01661     return Error(ParenLoc, "expected ')'");
01662   if (!isPowerOf2_32(Alignment))
01663     return Error(AlignLoc, "stack alignment is not a power of two");
01664   return false;
01665 }
01666 
01667 /// ParseIndexList - This parses the index list for an insert/extractvalue
01668 /// instruction.  This sets AteExtraComma in the case where we eat an extra
01669 /// comma at the end of the line and find that it is followed by metadata.
01670 /// Clients that don't allow metadata can call the version of this function that
01671 /// only takes one argument.
01672 ///
01673 /// ParseIndexList
01674 ///    ::=  (',' uint32)+
01675 ///
01676 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
01677                               bool &AteExtraComma) {
01678   AteExtraComma = false;
01679 
01680   if (Lex.getKind() != lltok::comma)
01681     return TokError("expected ',' as start of index list");
01682 
01683   while (EatIfPresent(lltok::comma)) {
01684     if (Lex.getKind() == lltok::MetadataVar) {
01685       AteExtraComma = true;
01686       return false;
01687     }
01688     unsigned Idx = 0;
01689     if (ParseUInt32(Idx)) return true;
01690     Indices.push_back(Idx);
01691   }
01692 
01693   return false;
01694 }
01695 
01696 //===----------------------------------------------------------------------===//
01697 // Type Parsing.
01698 //===----------------------------------------------------------------------===//
01699 
01700 /// ParseType - Parse a type.
01701 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
01702   SMLoc TypeLoc = Lex.getLoc();
01703   switch (Lex.getKind()) {
01704   default:
01705     return TokError("expected type");
01706   case lltok::Type:
01707     // Type ::= 'float' | 'void' (etc)
01708     Result = Lex.getTyVal();
01709     Lex.Lex();
01710     break;
01711   case lltok::lbrace:
01712     // Type ::= StructType
01713     if (ParseAnonStructType(Result, false))
01714       return true;
01715     break;
01716   case lltok::lsquare:
01717     // Type ::= '[' ... ']'
01718     Lex.Lex(); // eat the lsquare.
01719     if (ParseArrayVectorType(Result, false))
01720       return true;
01721     break;
01722   case lltok::less: // Either vector or packed struct.
01723     // Type ::= '<' ... '>'
01724     Lex.Lex();
01725     if (Lex.getKind() == lltok::lbrace) {
01726       if (ParseAnonStructType(Result, true) ||
01727           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
01728         return true;
01729     } else if (ParseArrayVectorType(Result, true))
01730       return true;
01731     break;
01732   case lltok::LocalVar: {
01733     // Type ::= %foo
01734     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
01735 
01736     // If the type hasn't been defined yet, create a forward definition and
01737     // remember where that forward def'n was seen (in case it never is defined).
01738     if (!Entry.first) {
01739       Entry.first = StructType::create(Context, Lex.getStrVal());
01740       Entry.second = Lex.getLoc();
01741     }
01742     Result = Entry.first;
01743     Lex.Lex();
01744     break;
01745   }
01746 
01747   case lltok::LocalVarID: {
01748     // Type ::= %4
01749     if (Lex.getUIntVal() >= NumberedTypes.size())
01750       NumberedTypes.resize(Lex.getUIntVal()+1);
01751     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
01752 
01753     // If the type hasn't been defined yet, create a forward definition and
01754     // remember where that forward def'n was seen (in case it never is defined).
01755     if (!Entry.first) {
01756       Entry.first = StructType::create(Context);
01757       Entry.second = Lex.getLoc();
01758     }
01759     Result = Entry.first;
01760     Lex.Lex();
01761     break;
01762   }
01763   }
01764 
01765   // Parse the type suffixes.
01766   while (1) {
01767     switch (Lex.getKind()) {
01768     // End of type.
01769     default:
01770       if (!AllowVoid && Result->isVoidTy())
01771         return Error(TypeLoc, "void type only allowed for function results");
01772       return false;
01773 
01774     // Type ::= Type '*'
01775     case lltok::star:
01776       if (Result->isLabelTy())
01777         return TokError("basic block pointers are invalid");
01778       if (Result->isVoidTy())
01779         return TokError("pointers to void are invalid - use i8* instead");
01780       if (!PointerType::isValidElementType(Result))
01781         return TokError("pointer to this type is invalid");
01782       Result = PointerType::getUnqual(Result);
01783       Lex.Lex();
01784       break;
01785 
01786     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
01787     case lltok::kw_addrspace: {
01788       if (Result->isLabelTy())
01789         return TokError("basic block pointers are invalid");
01790       if (Result->isVoidTy())
01791         return TokError("pointers to void are invalid; use i8* instead");
01792       if (!PointerType::isValidElementType(Result))
01793         return TokError("pointer to this type is invalid");
01794       unsigned AddrSpace;
01795       if (ParseOptionalAddrSpace(AddrSpace) ||
01796           ParseToken(lltok::star, "expected '*' in address space"))
01797         return true;
01798 
01799       Result = PointerType::get(Result, AddrSpace);
01800       break;
01801     }
01802 
01803     /// Types '(' ArgTypeListI ')' OptFuncAttrs
01804     case lltok::lparen:
01805       if (ParseFunctionType(Result))
01806         return true;
01807       break;
01808     }
01809   }
01810 }
01811 
01812 /// ParseParameterList
01813 ///    ::= '(' ')'
01814 ///    ::= '(' Arg (',' Arg)* ')'
01815 ///  Arg
01816 ///    ::= Type OptionalAttributes Value OptionalAttributes
01817 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
01818                                   PerFunctionState &PFS, bool IsMustTailCall,
01819                                   bool InVarArgsFunc) {
01820   if (ParseToken(lltok::lparen, "expected '(' in call"))
01821     return true;
01822 
01823   unsigned AttrIndex = 1;
01824   while (Lex.getKind() != lltok::rparen) {
01825     // If this isn't the first argument, we need a comma.
01826     if (!ArgList.empty() &&
01827         ParseToken(lltok::comma, "expected ',' in argument list"))
01828       return true;
01829 
01830     // Parse an ellipsis if this is a musttail call in a variadic function.
01831     if (Lex.getKind() == lltok::dotdotdot) {
01832       const char *Msg = "unexpected ellipsis in argument list for ";
01833       if (!IsMustTailCall)
01834         return TokError(Twine(Msg) + "non-musttail call");
01835       if (!InVarArgsFunc)
01836         return TokError(Twine(Msg) + "musttail call in non-varargs function");
01837       Lex.Lex();  // Lex the '...', it is purely for readability.
01838       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
01839     }
01840 
01841     // Parse the argument.
01842     LocTy ArgLoc;
01843     Type *ArgTy = nullptr;
01844     AttrBuilder ArgAttrs;
01845     Value *V;
01846     if (ParseType(ArgTy, ArgLoc))
01847       return true;
01848 
01849     // Otherwise, handle normal operands.
01850     if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
01851       return true;
01852     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
01853                                                              AttrIndex++,
01854                                                              ArgAttrs)));
01855   }
01856 
01857   if (IsMustTailCall && InVarArgsFunc)
01858     return TokError("expected '...' at end of argument list for musttail call "
01859                     "in varargs function");
01860 
01861   Lex.Lex();  // Lex the ')'.
01862   return false;
01863 }
01864 
01865 
01866 
01867 /// ParseArgumentList - Parse the argument list for a function type or function
01868 /// prototype.
01869 ///   ::= '(' ArgTypeListI ')'
01870 /// ArgTypeListI
01871 ///   ::= /*empty*/
01872 ///   ::= '...'
01873 ///   ::= ArgTypeList ',' '...'
01874 ///   ::= ArgType (',' ArgType)*
01875 ///
01876 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
01877                                  bool &isVarArg){
01878   isVarArg = false;
01879   assert(Lex.getKind() == lltok::lparen);
01880   Lex.Lex(); // eat the (.
01881 
01882   if (Lex.getKind() == lltok::rparen) {
01883     // empty
01884   } else if (Lex.getKind() == lltok::dotdotdot) {
01885     isVarArg = true;
01886     Lex.Lex();
01887   } else {
01888     LocTy TypeLoc = Lex.getLoc();
01889     Type *ArgTy = nullptr;
01890     AttrBuilder Attrs;
01891     std::string Name;
01892 
01893     if (ParseType(ArgTy) ||
01894         ParseOptionalParamAttrs(Attrs)) return true;
01895 
01896     if (ArgTy->isVoidTy())
01897       return Error(TypeLoc, "argument can not have void type");
01898 
01899     if (Lex.getKind() == lltok::LocalVar) {
01900       Name = Lex.getStrVal();
01901       Lex.Lex();
01902     }
01903 
01904     if (!FunctionType::isValidArgumentType(ArgTy))
01905       return Error(TypeLoc, "invalid type for function argument");
01906 
01907     unsigned AttrIndex = 1;
01908     ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
01909                               AttributeSet::get(ArgTy->getContext(),
01910                                                 AttrIndex++, Attrs), Name));
01911 
01912     while (EatIfPresent(lltok::comma)) {
01913       // Handle ... at end of arg list.
01914       if (EatIfPresent(lltok::dotdotdot)) {
01915         isVarArg = true;
01916         break;
01917       }
01918 
01919       // Otherwise must be an argument type.
01920       TypeLoc = Lex.getLoc();
01921       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
01922 
01923       if (ArgTy->isVoidTy())
01924         return Error(TypeLoc, "argument can not have void type");
01925 
01926       if (Lex.getKind() == lltok::LocalVar) {
01927         Name = Lex.getStrVal();
01928         Lex.Lex();
01929       } else {
01930         Name = "";
01931       }
01932 
01933       if (!ArgTy->isFirstClassType())
01934         return Error(TypeLoc, "invalid type for function argument");
01935 
01936       ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
01937                                 AttributeSet::get(ArgTy->getContext(),
01938                                                   AttrIndex++, Attrs),
01939                                 Name));
01940     }
01941   }
01942 
01943   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
01944 }
01945 
01946 /// ParseFunctionType
01947 ///  ::= Type ArgumentList OptionalAttrs
01948 bool LLParser::ParseFunctionType(Type *&Result) {
01949   assert(Lex.getKind() == lltok::lparen);
01950 
01951   if (!FunctionType::isValidReturnType(Result))
01952     return TokError("invalid function return type");
01953 
01954   SmallVector<ArgInfo, 8> ArgList;
01955   bool isVarArg;
01956   if (ParseArgumentList(ArgList, isVarArg))
01957     return true;
01958 
01959   // Reject names on the arguments lists.
01960   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
01961     if (!ArgList[i].Name.empty())
01962       return Error(ArgList[i].Loc, "argument name invalid in function type");
01963     if (ArgList[i].Attrs.hasAttributes(i + 1))
01964       return Error(ArgList[i].Loc,
01965                    "argument attributes invalid in function type");
01966   }
01967 
01968   SmallVector<Type*, 16> ArgListTy;
01969   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
01970     ArgListTy.push_back(ArgList[i].Ty);
01971 
01972   Result = FunctionType::get(Result, ArgListTy, isVarArg);
01973   return false;
01974 }
01975 
01976 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
01977 /// other structs.
01978 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
01979   SmallVector<Type*, 8> Elts;
01980   if (ParseStructBody(Elts)) return true;
01981 
01982   Result = StructType::get(Context, Elts, Packed);
01983   return false;
01984 }
01985 
01986 /// ParseStructDefinition - Parse a struct in a 'type' definition.
01987 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
01988                                      std::pair<Type*, LocTy> &Entry,
01989                                      Type *&ResultTy) {
01990   // If the type was already defined, diagnose the redefinition.
01991   if (Entry.first && !Entry.second.isValid())
01992     return Error(TypeLoc, "redefinition of type");
01993 
01994   // If we have opaque, just return without filling in the definition for the
01995   // struct.  This counts as a definition as far as the .ll file goes.
01996   if (EatIfPresent(lltok::kw_opaque)) {
01997     // This type is being defined, so clear the location to indicate this.
01998     Entry.second = SMLoc();
01999 
02000     // If this type number has never been uttered, create it.
02001     if (!Entry.first)
02002       Entry.first = StructType::create(Context, Name);
02003     ResultTy = Entry.first;
02004     return false;
02005   }
02006 
02007   // If the type starts with '<', then it is either a packed struct or a vector.
02008   bool isPacked = EatIfPresent(lltok::less);
02009 
02010   // If we don't have a struct, then we have a random type alias, which we
02011   // accept for compatibility with old files.  These types are not allowed to be
02012   // forward referenced and not allowed to be recursive.
02013   if (Lex.getKind() != lltok::lbrace) {
02014     if (Entry.first)
02015       return Error(TypeLoc, "forward references to non-struct type");
02016 
02017     ResultTy = nullptr;
02018     if (isPacked)
02019       return ParseArrayVectorType(ResultTy, true);
02020     return ParseType(ResultTy);
02021   }
02022 
02023   // This type is being defined, so clear the location to indicate this.
02024   Entry.second = SMLoc();
02025 
02026   // If this type number has never been uttered, create it.
02027   if (!Entry.first)
02028     Entry.first = StructType::create(Context, Name);
02029 
02030   StructType *STy = cast<StructType>(Entry.first);
02031 
02032   SmallVector<Type*, 8> Body;
02033   if (ParseStructBody(Body) ||
02034       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
02035     return true;
02036 
02037   STy->setBody(Body, isPacked);
02038   ResultTy = STy;
02039   return false;
02040 }
02041 
02042 
02043 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
02044 ///   StructType
02045 ///     ::= '{' '}'
02046 ///     ::= '{' Type (',' Type)* '}'
02047 ///     ::= '<' '{' '}' '>'
02048 ///     ::= '<' '{' Type (',' Type)* '}' '>'
02049 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
02050   assert(Lex.getKind() == lltok::lbrace);
02051   Lex.Lex(); // Consume the '{'
02052 
02053   // Handle the empty struct.
02054   if (EatIfPresent(lltok::rbrace))
02055     return false;
02056 
02057   LocTy EltTyLoc = Lex.getLoc();
02058   Type *Ty = nullptr;
02059   if (ParseType(Ty)) return true;
02060   Body.push_back(Ty);
02061 
02062   if (!StructType::isValidElementType(Ty))
02063     return Error(EltTyLoc, "invalid element type for struct");
02064 
02065   while (EatIfPresent(lltok::comma)) {
02066     EltTyLoc = Lex.getLoc();
02067     if (ParseType(Ty)) return true;
02068 
02069     if (!StructType::isValidElementType(Ty))
02070       return Error(EltTyLoc, "invalid element type for struct");
02071 
02072     Body.push_back(Ty);
02073   }
02074 
02075   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
02076 }
02077 
02078 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
02079 /// token has already been consumed.
02080 ///   Type
02081 ///     ::= '[' APSINTVAL 'x' Types ']'
02082 ///     ::= '<' APSINTVAL 'x' Types '>'
02083 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
02084   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
02085       Lex.getAPSIntVal().getBitWidth() > 64)
02086     return TokError("expected number in address space");
02087 
02088   LocTy SizeLoc = Lex.getLoc();
02089   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
02090   Lex.Lex();
02091 
02092   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
02093       return true;
02094 
02095   LocTy TypeLoc = Lex.getLoc();
02096   Type *EltTy = nullptr;
02097   if (ParseType(EltTy)) return true;
02098 
02099   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
02100                  "expected end of sequential type"))
02101     return true;
02102 
02103   if (isVector) {
02104     if (Size == 0)
02105       return Error(SizeLoc, "zero element vector is illegal");
02106     if ((unsigned)Size != Size)
02107       return Error(SizeLoc, "size too large for vector");
02108     if (!VectorType::isValidElementType(EltTy))
02109       return Error(TypeLoc, "invalid vector element type");
02110     Result = VectorType::get(EltTy, unsigned(Size));
02111   } else {
02112     if (!ArrayType::isValidElementType(EltTy))
02113       return Error(TypeLoc, "invalid array element type");
02114     Result = ArrayType::get(EltTy, Size);
02115   }
02116   return false;
02117 }
02118 
02119 //===----------------------------------------------------------------------===//
02120 // Function Semantic Analysis.
02121 //===----------------------------------------------------------------------===//
02122 
02123 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
02124                                              int functionNumber)
02125   : P(p), F(f), FunctionNumber(functionNumber) {
02126 
02127   // Insert unnamed arguments into the NumberedVals list.
02128   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
02129        AI != E; ++AI)
02130     if (!AI->hasName())
02131       NumberedVals.push_back(AI);
02132 }
02133 
02134 LLParser::PerFunctionState::~PerFunctionState() {
02135   // If there were any forward referenced non-basicblock values, delete them.
02136   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
02137        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
02138     if (!isa<BasicBlock>(I->second.first)) {
02139       I->second.first->replaceAllUsesWith(
02140                            UndefValue::get(I->second.first->getType()));
02141       delete I->second.first;
02142       I->second.first = nullptr;
02143     }
02144 
02145   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
02146        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
02147     if (!isa<BasicBlock>(I->second.first)) {
02148       I->second.first->replaceAllUsesWith(
02149                            UndefValue::get(I->second.first->getType()));
02150       delete I->second.first;
02151       I->second.first = nullptr;
02152     }
02153 }
02154 
02155 bool LLParser::PerFunctionState::FinishFunction() {
02156   if (!ForwardRefVals.empty())
02157     return P.Error(ForwardRefVals.begin()->second.second,
02158                    "use of undefined value '%" + ForwardRefVals.begin()->first +
02159                    "'");
02160   if (!ForwardRefValIDs.empty())
02161     return P.Error(ForwardRefValIDs.begin()->second.second,
02162                    "use of undefined value '%" +
02163                    Twine(ForwardRefValIDs.begin()->first) + "'");
02164   return false;
02165 }
02166 
02167 
02168 /// GetVal - Get a value with the specified name or ID, creating a
02169 /// forward reference record if needed.  This can return null if the value
02170 /// exists but does not have the right type.
02171 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
02172                                           Type *Ty, LocTy Loc) {
02173   // Look this name up in the normal function symbol table.
02174   Value *Val = F.getValueSymbolTable().lookup(Name);
02175 
02176   // If this is a forward reference for the value, see if we already created a
02177   // forward ref record.
02178   if (!Val) {
02179     std::map<std::string, std::pair<Value*, LocTy> >::iterator
02180       I = ForwardRefVals.find(Name);
02181     if (I != ForwardRefVals.end())
02182       Val = I->second.first;
02183   }
02184 
02185   // If we have the value in the symbol table or fwd-ref table, return it.
02186   if (Val) {
02187     if (Val->getType() == Ty) return Val;
02188     if (Ty->isLabelTy())
02189       P.Error(Loc, "'%" + Name + "' is not a basic block");
02190     else
02191       P.Error(Loc, "'%" + Name + "' defined with type '" +
02192               getTypeString(Val->getType()) + "'");
02193     return nullptr;
02194   }
02195 
02196   // Don't make placeholders with invalid type.
02197   if (!Ty->isFirstClassType()) {
02198     P.Error(Loc, "invalid use of a non-first-class type");
02199     return nullptr;
02200   }
02201 
02202   // Otherwise, create a new forward reference for this value and remember it.
02203   Value *FwdVal;
02204   if (Ty->isLabelTy())
02205     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
02206   else
02207     FwdVal = new Argument(Ty, Name);
02208 
02209   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
02210   return FwdVal;
02211 }
02212 
02213 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
02214                                           LocTy Loc) {
02215   // Look this name up in the normal function symbol table.
02216   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
02217 
02218   // If this is a forward reference for the value, see if we already created a
02219   // forward ref record.
02220   if (!Val) {
02221     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
02222       I = ForwardRefValIDs.find(ID);
02223     if (I != ForwardRefValIDs.end())
02224       Val = I->second.first;
02225   }
02226 
02227   // If we have the value in the symbol table or fwd-ref table, return it.
02228   if (Val) {
02229     if (Val->getType() == Ty) return Val;
02230     if (Ty->isLabelTy())
02231       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
02232     else
02233       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
02234               getTypeString(Val->getType()) + "'");
02235     return nullptr;
02236   }
02237 
02238   if (!Ty->isFirstClassType()) {
02239     P.Error(Loc, "invalid use of a non-first-class type");
02240     return nullptr;
02241   }
02242 
02243   // Otherwise, create a new forward reference for this value and remember it.
02244   Value *FwdVal;
02245   if (Ty->isLabelTy())
02246     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
02247   else
02248     FwdVal = new Argument(Ty);
02249 
02250   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
02251   return FwdVal;
02252 }
02253 
02254 /// SetInstName - After an instruction is parsed and inserted into its
02255 /// basic block, this installs its name.
02256 bool LLParser::PerFunctionState::SetInstName(int NameID,
02257                                              const std::string &NameStr,
02258                                              LocTy NameLoc, Instruction *Inst) {
02259   // If this instruction has void type, it cannot have a name or ID specified.
02260   if (Inst->getType()->isVoidTy()) {
02261     if (NameID != -1 || !NameStr.empty())
02262       return P.Error(NameLoc, "instructions returning void cannot have a name");
02263     return false;
02264   }
02265 
02266   // If this was a numbered instruction, verify that the instruction is the
02267   // expected value and resolve any forward references.
02268   if (NameStr.empty()) {
02269     // If neither a name nor an ID was specified, just use the next ID.
02270     if (NameID == -1)
02271       NameID = NumberedVals.size();
02272 
02273     if (unsigned(NameID) != NumberedVals.size())
02274       return P.Error(NameLoc, "instruction expected to be numbered '%" +
02275                      Twine(NumberedVals.size()) + "'");
02276 
02277     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
02278       ForwardRefValIDs.find(NameID);
02279     if (FI != ForwardRefValIDs.end()) {
02280       if (FI->second.first->getType() != Inst->getType())
02281         return P.Error(NameLoc, "instruction forward referenced with type '" +
02282                        getTypeString(FI->second.first->getType()) + "'");
02283       FI->second.first->replaceAllUsesWith(Inst);
02284       delete FI->second.first;
02285       ForwardRefValIDs.erase(FI);
02286     }
02287 
02288     NumberedVals.push_back(Inst);
02289     return false;
02290   }
02291 
02292   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
02293   std::map<std::string, std::pair<Value*, LocTy> >::iterator
02294     FI = ForwardRefVals.find(NameStr);
02295   if (FI != ForwardRefVals.end()) {
02296     if (FI->second.first->getType() != Inst->getType())
02297       return P.Error(NameLoc, "instruction forward referenced with type '" +
02298                      getTypeString(FI->second.first->getType()) + "'");
02299     FI->second.first->replaceAllUsesWith(Inst);
02300     delete FI->second.first;
02301     ForwardRefVals.erase(FI);
02302   }
02303 
02304   // Set the name on the instruction.
02305   Inst->setName(NameStr);
02306 
02307   if (Inst->getName() != NameStr)
02308     return P.Error(NameLoc, "multiple definition of local value named '" +
02309                    NameStr + "'");
02310   return false;
02311 }
02312 
02313 /// GetBB - Get a basic block with the specified name or ID, creating a
02314 /// forward reference record if needed.
02315 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
02316                                               LocTy Loc) {
02317   return cast_or_null<BasicBlock>(GetVal(Name,
02318                                         Type::getLabelTy(F.getContext()), Loc));
02319 }
02320 
02321 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
02322   return cast_or_null<BasicBlock>(GetVal(ID,
02323                                         Type::getLabelTy(F.getContext()), Loc));
02324 }
02325 
02326 /// DefineBB - Define the specified basic block, which is either named or
02327 /// unnamed.  If there is an error, this returns null otherwise it returns
02328 /// the block being defined.
02329 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
02330                                                  LocTy Loc) {
02331   BasicBlock *BB;
02332   if (Name.empty())
02333     BB = GetBB(NumberedVals.size(), Loc);
02334   else
02335     BB = GetBB(Name, Loc);
02336   if (!BB) return nullptr; // Already diagnosed error.
02337 
02338   // Move the block to the end of the function.  Forward ref'd blocks are
02339   // inserted wherever they happen to be referenced.
02340   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
02341 
02342   // Remove the block from forward ref sets.
02343   if (Name.empty()) {
02344     ForwardRefValIDs.erase(NumberedVals.size());
02345     NumberedVals.push_back(BB);
02346   } else {
02347     // BB forward references are already in the function symbol table.
02348     ForwardRefVals.erase(Name);
02349   }
02350 
02351   return BB;
02352 }
02353 
02354 //===----------------------------------------------------------------------===//
02355 // Constants.
02356 //===----------------------------------------------------------------------===//
02357 
02358 /// ParseValID - Parse an abstract value that doesn't necessarily have a
02359 /// type implied.  For example, if we parse "4" we don't know what integer type
02360 /// it has.  The value will later be combined with its type and checked for
02361 /// sanity.  PFS is used to convert function-local operands of metadata (since
02362 /// metadata operands are not just parsed here but also converted to values).
02363 /// PFS can be null when we are not parsing metadata values inside a function.
02364 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
02365   ID.Loc = Lex.getLoc();
02366   switch (Lex.getKind()) {
02367   default: return TokError("expected value token");
02368   case lltok::GlobalID:  // @42
02369     ID.UIntVal = Lex.getUIntVal();
02370     ID.Kind = ValID::t_GlobalID;
02371     break;
02372   case lltok::GlobalVar:  // @foo
02373     ID.StrVal = Lex.getStrVal();
02374     ID.Kind = ValID::t_GlobalName;
02375     break;
02376   case lltok::LocalVarID:  // %42
02377     ID.UIntVal = Lex.getUIntVal();
02378     ID.Kind = ValID::t_LocalID;
02379     break;
02380   case lltok::LocalVar:  // %foo
02381     ID.StrVal = Lex.getStrVal();
02382     ID.Kind = ValID::t_LocalName;
02383     break;
02384   case lltok::exclaim:   // !42, !{...}, or !"foo"
02385     return ParseMetadataValue(ID, PFS);
02386   case lltok::APSInt:
02387     ID.APSIntVal = Lex.getAPSIntVal();
02388     ID.Kind = ValID::t_APSInt;
02389     break;
02390   case lltok::APFloat:
02391     ID.APFloatVal = Lex.getAPFloatVal();
02392     ID.Kind = ValID::t_APFloat;
02393     break;
02394   case lltok::kw_true:
02395     ID.ConstantVal = ConstantInt::getTrue(Context);
02396     ID.Kind = ValID::t_Constant;
02397     break;
02398   case lltok::kw_false:
02399     ID.ConstantVal = ConstantInt::getFalse(Context);
02400     ID.Kind = ValID::t_Constant;
02401     break;
02402   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
02403   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
02404   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
02405 
02406   case lltok::lbrace: {
02407     // ValID ::= '{' ConstVector '}'
02408     Lex.Lex();
02409     SmallVector<Constant*, 16> Elts;
02410     if (ParseGlobalValueVector(Elts) ||
02411         ParseToken(lltok::rbrace, "expected end of struct constant"))
02412       return true;
02413 
02414     ID.ConstantStructElts = new Constant*[Elts.size()];
02415     ID.UIntVal = Elts.size();
02416     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
02417     ID.Kind = ValID::t_ConstantStruct;
02418     return false;
02419   }
02420   case lltok::less: {
02421     // ValID ::= '<' ConstVector '>'         --> Vector.
02422     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
02423     Lex.Lex();
02424     bool isPackedStruct = EatIfPresent(lltok::lbrace);
02425 
02426     SmallVector<Constant*, 16> Elts;
02427     LocTy FirstEltLoc = Lex.getLoc();
02428     if (ParseGlobalValueVector(Elts) ||
02429         (isPackedStruct &&
02430          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
02431         ParseToken(lltok::greater, "expected end of constant"))
02432       return true;
02433 
02434     if (isPackedStruct) {
02435       ID.ConstantStructElts = new Constant*[Elts.size()];
02436       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
02437       ID.UIntVal = Elts.size();
02438       ID.Kind = ValID::t_PackedConstantStruct;
02439       return false;
02440     }
02441 
02442     if (Elts.empty())
02443       return Error(ID.Loc, "constant vector must not be empty");
02444 
02445     if (!Elts[0]->getType()->isIntegerTy() &&
02446         !Elts[0]->getType()->isFloatingPointTy() &&
02447         !Elts[0]->getType()->isPointerTy())
02448       return Error(FirstEltLoc,
02449             "vector elements must have integer, pointer or floating point type");
02450 
02451     // Verify that all the vector elements have the same type.
02452     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
02453       if (Elts[i]->getType() != Elts[0]->getType())
02454         return Error(FirstEltLoc,
02455                      "vector element #" + Twine(i) +
02456                     " is not of type '" + getTypeString(Elts[0]->getType()));
02457 
02458     ID.ConstantVal = ConstantVector::get(Elts);
02459     ID.Kind = ValID::t_Constant;
02460     return false;
02461   }
02462   case lltok::lsquare: {   // Array Constant
02463     Lex.Lex();
02464     SmallVector<Constant*, 16> Elts;
02465     LocTy FirstEltLoc = Lex.getLoc();
02466     if (ParseGlobalValueVector(Elts) ||
02467         ParseToken(lltok::rsquare, "expected end of array constant"))
02468       return true;
02469 
02470     // Handle empty element.
02471     if (Elts.empty()) {
02472       // Use undef instead of an array because it's inconvenient to determine
02473       // the element type at this point, there being no elements to examine.
02474       ID.Kind = ValID::t_EmptyArray;
02475       return false;
02476     }
02477 
02478     if (!Elts[0]->getType()->isFirstClassType())
02479       return Error(FirstEltLoc, "invalid array element type: " +
02480                    getTypeString(Elts[0]->getType()));
02481 
02482     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
02483 
02484     // Verify all elements are correct type!
02485     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
02486       if (Elts[i]->getType() != Elts[0]->getType())
02487         return Error(FirstEltLoc,
02488                      "array element #" + Twine(i) +
02489                      " is not of type '" + getTypeString(Elts[0]->getType()));
02490     }
02491 
02492     ID.ConstantVal = ConstantArray::get(ATy, Elts);
02493     ID.Kind = ValID::t_Constant;
02494     return false;
02495   }
02496   case lltok::kw_c:  // c "foo"
02497     Lex.Lex();
02498     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
02499                                                   false);
02500     if (ParseToken(lltok::StringConstant, "expected string")) return true;
02501     ID.Kind = ValID::t_Constant;
02502     return false;
02503 
02504   case lltok::kw_asm: {
02505     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
02506     //             STRINGCONSTANT
02507     bool HasSideEffect, AlignStack, AsmDialect;
02508     Lex.Lex();
02509     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
02510         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
02511         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
02512         ParseStringConstant(ID.StrVal) ||
02513         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
02514         ParseToken(lltok::StringConstant, "expected constraint string"))
02515       return true;
02516     ID.StrVal2 = Lex.getStrVal();
02517     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
02518       (unsigned(AsmDialect)<<2);
02519     ID.Kind = ValID::t_InlineAsm;
02520     return false;
02521   }
02522 
02523   case lltok::kw_blockaddress: {
02524     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
02525     Lex.Lex();
02526 
02527     ValID Fn, Label;
02528 
02529     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
02530         ParseValID(Fn) ||
02531         ParseToken(lltok::comma, "expected comma in block address expression")||
02532         ParseValID(Label) ||
02533         ParseToken(lltok::rparen, "expected ')' in block address expression"))
02534       return true;
02535 
02536     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
02537       return Error(Fn.Loc, "expected function name in blockaddress");
02538     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
02539       return Error(Label.Loc, "expected basic block name in blockaddress");
02540 
02541     // Try to find the function (but skip it if it's forward-referenced).
02542     GlobalValue *GV = nullptr;
02543     if (Fn.Kind == ValID::t_GlobalID) {
02544       if (Fn.UIntVal < NumberedVals.size())
02545         GV = NumberedVals[Fn.UIntVal];
02546     } else if (!ForwardRefVals.count(Fn.StrVal)) {
02547       GV = M->getNamedValue(Fn.StrVal);
02548     }
02549     Function *F = nullptr;
02550     if (GV) {
02551       // Confirm that it's actually a function with a definition.
02552       if (!isa<Function>(GV))
02553         return Error(Fn.Loc, "expected function name in blockaddress");
02554       F = cast<Function>(GV);
02555       if (F->isDeclaration())
02556         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
02557     }
02558 
02559     if (!F) {
02560       // Make a global variable as a placeholder for this reference.
02561       GlobalValue *&FwdRef = ForwardRefBlockAddresses[Fn][Label];
02562       if (!FwdRef)
02563         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
02564                                     GlobalValue::InternalLinkage, nullptr, "");
02565       ID.ConstantVal = FwdRef;
02566       ID.Kind = ValID::t_Constant;
02567       return false;
02568     }
02569 
02570     // We found the function; now find the basic block.  Don't use PFS, since we
02571     // might be inside a constant expression.
02572     BasicBlock *BB;
02573     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
02574       if (Label.Kind == ValID::t_LocalID)
02575         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
02576       else
02577         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
02578       if (!BB)
02579         return Error(Label.Loc, "referenced value is not a basic block");
02580     } else {
02581       if (Label.Kind == ValID::t_LocalID)
02582         return Error(Label.Loc, "cannot take address of numeric label after "
02583                                 "the function is defined");
02584       BB = dyn_cast_or_null<BasicBlock>(
02585           F->getValueSymbolTable().lookup(Label.StrVal));
02586       if (!BB)
02587         return Error(Label.Loc, "referenced value is not a basic block");
02588     }
02589 
02590     ID.ConstantVal = BlockAddress::get(F, BB);
02591     ID.Kind = ValID::t_Constant;
02592     return false;
02593   }
02594 
02595   case lltok::kw_trunc:
02596   case lltok::kw_zext:
02597   case lltok::kw_sext:
02598   case lltok::kw_fptrunc:
02599   case lltok::kw_fpext:
02600   case lltok::kw_bitcast:
02601   case lltok::kw_addrspacecast:
02602   case lltok::kw_uitofp:
02603   case lltok::kw_sitofp:
02604   case lltok::kw_fptoui:
02605   case lltok::kw_fptosi:
02606   case lltok::kw_inttoptr:
02607   case lltok::kw_ptrtoint: {
02608     unsigned Opc = Lex.getUIntVal();
02609     Type *DestTy = nullptr;
02610     Constant *SrcVal;
02611     Lex.Lex();
02612     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
02613         ParseGlobalTypeAndValue(SrcVal) ||
02614         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
02615         ParseType(DestTy) ||
02616         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
02617       return true;
02618     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
02619       return Error(ID.Loc, "invalid cast opcode for cast from '" +
02620                    getTypeString(SrcVal->getType()) + "' to '" +
02621                    getTypeString(DestTy) + "'");
02622     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
02623                                                  SrcVal, DestTy);
02624     ID.Kind = ValID::t_Constant;
02625     return false;
02626   }
02627   case lltok::kw_extractvalue: {
02628     Lex.Lex();
02629     Constant *Val;
02630     SmallVector<unsigned, 4> Indices;
02631     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
02632         ParseGlobalTypeAndValue(Val) ||
02633         ParseIndexList(Indices) ||
02634         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
02635       return true;
02636 
02637     if (!Val->getType()->isAggregateType())
02638       return Error(ID.Loc, "extractvalue operand must be aggregate type");
02639     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
02640       return Error(ID.Loc, "invalid indices for extractvalue");
02641     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
02642     ID.Kind = ValID::t_Constant;
02643     return false;
02644   }
02645   case lltok::kw_insertvalue: {
02646     Lex.Lex();
02647     Constant *Val0, *Val1;
02648     SmallVector<unsigned, 4> Indices;
02649     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
02650         ParseGlobalTypeAndValue(Val0) ||
02651         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
02652         ParseGlobalTypeAndValue(Val1) ||
02653         ParseIndexList(Indices) ||
02654         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
02655       return true;
02656     if (!Val0->getType()->isAggregateType())
02657       return Error(ID.Loc, "insertvalue operand must be aggregate type");
02658     if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
02659       return Error(ID.Loc, "invalid indices for insertvalue");
02660     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
02661     ID.Kind = ValID::t_Constant;
02662     return false;
02663   }
02664   case lltok::kw_icmp:
02665   case lltok::kw_fcmp: {
02666     unsigned PredVal, Opc = Lex.getUIntVal();
02667     Constant *Val0, *Val1;
02668     Lex.Lex();
02669     if (ParseCmpPredicate(PredVal, Opc) ||
02670         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
02671         ParseGlobalTypeAndValue(Val0) ||
02672         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
02673         ParseGlobalTypeAndValue(Val1) ||
02674         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
02675       return true;
02676 
02677     if (Val0->getType() != Val1->getType())
02678       return Error(ID.Loc, "compare operands must have the same type");
02679 
02680     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
02681 
02682     if (Opc == Instruction::FCmp) {
02683       if (!Val0->getType()->isFPOrFPVectorTy())
02684         return Error(ID.Loc, "fcmp requires floating point operands");
02685       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
02686     } else {
02687       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
02688       if (!Val0->getType()->isIntOrIntVectorTy() &&
02689           !Val0->getType()->getScalarType()->isPointerTy())
02690         return Error(ID.Loc, "icmp requires pointer or integer operands");
02691       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
02692     }
02693     ID.Kind = ValID::t_Constant;
02694     return false;
02695   }
02696 
02697   // Binary Operators.
02698   case lltok::kw_add:
02699   case lltok::kw_fadd:
02700   case lltok::kw_sub:
02701   case lltok::kw_fsub:
02702   case lltok::kw_mul:
02703   case lltok::kw_fmul:
02704   case lltok::kw_udiv:
02705   case lltok::kw_sdiv:
02706   case lltok::kw_fdiv:
02707   case lltok::kw_urem:
02708   case lltok::kw_srem:
02709   case lltok::kw_frem:
02710   case lltok::kw_shl:
02711   case lltok::kw_lshr:
02712   case lltok::kw_ashr: {
02713     bool NUW = false;
02714     bool NSW = false;
02715     bool Exact = false;
02716     unsigned Opc = Lex.getUIntVal();
02717     Constant *Val0, *Val1;
02718     Lex.Lex();
02719     LocTy ModifierLoc = Lex.getLoc();
02720     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
02721         Opc == Instruction::Mul || Opc == Instruction::Shl) {
02722       if (EatIfPresent(lltok::kw_nuw))
02723         NUW = true;
02724       if (EatIfPresent(lltok::kw_nsw)) {
02725         NSW = true;
02726         if (EatIfPresent(lltok::kw_nuw))
02727           NUW = true;
02728       }
02729     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
02730                Opc == Instruction::LShr || Opc == Instruction::AShr) {
02731       if (EatIfPresent(lltok::kw_exact))
02732         Exact = true;
02733     }
02734     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
02735         ParseGlobalTypeAndValue(Val0) ||
02736         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
02737         ParseGlobalTypeAndValue(Val1) ||
02738         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
02739       return true;
02740     if (Val0->getType() != Val1->getType())
02741       return Error(ID.Loc, "operands of constexpr must have same type");
02742     if (!Val0->getType()->isIntOrIntVectorTy()) {
02743       if (NUW)
02744         return Error(ModifierLoc, "nuw only applies to integer operations");
02745       if (NSW)
02746         return Error(ModifierLoc, "nsw only applies to integer operations");
02747     }
02748     // Check that the type is valid for the operator.
02749     switch (Opc) {
02750     case Instruction::Add:
02751     case Instruction::Sub:
02752     case Instruction::Mul:
02753     case Instruction::UDiv:
02754     case Instruction::SDiv:
02755     case Instruction::URem:
02756     case Instruction::SRem:
02757     case Instruction::Shl:
02758     case Instruction::AShr:
02759     case Instruction::LShr:
02760       if (!Val0->getType()->isIntOrIntVectorTy())
02761         return Error(ID.Loc, "constexpr requires integer operands");
02762       break;
02763     case Instruction::FAdd:
02764     case Instruction::FSub:
02765     case Instruction::FMul:
02766     case Instruction::FDiv:
02767     case Instruction::FRem:
02768       if (!Val0->getType()->isFPOrFPVectorTy())
02769         return Error(ID.Loc, "constexpr requires fp operands");
02770       break;
02771     default: llvm_unreachable("Unknown binary operator!");
02772     }
02773     unsigned Flags = 0;
02774     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
02775     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
02776     if (Exact) Flags |= PossiblyExactOperator::IsExact;
02777     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
02778     ID.ConstantVal = C;
02779     ID.Kind = ValID::t_Constant;
02780     return false;
02781   }
02782 
02783   // Logical Operations
02784   case lltok::kw_and:
02785   case lltok::kw_or:
02786   case lltok::kw_xor: {
02787     unsigned Opc = Lex.getUIntVal();
02788     Constant *Val0, *Val1;
02789     Lex.Lex();
02790     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
02791         ParseGlobalTypeAndValue(Val0) ||
02792         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
02793         ParseGlobalTypeAndValue(Val1) ||
02794         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
02795       return true;
02796     if (Val0->getType() != Val1->getType())
02797       return Error(ID.Loc, "operands of constexpr must have same type");
02798     if (!Val0->getType()->isIntOrIntVectorTy())
02799       return Error(ID.Loc,
02800                    "constexpr requires integer or integer vector operands");
02801     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
02802     ID.Kind = ValID::t_Constant;
02803     return false;
02804   }
02805 
02806   case lltok::kw_getelementptr:
02807   case lltok::kw_shufflevector:
02808   case lltok::kw_insertelement:
02809   case lltok::kw_extractelement:
02810   case lltok::kw_select: {
02811     unsigned Opc = Lex.getUIntVal();
02812     SmallVector<Constant*, 16> Elts;
02813     bool InBounds = false;
02814     Lex.Lex();
02815     if (Opc == Instruction::GetElementPtr)
02816       InBounds = EatIfPresent(lltok::kw_inbounds);
02817     if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
02818         ParseGlobalValueVector(Elts) ||
02819         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
02820       return true;
02821 
02822     if (Opc == Instruction::GetElementPtr) {
02823       if (Elts.size() == 0 ||
02824           !Elts[0]->getType()->getScalarType()->isPointerTy())
02825         return Error(ID.Loc, "getelementptr requires pointer operand");
02826 
02827       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
02828       if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
02829         return Error(ID.Loc, "invalid indices for getelementptr");
02830       ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
02831                                                       InBounds);
02832     } else if (Opc == Instruction::Select) {
02833       if (Elts.size() != 3)
02834         return Error(ID.Loc, "expected three operands to select");
02835       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
02836                                                               Elts[2]))
02837         return Error(ID.Loc, Reason);
02838       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
02839     } else if (Opc == Instruction::ShuffleVector) {
02840       if (Elts.size() != 3)
02841         return Error(ID.Loc, "expected three operands to shufflevector");
02842       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
02843         return Error(ID.Loc, "invalid operands to shufflevector");
02844       ID.ConstantVal =
02845                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
02846     } else if (Opc == Instruction::ExtractElement) {
02847       if (Elts.size() != 2)
02848         return Error(ID.Loc, "expected two operands to extractelement");
02849       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
02850         return Error(ID.Loc, "invalid extractelement operands");
02851       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
02852     } else {
02853       assert(Opc == Instruction::InsertElement && "Unknown opcode");
02854       if (Elts.size() != 3)
02855       return Error(ID.Loc, "expected three operands to insertelement");
02856       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
02857         return Error(ID.Loc, "invalid insertelement operands");
02858       ID.ConstantVal =
02859                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
02860     }
02861 
02862     ID.Kind = ValID::t_Constant;
02863     return false;
02864   }
02865   }
02866 
02867   Lex.Lex();
02868   return false;
02869 }
02870 
02871 /// ParseGlobalValue - Parse a global value with the specified type.
02872 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
02873   C = nullptr;
02874   ValID ID;
02875   Value *V = nullptr;
02876   bool Parsed = ParseValID(ID) ||
02877                 ConvertValIDToValue(Ty, ID, V, nullptr);
02878   if (V && !(C = dyn_cast<Constant>(V)))
02879     return Error(ID.Loc, "global values must be constants");
02880   return Parsed;
02881 }
02882 
02883 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
02884   Type *Ty = nullptr;
02885   return ParseType(Ty) ||
02886          ParseGlobalValue(Ty, V);
02887 }
02888 
02889 bool LLParser::parseOptionalComdat(Comdat *&C) {
02890   C = nullptr;
02891   if (!EatIfPresent(lltok::kw_comdat))
02892     return false;
02893   if (Lex.getKind() != lltok::ComdatVar)
02894     return TokError("expected comdat variable");
02895   LocTy Loc = Lex.getLoc();
02896   StringRef Name = Lex.getStrVal();
02897   C = getComdat(Name, Loc);
02898   Lex.Lex();
02899   return false;
02900 }
02901 
02902 /// ParseGlobalValueVector
02903 ///   ::= /*empty*/
02904 ///   ::= TypeAndValue (',' TypeAndValue)*
02905 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
02906   // Empty list.
02907   if (Lex.getKind() == lltok::rbrace ||
02908       Lex.getKind() == lltok::rsquare ||
02909       Lex.getKind() == lltok::greater ||
02910       Lex.getKind() == lltok::rparen)
02911     return false;
02912 
02913   Constant *C;
02914   if (ParseGlobalTypeAndValue(C)) return true;
02915   Elts.push_back(C);
02916 
02917   while (EatIfPresent(lltok::comma)) {
02918     if (ParseGlobalTypeAndValue(C)) return true;
02919     Elts.push_back(C);
02920   }
02921 
02922   return false;
02923 }
02924 
02925 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
02926   assert(Lex.getKind() == lltok::lbrace);
02927   Lex.Lex();
02928 
02929   SmallVector<Value*, 16> Elts;
02930   if (ParseMDNodeVector(Elts, PFS) ||
02931       ParseToken(lltok::rbrace, "expected end of metadata node"))
02932     return true;
02933 
02934   ID.MDNodeVal = MDNode::get(Context, Elts);
02935   ID.Kind = ValID::t_MDNode;
02936   return false;
02937 }
02938 
02939 /// ParseMetadataValue
02940 ///  ::= !42
02941 ///  ::= !{...}
02942 ///  ::= !"string"
02943 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
02944   assert(Lex.getKind() == lltok::exclaim);
02945   Lex.Lex();
02946 
02947   // MDNode:
02948   // !{ ... }
02949   if (Lex.getKind() == lltok::lbrace)
02950     return ParseMetadataListValue(ID, PFS);
02951 
02952   // Standalone metadata reference
02953   // !42
02954   if (Lex.getKind() == lltok::APSInt) {
02955     if (ParseMDNodeID(ID.MDNodeVal)) return true;
02956     ID.Kind = ValID::t_MDNode;
02957     return false;
02958   }
02959 
02960   // MDString:
02961   //   ::= '!' STRINGCONSTANT
02962   if (ParseMDString(ID.MDStringVal)) return true;
02963   ID.Kind = ValID::t_MDString;
02964   return false;
02965 }
02966 
02967 
02968 //===----------------------------------------------------------------------===//
02969 // Function Parsing.
02970 //===----------------------------------------------------------------------===//
02971 
02972 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
02973                                    PerFunctionState *PFS) {
02974   if (Ty->isFunctionTy())
02975     return Error(ID.Loc, "functions are not values, refer to them as pointers");
02976 
02977   switch (ID.Kind) {
02978   case ValID::t_LocalID:
02979     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
02980     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
02981     return V == nullptr;
02982   case ValID::t_LocalName:
02983     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
02984     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
02985     return V == nullptr;
02986   case ValID::t_InlineAsm: {
02987     PointerType *PTy = dyn_cast<PointerType>(Ty);
02988     FunctionType *FTy =
02989       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
02990     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
02991       return Error(ID.Loc, "invalid type for inline asm constraint string");
02992     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
02993                        (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
02994     return false;
02995   }
02996   case ValID::t_MDNode:
02997     if (!Ty->isMetadataTy())
02998       return Error(ID.Loc, "metadata value must have metadata type");
02999     V = ID.MDNodeVal;
03000     return false;
03001   case ValID::t_MDString:
03002     if (!Ty->isMetadataTy())
03003       return Error(ID.Loc, "metadata value must have metadata type");
03004     V = ID.MDStringVal;
03005     return false;
03006   case ValID::t_GlobalName:
03007     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
03008     return V == nullptr;
03009   case ValID::t_GlobalID:
03010     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
03011     return V == nullptr;
03012   case ValID::t_APSInt:
03013     if (!Ty->isIntegerTy())
03014       return Error(ID.Loc, "integer constant must have integer type");
03015     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
03016     V = ConstantInt::get(Context, ID.APSIntVal);
03017     return false;
03018   case ValID::t_APFloat:
03019     if (!Ty->isFloatingPointTy() ||
03020         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
03021       return Error(ID.Loc, "floating point constant invalid for type");
03022 
03023     // The lexer has no type info, so builds all half, float, and double FP
03024     // constants as double.  Fix this here.  Long double does not need this.
03025     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
03026       bool Ignored;
03027       if (Ty->isHalfTy())
03028         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
03029                               &Ignored);
03030       else if (Ty->isFloatTy())
03031         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
03032                               &Ignored);
03033     }
03034     V = ConstantFP::get(Context, ID.APFloatVal);
03035 
03036     if (V->getType() != Ty)
03037       return Error(ID.Loc, "floating point constant does not have type '" +
03038                    getTypeString(Ty) + "'");
03039 
03040     return false;
03041   case ValID::t_Null:
03042     if (!Ty->isPointerTy())
03043       return Error(ID.Loc, "null must be a pointer type");
03044     V = ConstantPointerNull::get(cast<PointerType>(Ty));
03045     return false;
03046   case ValID::t_Undef:
03047     // FIXME: LabelTy should not be a first-class type.
03048     if (!Ty->isFirstClassType() || Ty->isLabelTy())
03049       return Error(ID.Loc, "invalid type for undef constant");
03050     V = UndefValue::get(Ty);
03051     return false;
03052   case ValID::t_EmptyArray:
03053     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
03054       return Error(ID.Loc, "invalid empty array initializer");
03055     V = UndefValue::get(Ty);
03056     return false;
03057   case ValID::t_Zero:
03058     // FIXME: LabelTy should not be a first-class type.
03059     if (!Ty->isFirstClassType() || Ty->isLabelTy())
03060       return Error(ID.Loc, "invalid type for null constant");
03061     V = Constant::getNullValue(Ty);
03062     return false;
03063   case ValID::t_Constant:
03064     if (ID.ConstantVal->getType() != Ty)
03065       return Error(ID.Loc, "constant expression type mismatch");
03066 
03067     V = ID.ConstantVal;
03068     return false;
03069   case ValID::t_ConstantStruct:
03070   case ValID::t_PackedConstantStruct:
03071     if (StructType *ST = dyn_cast<StructType>(Ty)) {
03072       if (ST->getNumElements() != ID.UIntVal)
03073         return Error(ID.Loc,
03074                      "initializer with struct type has wrong # elements");
03075       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
03076         return Error(ID.Loc, "packed'ness of initializer and type don't match");
03077 
03078       // Verify that the elements are compatible with the structtype.
03079       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
03080         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
03081           return Error(ID.Loc, "element " + Twine(i) +
03082                     " of struct initializer doesn't match struct element type");
03083 
03084       V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
03085                                                ID.UIntVal));
03086     } else
03087       return Error(ID.Loc, "constant expression type mismatch");
03088     return false;
03089   }
03090   llvm_unreachable("Invalid ValID");
03091 }
03092 
03093 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
03094   V = nullptr;
03095   ValID ID;
03096   return ParseValID(ID, PFS) ||
03097          ConvertValIDToValue(Ty, ID, V, PFS);
03098 }
03099 
03100 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
03101   Type *Ty = nullptr;
03102   return ParseType(Ty) ||
03103          ParseValue(Ty, V, PFS);
03104 }
03105 
03106 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
03107                                       PerFunctionState &PFS) {
03108   Value *V;
03109   Loc = Lex.getLoc();
03110   if (ParseTypeAndValue(V, PFS)) return true;
03111   if (!isa<BasicBlock>(V))
03112     return Error(Loc, "expected a basic block");
03113   BB = cast<BasicBlock>(V);
03114   return false;
03115 }
03116 
03117 
03118 /// FunctionHeader
03119 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
03120 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
03121 ///       OptionalAlign OptGC OptionalPrefix
03122 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
03123   // Parse the linkage.
03124   LocTy LinkageLoc = Lex.getLoc();
03125   unsigned Linkage;
03126 
03127   unsigned Visibility;
03128   unsigned DLLStorageClass;
03129   AttrBuilder RetAttrs;
03130   unsigned CC;
03131   Type *RetType = nullptr;
03132   LocTy RetTypeLoc = Lex.getLoc();
03133   if (ParseOptionalLinkage(Linkage) ||
03134       ParseOptionalVisibility(Visibility) ||
03135       ParseOptionalDLLStorageClass(DLLStorageClass) ||
03136       ParseOptionalCallingConv(CC) ||
03137       ParseOptionalReturnAttrs(RetAttrs) ||
03138       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
03139     return true;
03140 
03141   // Verify that the linkage is ok.
03142   switch ((GlobalValue::LinkageTypes)Linkage) {
03143   case GlobalValue::ExternalLinkage:
03144     break; // always ok.
03145   case GlobalValue::ExternalWeakLinkage:
03146     if (isDefine)
03147       return Error(LinkageLoc, "invalid linkage for function definition");
03148     break;
03149   case GlobalValue::PrivateLinkage:
03150   case GlobalValue::InternalLinkage:
03151   case GlobalValue::AvailableExternallyLinkage:
03152   case GlobalValue::LinkOnceAnyLinkage:
03153   case GlobalValue::LinkOnceODRLinkage:
03154   case GlobalValue::WeakAnyLinkage:
03155   case GlobalValue::WeakODRLinkage:
03156     if (!isDefine)
03157       return Error(LinkageLoc, "invalid linkage for function declaration");
03158     break;
03159   case GlobalValue::AppendingLinkage:
03160   case GlobalValue::CommonLinkage:
03161     return Error(LinkageLoc, "invalid function linkage type");
03162   }
03163 
03164   if (!isValidVisibilityForLinkage(Visibility, Linkage))
03165     return Error(LinkageLoc,
03166                  "symbol with local linkage must have default visibility");
03167 
03168   if (!FunctionType::isValidReturnType(RetType))
03169     return Error(RetTypeLoc, "invalid function return type");
03170 
03171   LocTy NameLoc = Lex.getLoc();
03172 
03173   std::string FunctionName;
03174   if (Lex.getKind() == lltok::GlobalVar) {
03175     FunctionName = Lex.getStrVal();
03176   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
03177     unsigned NameID = Lex.getUIntVal();
03178 
03179     if (NameID != NumberedVals.size())
03180       return TokError("function expected to be numbered '%" +
03181                       Twine(NumberedVals.size()) + "'");
03182   } else {
03183     return TokError("expected function name");
03184   }
03185 
03186   Lex.Lex();
03187 
03188   if (Lex.getKind() != lltok::lparen)
03189     return TokError("expected '(' in function argument list");
03190 
03191   SmallVector<ArgInfo, 8> ArgList;
03192   bool isVarArg;
03193   AttrBuilder FuncAttrs;
03194   std::vector<unsigned> FwdRefAttrGrps;
03195   LocTy BuiltinLoc;
03196   std::string Section;
03197   unsigned Alignment;
03198   std::string GC;
03199   bool UnnamedAddr;
03200   LocTy UnnamedAddrLoc;
03201   Constant *Prefix = nullptr;
03202   Comdat *C;
03203 
03204   if (ParseArgumentList(ArgList, isVarArg) ||
03205       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
03206                          &UnnamedAddrLoc) ||
03207       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
03208                                  BuiltinLoc) ||
03209       (EatIfPresent(lltok::kw_section) &&
03210        ParseStringConstant(Section)) ||
03211       parseOptionalComdat(C) ||
03212       ParseOptionalAlignment(Alignment) ||
03213       (EatIfPresent(lltok::kw_gc) &&
03214        ParseStringConstant(GC)) ||
03215       (EatIfPresent(lltok::kw_prefix) &&
03216        ParseGlobalTypeAndValue(Prefix)))
03217     return true;
03218 
03219   if (FuncAttrs.contains(Attribute::Builtin))
03220     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
03221 
03222   // If the alignment was parsed as an attribute, move to the alignment field.
03223   if (FuncAttrs.hasAlignmentAttr()) {
03224     Alignment = FuncAttrs.getAlignment();
03225     FuncAttrs.removeAttribute(Attribute::Alignment);
03226   }
03227 
03228   // Okay, if we got here, the function is syntactically valid.  Convert types
03229   // and do semantic checks.
03230   std::vector<Type*> ParamTypeList;
03231   SmallVector<AttributeSet, 8> Attrs;
03232 
03233   if (RetAttrs.hasAttributes())
03234     Attrs.push_back(AttributeSet::get(RetType->getContext(),
03235                                       AttributeSet::ReturnIndex,
03236                                       RetAttrs));
03237 
03238   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
03239     ParamTypeList.push_back(ArgList[i].Ty);
03240     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
03241       AttrBuilder B(ArgList[i].Attrs, i + 1);
03242       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
03243     }
03244   }
03245 
03246   if (FuncAttrs.hasAttributes())
03247     Attrs.push_back(AttributeSet::get(RetType->getContext(),
03248                                       AttributeSet::FunctionIndex,
03249                                       FuncAttrs));
03250 
03251   AttributeSet PAL = AttributeSet::get(Context, Attrs);
03252 
03253   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
03254     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
03255 
03256   FunctionType *FT =
03257     FunctionType::get(RetType, ParamTypeList, isVarArg);
03258   PointerType *PFT = PointerType::getUnqual(FT);
03259 
03260   Fn = nullptr;
03261   if (!FunctionName.empty()) {
03262     // If this was a definition of a forward reference, remove the definition
03263     // from the forward reference table and fill in the forward ref.
03264     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
03265       ForwardRefVals.find(FunctionName);
03266     if (FRVI != ForwardRefVals.end()) {
03267       Fn = M->getFunction(FunctionName);
03268       if (!Fn)
03269         return Error(FRVI->second.second, "invalid forward reference to "
03270                      "function as global value!");
03271       if (Fn->getType() != PFT)
03272         return Error(FRVI->second.second, "invalid forward reference to "
03273                      "function '" + FunctionName + "' with wrong type!");
03274 
03275       ForwardRefVals.erase(FRVI);
03276     } else if ((Fn = M->getFunction(FunctionName))) {
03277       // Reject redefinitions.
03278       return Error(NameLoc, "invalid redefinition of function '" +
03279                    FunctionName + "'");
03280     } else if (M->getNamedValue(FunctionName)) {
03281       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
03282     }
03283 
03284   } else {
03285     // If this is a definition of a forward referenced function, make sure the
03286     // types agree.
03287     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
03288       = ForwardRefValIDs.find(NumberedVals.size());
03289     if (I != ForwardRefValIDs.end()) {
03290       Fn = cast<Function>(I->second.first);
03291       if (Fn->getType() != PFT)
03292         return Error(NameLoc, "type of definition and forward reference of '@" +
03293                      Twine(NumberedVals.size()) + "' disagree");
03294       ForwardRefValIDs.erase(I);
03295     }
03296   }
03297 
03298   if (!Fn)
03299     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
03300   else // Move the forward-reference to the correct spot in the module.
03301     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
03302 
03303   if (FunctionName.empty())
03304     NumberedVals.push_back(Fn);
03305 
03306   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
03307   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
03308   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
03309   Fn->setCallingConv(CC);
03310   Fn->setAttributes(PAL);
03311   Fn->setUnnamedAddr(UnnamedAddr);
03312   Fn->setAlignment(Alignment);
03313   Fn->setSection(Section);
03314   Fn->setComdat(C);
03315   if (!GC.empty()) Fn->setGC(GC.c_str());
03316   Fn->setPrefixData(Prefix);
03317   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
03318 
03319   // Add all of the arguments we parsed to the function.
03320   Function::arg_iterator ArgIt = Fn->arg_begin();
03321   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
03322     // If the argument has a name, insert it into the argument symbol table.
03323     if (ArgList[i].Name.empty()) continue;
03324 
03325     // Set the name, if it conflicted, it will be auto-renamed.
03326     ArgIt->setName(ArgList[i].Name);
03327 
03328     if (ArgIt->getName() != ArgList[i].Name)
03329       return Error(ArgList[i].Loc, "redefinition of argument '%" +
03330                    ArgList[i].Name + "'");
03331   }
03332 
03333   if (isDefine)
03334     return false;
03335 
03336   // Check the declaration has no block address forward references.
03337   ValID ID;
03338   if (FunctionName.empty()) {
03339     ID.Kind = ValID::t_GlobalID;
03340     ID.UIntVal = NumberedVals.size() - 1;
03341   } else {
03342     ID.Kind = ValID::t_GlobalName;
03343     ID.StrVal = FunctionName;
03344   }
03345   auto Blocks = ForwardRefBlockAddresses.find(ID);
03346   if (Blocks != ForwardRefBlockAddresses.end())
03347     return Error(Blocks->first.Loc,
03348                  "cannot take blockaddress inside a declaration");
03349   return false;
03350 }
03351 
03352 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
03353   ValID ID;
03354   if (FunctionNumber == -1) {
03355     ID.Kind = ValID::t_GlobalName;
03356     ID.StrVal = F.getName();
03357   } else {
03358     ID.Kind = ValID::t_GlobalID;
03359     ID.UIntVal = FunctionNumber;
03360   }
03361 
03362   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
03363   if (Blocks == P.ForwardRefBlockAddresses.end())
03364     return false;
03365 
03366   for (const auto &I : Blocks->second) {
03367     const ValID &BBID = I.first;
03368     GlobalValue *GV = I.second;
03369 
03370     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
03371            "Expected local id or name");
03372     BasicBlock *BB;
03373     if (BBID.Kind == ValID::t_LocalName)
03374       BB = GetBB(BBID.StrVal, BBID.Loc);
03375     else
03376       BB = GetBB(BBID.UIntVal, BBID.Loc);
03377     if (!BB)
03378       return P.Error(BBID.Loc, "referenced value is not a basic block");
03379 
03380     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
03381     GV->eraseFromParent();
03382   }
03383 
03384   P.ForwardRefBlockAddresses.erase(Blocks);
03385   return false;
03386 }
03387 
03388 /// ParseFunctionBody
03389 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
03390 bool LLParser::ParseFunctionBody(Function &Fn) {
03391   if (Lex.getKind() != lltok::lbrace)
03392     return TokError("expected '{' in function body");
03393   Lex.Lex();  // eat the {.
03394 
03395   int FunctionNumber = -1;
03396   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
03397 
03398   PerFunctionState PFS(*this, Fn, FunctionNumber);
03399 
03400   // Resolve block addresses and allow basic blocks to be forward-declared
03401   // within this function.
03402   if (PFS.resolveForwardRefBlockAddresses())
03403     return true;
03404   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
03405 
03406   // We need at least one basic block.
03407   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
03408     return TokError("function body requires at least one basic block");
03409 
03410   while (Lex.getKind() != lltok::rbrace &&
03411          Lex.getKind() != lltok::kw_uselistorder)
03412     if (ParseBasicBlock(PFS)) return true;
03413 
03414   while (Lex.getKind() != lltok::rbrace)
03415     if (ParseUseListOrder(&PFS))
03416       return true;
03417 
03418   // Eat the }.
03419   Lex.Lex();
03420 
03421   // Verify function is ok.
03422   return PFS.FinishFunction();
03423 }
03424 
03425 /// ParseBasicBlock
03426 ///   ::= LabelStr? Instruction*
03427 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
03428   // If this basic block starts out with a name, remember it.
03429   std::string Name;
03430   LocTy NameLoc = Lex.getLoc();
03431   if (Lex.getKind() == lltok::LabelStr) {
03432     Name = Lex.getStrVal();
03433     Lex.Lex();
03434   }
03435 
03436   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
03437   if (!BB) return true;
03438 
03439   std::string NameStr;
03440 
03441   // Parse the instructions in this block until we get a terminator.
03442   Instruction *Inst;
03443   do {
03444     // This instruction may have three possibilities for a name: a) none
03445     // specified, b) name specified "%foo =", c) number specified: "%4 =".
03446     LocTy NameLoc = Lex.getLoc();
03447     int NameID = -1;
03448     NameStr = "";
03449 
03450     if (Lex.getKind() == lltok::LocalVarID) {
03451       NameID = Lex.getUIntVal();
03452       Lex.Lex();
03453       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
03454         return true;
03455     } else if (Lex.getKind() == lltok::LocalVar) {
03456       NameStr = Lex.getStrVal();
03457       Lex.Lex();
03458       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
03459         return true;
03460     }
03461 
03462     switch (ParseInstruction(Inst, BB, PFS)) {
03463     default: llvm_unreachable("Unknown ParseInstruction result!");
03464     case InstError: return true;
03465     case InstNormal:
03466       BB->getInstList().push_back(Inst);
03467 
03468       // With a normal result, we check to see if the instruction is followed by
03469       // a comma and metadata.
03470       if (EatIfPresent(lltok::comma))
03471         if (ParseInstructionMetadata(Inst, &PFS))
03472           return true;
03473       break;
03474     case InstExtraComma:
03475       BB->getInstList().push_back(Inst);
03476 
03477       // If the instruction parser ate an extra comma at the end of it, it
03478       // *must* be followed by metadata.
03479       if (ParseInstructionMetadata(Inst, &PFS))
03480         return true;
03481       break;
03482     }
03483 
03484     // Set the name on the instruction.
03485     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
03486   } while (!isa<TerminatorInst>(Inst));
03487 
03488   return false;
03489 }
03490 
03491 //===----------------------------------------------------------------------===//
03492 // Instruction Parsing.
03493 //===----------------------------------------------------------------------===//
03494 
03495 /// ParseInstruction - Parse one of the many different instructions.
03496 ///
03497 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
03498                                PerFunctionState &PFS) {
03499   lltok::Kind Token = Lex.getKind();
03500   if (Token == lltok::Eof)
03501     return TokError("found end of file when expecting more instructions");
03502   LocTy Loc = Lex.getLoc();
03503   unsigned KeywordVal = Lex.getUIntVal();
03504   Lex.Lex();  // Eat the keyword.
03505 
03506   switch (Token) {
03507   default:                    return Error(Loc, "expected instruction opcode");
03508   // Terminator Instructions.
03509   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
03510   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
03511   case lltok::kw_br:          return ParseBr(Inst, PFS);
03512   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
03513   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
03514   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
03515   case lltok::kw_resume:      return ParseResume(Inst, PFS);
03516   // Binary Operators.
03517   case lltok::kw_add:
03518   case lltok::kw_sub:
03519   case lltok::kw_mul:
03520   case lltok::kw_shl: {
03521     bool NUW = EatIfPresent(lltok::kw_nuw);
03522     bool NSW = EatIfPresent(lltok::kw_nsw);
03523     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
03524 
03525     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
03526 
03527     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
03528     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
03529     return false;
03530   }
03531   case lltok::kw_fadd:
03532   case lltok::kw_fsub:
03533   case lltok::kw_fmul:
03534   case lltok::kw_fdiv:
03535   case lltok::kw_frem: {
03536     FastMathFlags FMF = EatFastMathFlagsIfPresent();
03537     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
03538     if (Res != 0)
03539       return Res;
03540     if (FMF.any())
03541       Inst->setFastMathFlags(FMF);
03542     return 0;
03543   }
03544 
03545   case lltok::kw_sdiv:
03546   case lltok::kw_udiv:
03547   case lltok::kw_lshr:
03548   case lltok::kw_ashr: {
03549     bool Exact = EatIfPresent(lltok::kw_exact);
03550 
03551     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
03552     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
03553     return false;
03554   }
03555 
03556   case lltok::kw_urem:
03557   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
03558   case lltok::kw_and:
03559   case lltok::kw_or:
03560   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
03561   case lltok::kw_icmp:
03562   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
03563   // Casts.
03564   case lltok::kw_trunc:
03565   case lltok::kw_zext:
03566   case lltok::kw_sext:
03567   case lltok::kw_fptrunc:
03568   case lltok::kw_fpext:
03569   case lltok::kw_bitcast:
03570   case lltok::kw_addrspacecast:
03571   case lltok::kw_uitofp:
03572   case lltok::kw_sitofp:
03573   case lltok::kw_fptoui:
03574   case lltok::kw_fptosi:
03575   case lltok::kw_inttoptr:
03576   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
03577   // Other.
03578   case lltok::kw_select:         return ParseSelect(Inst, PFS);
03579   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
03580   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
03581   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
03582   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
03583   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
03584   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
03585   // Call.
03586   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
03587   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
03588   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
03589   // Memory.
03590   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
03591   case lltok::kw_load:           return ParseLoad(Inst, PFS);
03592   case lltok::kw_store:          return ParseStore(Inst, PFS);
03593   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
03594   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
03595   case lltok::kw_fence:          return ParseFence(Inst, PFS);
03596   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
03597   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
03598   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
03599   }
03600 }
03601 
03602 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
03603 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
03604   if (Opc == Instruction::FCmp) {
03605     switch (Lex.getKind()) {
03606     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
03607     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
03608     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
03609     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
03610     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
03611     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
03612     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
03613     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
03614     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
03615     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
03616     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
03617     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
03618     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
03619     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
03620     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
03621     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
03622     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
03623     }
03624   } else {
03625     switch (Lex.getKind()) {
03626     default: return TokError("expected icmp predicate (e.g. 'eq')");
03627     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
03628     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
03629     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
03630     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
03631     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
03632     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
03633     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
03634     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
03635     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
03636     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
03637     }
03638   }
03639   Lex.Lex();
03640   return false;
03641 }
03642 
03643 //===----------------------------------------------------------------------===//
03644 // Terminator Instructions.
03645 //===----------------------------------------------------------------------===//
03646 
03647 /// ParseRet - Parse a return instruction.
03648 ///   ::= 'ret' void (',' !dbg, !1)*
03649 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
03650 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
03651                         PerFunctionState &PFS) {
03652   SMLoc TypeLoc = Lex.getLoc();
03653   Type *Ty = nullptr;
03654   if (ParseType(Ty, true /*void allowed*/)) return true;
03655 
03656   Type *ResType = PFS.getFunction().getReturnType();
03657 
03658   if (Ty->isVoidTy()) {
03659     if (!ResType->isVoidTy())
03660       return Error(TypeLoc, "value doesn't match function result type '" +
03661                    getTypeString(ResType) + "'");
03662 
03663     Inst = ReturnInst::Create(Context);
03664     return false;
03665   }
03666 
03667   Value *RV;
03668   if (ParseValue(Ty, RV, PFS)) return true;
03669 
03670   if (ResType != RV->getType())
03671     return Error(TypeLoc, "value doesn't match function result type '" +
03672                  getTypeString(ResType) + "'");
03673 
03674   Inst = ReturnInst::Create(Context, RV);
03675   return false;
03676 }
03677 
03678 
03679 /// ParseBr
03680 ///   ::= 'br' TypeAndValue
03681 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
03682 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
03683   LocTy Loc, Loc2;
03684   Value *Op0;
03685   BasicBlock *Op1, *Op2;
03686   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
03687 
03688   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
03689     Inst = BranchInst::Create(BB);
03690     return false;
03691   }
03692 
03693   if (Op0->getType() != Type::getInt1Ty(Context))
03694     return Error(Loc, "branch condition must have 'i1' type");
03695 
03696   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
03697       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
03698       ParseToken(lltok::comma, "expected ',' after true destination") ||
03699       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
03700     return true;
03701 
03702   Inst = BranchInst::Create(Op1, Op2, Op0);
03703   return false;
03704 }
03705 
03706 /// ParseSwitch
03707 ///  Instruction
03708 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
03709 ///  JumpTable
03710 ///    ::= (TypeAndValue ',' TypeAndValue)*
03711 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
03712   LocTy CondLoc, BBLoc;
03713   Value *Cond;
03714   BasicBlock *DefaultBB;
03715   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
03716       ParseToken(lltok::comma, "expected ',' after switch condition") ||
03717       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
03718       ParseToken(lltok::lsquare, "expected '[' with switch table"))
03719     return true;
03720 
03721   if (!Cond->getType()->isIntegerTy())
03722     return Error(CondLoc, "switch condition must have integer type");
03723 
03724   // Parse the jump table pairs.
03725   SmallPtrSet<Value*, 32> SeenCases;
03726   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
03727   while (Lex.getKind() != lltok::rsquare) {
03728     Value *Constant;
03729     BasicBlock *DestBB;
03730 
03731     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
03732         ParseToken(lltok::comma, "expected ',' after case value") ||
03733         ParseTypeAndBasicBlock(DestBB, PFS))
03734       return true;
03735 
03736     if (!SeenCases.insert(Constant))
03737       return Error(CondLoc, "duplicate case value in switch");
03738     if (!isa<ConstantInt>(Constant))
03739       return Error(CondLoc, "case value is not a constant integer");
03740 
03741     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
03742   }
03743 
03744   Lex.Lex();  // Eat the ']'.
03745 
03746   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
03747   for (unsigned i = 0, e = Table.size(); i != e; ++i)
03748     SI->addCase(Table[i].first, Table[i].second);
03749   Inst = SI;
03750   return false;
03751 }
03752 
03753 /// ParseIndirectBr
03754 ///  Instruction
03755 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
03756 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
03757   LocTy AddrLoc;
03758   Value *Address;
03759   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
03760       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
03761       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
03762     return true;
03763 
03764   if (!Address->getType()->isPointerTy())
03765     return Error(AddrLoc, "indirectbr address must have pointer type");
03766 
03767   // Parse the destination list.
03768   SmallVector<BasicBlock*, 16> DestList;
03769 
03770   if (Lex.getKind() != lltok::rsquare) {
03771     BasicBlock *DestBB;
03772     if (ParseTypeAndBasicBlock(DestBB, PFS))
03773       return true;
03774     DestList.push_back(DestBB);
03775 
03776     while (EatIfPresent(lltok::comma)) {
03777       if (ParseTypeAndBasicBlock(DestBB, PFS))
03778         return true;
03779       DestList.push_back(DestBB);
03780     }
03781   }
03782 
03783   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
03784     return true;
03785 
03786   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
03787   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
03788     IBI->addDestination(DestList[i]);
03789   Inst = IBI;
03790   return false;
03791 }
03792 
03793 
03794 /// ParseInvoke
03795 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
03796 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
03797 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
03798   LocTy CallLoc = Lex.getLoc();
03799   AttrBuilder RetAttrs, FnAttrs;
03800   std::vector<unsigned> FwdRefAttrGrps;
03801   LocTy NoBuiltinLoc;
03802   unsigned CC;
03803   Type *RetType = nullptr;
03804   LocTy RetTypeLoc;
03805   ValID CalleeID;
03806   SmallVector<ParamInfo, 16> ArgList;
03807 
03808   BasicBlock *NormalBB, *UnwindBB;
03809   if (ParseOptionalCallingConv(CC) ||
03810       ParseOptionalReturnAttrs(RetAttrs) ||
03811       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
03812       ParseValID(CalleeID) ||
03813       ParseParameterList(ArgList, PFS) ||
03814       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
03815                                  NoBuiltinLoc) ||
03816       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
03817       ParseTypeAndBasicBlock(NormalBB, PFS) ||
03818       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
03819       ParseTypeAndBasicBlock(UnwindBB, PFS))
03820     return true;
03821 
03822   // If RetType is a non-function pointer type, then this is the short syntax
03823   // for the call, which means that RetType is just the return type.  Infer the
03824   // rest of the function argument types from the arguments that are present.
03825   PointerType *PFTy = nullptr;
03826   FunctionType *Ty = nullptr;
03827   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
03828       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
03829     // Pull out the types of all of the arguments...
03830     std::vector<Type*> ParamTypes;
03831     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
03832       ParamTypes.push_back(ArgList[i].V->getType());
03833 
03834     if (!FunctionType::isValidReturnType(RetType))
03835       return Error(RetTypeLoc, "Invalid result type for LLVM function");
03836 
03837     Ty = FunctionType::get(RetType, ParamTypes, false);
03838     PFTy = PointerType::getUnqual(Ty);
03839   }
03840 
03841   // Look up the callee.
03842   Value *Callee;
03843   if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
03844 
03845   // Set up the Attribute for the function.
03846   SmallVector<AttributeSet, 8> Attrs;
03847   if (RetAttrs.hasAttributes())
03848     Attrs.push_back(AttributeSet::get(RetType->getContext(),
03849                                       AttributeSet::ReturnIndex,
03850                                       RetAttrs));
03851 
03852   SmallVector<Value*, 8> Args;
03853 
03854   // Loop through FunctionType's arguments and ensure they are specified
03855   // correctly.  Also, gather any parameter attributes.
03856   FunctionType::param_iterator I = Ty->param_begin();
03857   FunctionType::param_iterator E = Ty->param_end();
03858   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
03859     Type *ExpectedTy = nullptr;
03860     if (I != E) {
03861       ExpectedTy = *I++;
03862     } else if (!Ty->isVarArg()) {
03863       return Error(ArgList[i].Loc, "too many arguments specified");
03864     }
03865 
03866     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
03867       return Error(ArgList[i].Loc, "argument is not of expected type '" +
03868                    getTypeString(ExpectedTy) + "'");
03869     Args.push_back(ArgList[i].V);
03870     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
03871       AttrBuilder B(ArgList[i].Attrs, i + 1);
03872       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
03873     }
03874   }
03875 
03876   if (I != E)
03877     return Error(CallLoc, "not enough parameters specified for call");
03878 
03879   if (FnAttrs.hasAttributes())
03880     Attrs.push_back(AttributeSet::get(RetType->getContext(),
03881                                       AttributeSet::FunctionIndex,
03882                                       FnAttrs));
03883 
03884   // Finish off the Attribute and check them
03885   AttributeSet PAL = AttributeSet::get(Context, Attrs);
03886 
03887   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
03888   II->setCallingConv(CC);
03889   II->setAttributes(PAL);
03890   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
03891   Inst = II;
03892   return false;
03893 }
03894 
03895 /// ParseResume
03896 ///   ::= 'resume' TypeAndValue
03897 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
03898   Value *Exn; LocTy ExnLoc;
03899   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
03900     return true;
03901 
03902   ResumeInst *RI = ResumeInst::Create(Exn);
03903   Inst = RI;
03904   return false;
03905 }
03906 
03907 //===----------------------------------------------------------------------===//
03908 // Binary Operators.
03909 //===----------------------------------------------------------------------===//
03910 
03911 /// ParseArithmetic
03912 ///  ::= ArithmeticOps TypeAndValue ',' Value
03913 ///
03914 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
03915 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
03916 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
03917                                unsigned Opc, unsigned OperandType) {
03918   LocTy Loc; Value *LHS, *RHS;
03919   if (ParseTypeAndValue(LHS, Loc, PFS) ||
03920       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
03921       ParseValue(LHS->getType(), RHS, PFS))
03922     return true;
03923 
03924   bool Valid;
03925   switch (OperandType) {
03926   default: llvm_unreachable("Unknown operand type!");
03927   case 0: // int or FP.
03928     Valid = LHS->getType()->isIntOrIntVectorTy() ||
03929             LHS->getType()->isFPOrFPVectorTy();
03930     break;
03931   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
03932   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
03933   }
03934 
03935   if (!Valid)
03936     return Error(Loc, "invalid operand type for instruction");
03937 
03938   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
03939   return false;
03940 }
03941 
03942 /// ParseLogical
03943 ///  ::= ArithmeticOps TypeAndValue ',' Value {
03944 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
03945                             unsigned Opc) {
03946   LocTy Loc; Value *LHS, *RHS;
03947   if (ParseTypeAndValue(LHS, Loc, PFS) ||
03948       ParseToken(lltok::comma, "expected ',' in logical operation") ||
03949       ParseValue(LHS->getType(), RHS, PFS))
03950     return true;
03951 
03952   if (!LHS->getType()->isIntOrIntVectorTy())
03953     return Error(Loc,"instruction requires integer or integer vector operands");
03954 
03955   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
03956   return false;
03957 }
03958 
03959 
03960 /// ParseCompare
03961 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
03962 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
03963 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
03964                             unsigned Opc) {
03965   // Parse the integer/fp comparison predicate.
03966   LocTy Loc;
03967   unsigned Pred;
03968   Value *LHS, *RHS;
03969   if (ParseCmpPredicate(Pred, Opc) ||
03970       ParseTypeAndValue(LHS, Loc, PFS) ||
03971       ParseToken(lltok::comma, "expected ',' after compare value") ||
03972       ParseValue(LHS->getType(), RHS, PFS))
03973     return true;
03974 
03975   if (Opc == Instruction::FCmp) {
03976     if (!LHS->getType()->isFPOrFPVectorTy())
03977       return Error(Loc, "fcmp requires floating point operands");
03978     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
03979   } else {
03980     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
03981     if (!LHS->getType()->isIntOrIntVectorTy() &&
03982         !LHS->getType()->getScalarType()->isPointerTy())
03983       return Error(Loc, "icmp requires integer operands");
03984     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
03985   }
03986   return false;
03987 }
03988 
03989 //===----------------------------------------------------------------------===//
03990 // Other Instructions.
03991 //===----------------------------------------------------------------------===//
03992 
03993 
03994 /// ParseCast
03995 ///   ::= CastOpc TypeAndValue 'to' Type
03996 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
03997                          unsigned Opc) {
03998   LocTy Loc;
03999   Value *Op;
04000   Type *DestTy = nullptr;
04001   if (ParseTypeAndValue(Op, Loc, PFS) ||
04002       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
04003       ParseType(DestTy))
04004     return true;
04005 
04006   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
04007     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
04008     return Error(Loc, "invalid cast opcode for cast from '" +
04009                  getTypeString(Op->getType()) + "' to '" +
04010                  getTypeString(DestTy) + "'");
04011   }
04012   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
04013   return false;
04014 }
04015 
04016 /// ParseSelect
04017 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
04018 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
04019   LocTy Loc;
04020   Value *Op0, *Op1, *Op2;
04021   if (ParseTypeAndValue(Op0, Loc, PFS) ||
04022       ParseToken(lltok::comma, "expected ',' after select condition") ||
04023       ParseTypeAndValue(Op1, PFS) ||
04024       ParseToken(lltok::comma, "expected ',' after select value") ||
04025       ParseTypeAndValue(Op2, PFS))
04026     return true;
04027 
04028   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
04029     return Error(Loc, Reason);
04030 
04031   Inst = SelectInst::Create(Op0, Op1, Op2);
04032   return false;
04033 }
04034 
04035 /// ParseVA_Arg
04036 ///   ::= 'va_arg' TypeAndValue ',' Type
04037 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
04038   Value *Op;
04039   Type *EltTy = nullptr;
04040   LocTy TypeLoc;
04041   if (ParseTypeAndValue(Op, PFS) ||
04042       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
04043       ParseType(EltTy, TypeLoc))
04044     return true;
04045 
04046   if (!EltTy->isFirstClassType())
04047     return Error(TypeLoc, "va_arg requires operand with first class type");
04048 
04049   Inst = new VAArgInst(Op, EltTy);
04050   return false;
04051 }
04052 
04053 /// ParseExtractElement
04054 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
04055 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
04056   LocTy Loc;
04057   Value *Op0, *Op1;
04058   if (ParseTypeAndValue(Op0, Loc, PFS) ||
04059       ParseToken(lltok::comma, "expected ',' after extract value") ||
04060       ParseTypeAndValue(Op1, PFS))
04061     return true;
04062 
04063   if (!ExtractElementInst::isValidOperands(Op0, Op1))
04064     return Error(Loc, "invalid extractelement operands");
04065 
04066   Inst = ExtractElementInst::Create(Op0, Op1);
04067   return false;
04068 }
04069 
04070 /// ParseInsertElement
04071 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
04072 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
04073   LocTy Loc;
04074   Value *Op0, *Op1, *Op2;
04075   if (ParseTypeAndValue(Op0, Loc, PFS) ||
04076       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
04077       ParseTypeAndValue(Op1, PFS) ||
04078       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
04079       ParseTypeAndValue(Op2, PFS))
04080     return true;
04081 
04082   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
04083     return Error(Loc, "invalid insertelement operands");
04084 
04085   Inst = InsertElementInst::Create(Op0, Op1, Op2);
04086   return false;
04087 }
04088 
04089 /// ParseShuffleVector
04090 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
04091 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
04092   LocTy Loc;
04093   Value *Op0, *Op1, *Op2;
04094   if (ParseTypeAndValue(Op0, Loc, PFS) ||
04095       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
04096       ParseTypeAndValue(Op1, PFS) ||
04097       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
04098       ParseTypeAndValue(Op2, PFS))
04099     return true;
04100 
04101   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
04102     return Error(Loc, "invalid shufflevector operands");
04103 
04104   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
04105   return false;
04106 }
04107 
04108 /// ParsePHI
04109 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
04110 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
04111   Type *Ty = nullptr;  LocTy TypeLoc;
04112   Value *Op0, *Op1;
04113 
04114   if (ParseType(Ty, TypeLoc) ||
04115       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
04116       ParseValue(Ty, Op0, PFS) ||
04117       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
04118       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
04119       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
04120     return true;
04121 
04122   bool AteExtraComma = false;
04123   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
04124   while (1) {
04125     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
04126 
04127     if (!EatIfPresent(lltok::comma))
04128       break;
04129 
04130     if (Lex.getKind() == lltok::MetadataVar) {
04131       AteExtraComma = true;
04132       break;
04133     }
04134 
04135     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
04136         ParseValue(Ty, Op0, PFS) ||
04137         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
04138         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
04139         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
04140       return true;
04141   }
04142 
04143   if (!Ty->isFirstClassType())
04144     return Error(TypeLoc, "phi node must have first class type");
04145 
04146   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
04147   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
04148     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
04149   Inst = PN;
04150   return AteExtraComma ? InstExtraComma : InstNormal;
04151 }
04152 
04153 /// ParseLandingPad
04154 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
04155 /// Clause
04156 ///   ::= 'catch' TypeAndValue
04157 ///   ::= 'filter'
04158 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
04159 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
04160   Type *Ty = nullptr; LocTy TyLoc;
04161   Value *PersFn; LocTy PersFnLoc;
04162 
04163   if (ParseType(Ty, TyLoc) ||
04164       ParseToken(lltok::kw_personality, "expected 'personality'") ||
04165       ParseTypeAndValue(PersFn, PersFnLoc, PFS))
04166     return true;
04167 
04168   LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
04169   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
04170 
04171   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
04172     LandingPadInst::ClauseType CT;
04173     if (EatIfPresent(lltok::kw_catch))
04174       CT = LandingPadInst::Catch;
04175     else if (EatIfPresent(lltok::kw_filter))
04176       CT = LandingPadInst::Filter;
04177     else
04178       return TokError("expected 'catch' or 'filter' clause type");
04179 
04180     Value *V;
04181     LocTy VLoc;
04182     if (ParseTypeAndValue(V, VLoc, PFS)) {
04183       delete LP;
04184       return true;
04185     }
04186 
04187     // A 'catch' type expects a non-array constant. A filter clause expects an
04188     // array constant.
04189     if (CT == LandingPadInst::Catch) {
04190       if (isa<ArrayType>(V->getType()))
04191         Error(VLoc, "'catch' clause has an invalid type");
04192     } else {
04193       if (!isa<ArrayType>(V->getType()))
04194         Error(VLoc, "'filter' clause has an invalid type");
04195     }
04196 
04197     LP->addClause(cast<Constant>(V));
04198   }
04199 
04200   Inst = LP;
04201   return false;
04202 }
04203 
04204 /// ParseCall
04205 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
04206 ///       ParameterList OptionalAttrs
04207 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
04208 ///       ParameterList OptionalAttrs
04209 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
04210 ///       ParameterList OptionalAttrs
04211 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
04212                          CallInst::TailCallKind TCK) {
04213   AttrBuilder RetAttrs, FnAttrs;
04214   std::vector<unsigned> FwdRefAttrGrps;
04215   LocTy BuiltinLoc;
04216   unsigned CC;
04217   Type *RetType = nullptr;
04218   LocTy RetTypeLoc;
04219   ValID CalleeID;
04220   SmallVector<ParamInfo, 16> ArgList;
04221   LocTy CallLoc = Lex.getLoc();
04222 
04223   if ((TCK != CallInst::TCK_None &&
04224        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
04225       ParseOptionalCallingConv(CC) ||
04226       ParseOptionalReturnAttrs(RetAttrs) ||
04227       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
04228       ParseValID(CalleeID) ||
04229       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
04230                          PFS.getFunction().isVarArg()) ||
04231       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
04232                                  BuiltinLoc))
04233     return true;
04234 
04235   // If RetType is a non-function pointer type, then this is the short syntax
04236   // for the call, which means that RetType is just the return type.  Infer the
04237   // rest of the function argument types from the arguments that are present.
04238   PointerType *PFTy = nullptr;
04239   FunctionType *Ty = nullptr;
04240   if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
04241       !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
04242     // Pull out the types of all of the arguments...
04243     std::vector<Type*> ParamTypes;
04244     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
04245       ParamTypes.push_back(ArgList[i].V->getType());
04246 
04247     if (!FunctionType::isValidReturnType(RetType))
04248       return Error(RetTypeLoc, "Invalid result type for LLVM function");
04249 
04250     Ty = FunctionType::get(RetType, ParamTypes, false);
04251     PFTy = PointerType::getUnqual(Ty);
04252   }
04253 
04254   // Look up the callee.
04255   Value *Callee;
04256   if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
04257 
04258   // Set up the Attribute for the function.
04259   SmallVector<AttributeSet, 8> Attrs;
04260   if (RetAttrs.hasAttributes())
04261     Attrs.push_back(AttributeSet::get(RetType->getContext(),
04262                                       AttributeSet::ReturnIndex,
04263                                       RetAttrs));
04264 
04265   SmallVector<Value*, 8> Args;
04266 
04267   // Loop through FunctionType's arguments and ensure they are specified
04268   // correctly.  Also, gather any parameter attributes.
04269   FunctionType::param_iterator I = Ty->param_begin();
04270   FunctionType::param_iterator E = Ty->param_end();
04271   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
04272     Type *ExpectedTy = nullptr;
04273     if (I != E) {
04274       ExpectedTy = *I++;
04275     } else if (!Ty->isVarArg()) {
04276       return Error(ArgList[i].Loc, "too many arguments specified");
04277     }
04278 
04279     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
04280       return Error(ArgList[i].Loc, "argument is not of expected type '" +
04281                    getTypeString(ExpectedTy) + "'");
04282     Args.push_back(ArgList[i].V);
04283     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
04284       AttrBuilder B(ArgList[i].Attrs, i + 1);
04285       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
04286     }
04287   }
04288 
04289   if (I != E)
04290     return Error(CallLoc, "not enough parameters specified for call");
04291 
04292   if (FnAttrs.hasAttributes())
04293     Attrs.push_back(AttributeSet::get(RetType->getContext(),
04294                                       AttributeSet::FunctionIndex,
04295                                       FnAttrs));
04296 
04297   // Finish off the Attribute and check them
04298   AttributeSet PAL = AttributeSet::get(Context, Attrs);
04299 
04300   CallInst *CI = CallInst::Create(Callee, Args);
04301   CI->setTailCallKind(TCK);
04302   CI->setCallingConv(CC);
04303   CI->setAttributes(PAL);
04304   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
04305   Inst = CI;
04306   return false;
04307 }
04308 
04309 //===----------------------------------------------------------------------===//
04310 // Memory Instructions.
04311 //===----------------------------------------------------------------------===//
04312 
04313 /// ParseAlloc
04314 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
04315 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
04316   Value *Size = nullptr;
04317   LocTy SizeLoc;
04318   unsigned Alignment = 0;
04319   Type *Ty = nullptr;
04320 
04321   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
04322 
04323   if (ParseType(Ty)) return true;
04324 
04325   bool AteExtraComma = false;
04326   if (EatIfPresent(lltok::comma)) {
04327     if (Lex.getKind() == lltok::kw_align) {
04328       if (ParseOptionalAlignment(Alignment)) return true;
04329     } else if (Lex.getKind() == lltok::MetadataVar) {
04330       AteExtraComma = true;
04331     } else {
04332       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
04333           ParseOptionalCommaAlign(Alignment, AteExtraComma))
04334         return true;
04335     }
04336   }
04337 
04338   if (Size && !Size->getType()->isIntegerTy())
04339     return Error(SizeLoc, "element count must have integer type");
04340 
04341   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
04342   AI->setUsedWithInAlloca(IsInAlloca);
04343   Inst = AI;
04344   return AteExtraComma ? InstExtraComma : InstNormal;
04345 }
04346 
04347 /// ParseLoad
04348 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
04349 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
04350 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
04351 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
04352   Value *Val; LocTy Loc;
04353   unsigned Alignment = 0;
04354   bool AteExtraComma = false;
04355   bool isAtomic = false;
04356   AtomicOrdering Ordering = NotAtomic;
04357   SynchronizationScope Scope = CrossThread;
04358 
04359   if (Lex.getKind() == lltok::kw_atomic) {
04360     isAtomic = true;
04361     Lex.Lex();
04362   }
04363 
04364   bool isVolatile = false;
04365   if (Lex.getKind() == lltok::kw_volatile) {
04366     isVolatile = true;
04367     Lex.Lex();
04368   }
04369 
04370   if (ParseTypeAndValue(Val, Loc, PFS) ||
04371       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
04372       ParseOptionalCommaAlign(Alignment, AteExtraComma))
04373     return true;
04374 
04375   if (!Val->getType()->isPointerTy() ||
04376       !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
04377     return Error(Loc, "load operand must be a pointer to a first class type");
04378   if (isAtomic && !Alignment)
04379     return Error(Loc, "atomic load must have explicit non-zero alignment");
04380   if (Ordering == Release || Ordering == AcquireRelease)
04381     return Error(Loc, "atomic load cannot use Release ordering");
04382 
04383   Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
04384   return AteExtraComma ? InstExtraComma : InstNormal;
04385 }
04386 
04387 /// ParseStore
04388 
04389 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
04390 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
04391 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
04392 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
04393   Value *Val, *Ptr; LocTy Loc, PtrLoc;
04394   unsigned Alignment = 0;
04395   bool AteExtraComma = false;
04396   bool isAtomic = false;
04397   AtomicOrdering Ordering = NotAtomic;
04398   SynchronizationScope Scope = CrossThread;
04399 
04400   if (Lex.getKind() == lltok::kw_atomic) {
04401     isAtomic = true;
04402     Lex.Lex();
04403   }
04404 
04405   bool isVolatile = false;
04406   if (Lex.getKind() == lltok::kw_volatile) {
04407     isVolatile = true;
04408     Lex.Lex();
04409   }
04410 
04411   if (ParseTypeAndValue(Val, Loc, PFS) ||
04412       ParseToken(lltok::comma, "expected ',' after store operand") ||
04413       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
04414       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
04415       ParseOptionalCommaAlign(Alignment, AteExtraComma))
04416     return true;
04417 
04418   if (!Ptr->getType()->isPointerTy())
04419     return Error(PtrLoc, "store operand must be a pointer");
04420   if (!Val->getType()->isFirstClassType())
04421     return Error(Loc, "store operand must be a first class value");
04422   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
04423     return Error(Loc, "stored value and pointer type do not match");
04424   if (isAtomic && !Alignment)
04425     return Error(Loc, "atomic store must have explicit non-zero alignment");
04426   if (Ordering == Acquire || Ordering == AcquireRelease)
04427     return Error(Loc, "atomic store cannot use Acquire ordering");
04428 
04429   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
04430   return AteExtraComma ? InstExtraComma : InstNormal;
04431 }
04432 
04433 /// ParseCmpXchg
04434 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
04435 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
04436 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
04437   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
04438   bool AteExtraComma = false;
04439   AtomicOrdering SuccessOrdering = NotAtomic;
04440   AtomicOrdering FailureOrdering = NotAtomic;
04441   SynchronizationScope Scope = CrossThread;
04442   bool isVolatile = false;
04443   bool isWeak = false;
04444 
04445   if (EatIfPresent(lltok::kw_weak))
04446     isWeak = true;
04447 
04448   if (EatIfPresent(lltok::kw_volatile))
04449     isVolatile = true;
04450 
04451   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
04452       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
04453       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
04454       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
04455       ParseTypeAndValue(New, NewLoc, PFS) ||
04456       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
04457       ParseOrdering(FailureOrdering))
04458     return true;
04459 
04460   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
04461     return TokError("cmpxchg cannot be unordered");
04462   if (SuccessOrdering < FailureOrdering)
04463     return TokError("cmpxchg must be at least as ordered on success as failure");
04464   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
04465     return TokError("cmpxchg failure ordering cannot include release semantics");
04466   if (!Ptr->getType()->isPointerTy())
04467     return Error(PtrLoc, "cmpxchg operand must be a pointer");
04468   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
04469     return Error(CmpLoc, "compare value and pointer type do not match");
04470   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
04471     return Error(NewLoc, "new value and pointer type do not match");
04472   if (!New->getType()->isIntegerTy())
04473     return Error(NewLoc, "cmpxchg operand must be an integer");
04474   unsigned Size = New->getType()->getPrimitiveSizeInBits();
04475   if (Size < 8 || (Size & (Size - 1)))
04476     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
04477                          " integer");
04478 
04479   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
04480       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
04481   CXI->setVolatile(isVolatile);
04482   CXI->setWeak(isWeak);
04483   Inst = CXI;
04484   return AteExtraComma ? InstExtraComma : InstNormal;
04485 }
04486 
04487 /// ParseAtomicRMW
04488 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
04489 ///       'singlethread'? AtomicOrdering
04490 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
04491   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
04492   bool AteExtraComma = false;
04493   AtomicOrdering Ordering = NotAtomic;
04494   SynchronizationScope Scope = CrossThread;
04495   bool isVolatile = false;
04496   AtomicRMWInst::BinOp Operation;
04497 
04498   if (EatIfPresent(lltok::kw_volatile))
04499     isVolatile = true;
04500 
04501   switch (Lex.getKind()) {
04502   default: return TokError("expected binary operation in atomicrmw");
04503   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
04504   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
04505   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
04506   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
04507   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
04508   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
04509   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
04510   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
04511   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
04512   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
04513   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
04514   }
04515   Lex.Lex();  // Eat the operation.
04516 
04517   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
04518       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
04519       ParseTypeAndValue(Val, ValLoc, PFS) ||
04520       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
04521     return true;
04522 
04523   if (Ordering == Unordered)
04524     return TokError("atomicrmw cannot be unordered");
04525   if (!Ptr->getType()->isPointerTy())
04526     return Error(PtrLoc, "atomicrmw operand must be a pointer");
04527   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
04528     return Error(ValLoc, "atomicrmw value and pointer type do not match");
04529   if (!Val->getType()->isIntegerTy())
04530     return Error(ValLoc, "atomicrmw operand must be an integer");
04531   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
04532   if (Size < 8 || (Size & (Size - 1)))
04533     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
04534                          " integer");
04535 
04536   AtomicRMWInst *RMWI =
04537     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
04538   RMWI->setVolatile(isVolatile);
04539   Inst = RMWI;
04540   return AteExtraComma ? InstExtraComma : InstNormal;
04541 }
04542 
04543 /// ParseFence
04544 ///   ::= 'fence' 'singlethread'? AtomicOrdering
04545 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
04546   AtomicOrdering Ordering = NotAtomic;
04547   SynchronizationScope Scope = CrossThread;
04548   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
04549     return true;
04550 
04551   if (Ordering == Unordered)
04552     return TokError("fence cannot be unordered");
04553   if (Ordering == Monotonic)
04554     return TokError("fence cannot be monotonic");
04555 
04556   Inst = new FenceInst(Context, Ordering, Scope);
04557   return InstNormal;
04558 }
04559 
04560 /// ParseGetElementPtr
04561 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
04562 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
04563   Value *Ptr = nullptr;
04564   Value *Val = nullptr;
04565   LocTy Loc, EltLoc;
04566 
04567   bool InBounds = EatIfPresent(lltok::kw_inbounds);
04568 
04569   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
04570 
04571   Type *BaseType = Ptr->getType();
04572   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
04573   if (!BasePointerType)
04574     return Error(Loc, "base of getelementptr must be a pointer");
04575 
04576   SmallVector<Value*, 16> Indices;
04577   bool AteExtraComma = false;
04578   while (EatIfPresent(lltok::comma)) {
04579     if (Lex.getKind() == lltok::MetadataVar) {
04580       AteExtraComma = true;
04581       break;
04582     }
04583     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
04584     if (!Val->getType()->getScalarType()->isIntegerTy())
04585       return Error(EltLoc, "getelementptr index must be an integer");
04586     if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
04587       return Error(EltLoc, "getelementptr index type missmatch");
04588     if (Val->getType()->isVectorTy()) {
04589       unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
04590       unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
04591       if (ValNumEl != PtrNumEl)
04592         return Error(EltLoc,
04593           "getelementptr vector index has a wrong number of elements");
04594     }
04595     Indices.push_back(Val);
04596   }
04597 
04598   if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
04599     return Error(Loc, "base element of getelementptr must be sized");
04600 
04601   if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
04602     return Error(Loc, "invalid getelementptr indices");
04603   Inst = GetElementPtrInst::Create(Ptr, Indices);
04604   if (InBounds)
04605     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
04606   return AteExtraComma ? InstExtraComma : InstNormal;
04607 }
04608 
04609 /// ParseExtractValue
04610 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
04611 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
04612   Value *Val; LocTy Loc;
04613   SmallVector<unsigned, 4> Indices;
04614   bool AteExtraComma;
04615   if (ParseTypeAndValue(Val, Loc, PFS) ||
04616       ParseIndexList(Indices, AteExtraComma))
04617     return true;
04618 
04619   if (!Val->getType()->isAggregateType())
04620     return Error(Loc, "extractvalue operand must be aggregate type");
04621 
04622   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
04623     return Error(Loc, "invalid indices for extractvalue");
04624   Inst = ExtractValueInst::Create(Val, Indices);
04625   return AteExtraComma ? InstExtraComma : InstNormal;
04626 }
04627 
04628 /// ParseInsertValue
04629 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
04630 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
04631   Value *Val0, *Val1; LocTy Loc0, Loc1;
04632   SmallVector<unsigned, 4> Indices;
04633   bool AteExtraComma;
04634   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
04635       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
04636       ParseTypeAndValue(Val1, Loc1, PFS) ||
04637       ParseIndexList(Indices, AteExtraComma))
04638     return true;
04639 
04640   if (!Val0->getType()->isAggregateType())
04641     return Error(Loc0, "insertvalue operand must be aggregate type");
04642 
04643   if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
04644     return Error(Loc0, "invalid indices for insertvalue");
04645   Inst = InsertValueInst::Create(Val0, Val1, Indices);
04646   return AteExtraComma ? InstExtraComma : InstNormal;
04647 }
04648 
04649 //===----------------------------------------------------------------------===//
04650 // Embedded metadata.
04651 //===----------------------------------------------------------------------===//
04652 
04653 /// ParseMDNodeVector
04654 ///   ::= Element (',' Element)*
04655 /// Element
04656 ///   ::= 'null' | TypeAndValue
04657 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
04658                                  PerFunctionState *PFS) {
04659   // Check for an empty list.
04660   if (Lex.getKind() == lltok::rbrace)
04661     return false;
04662 
04663   do {
04664     // Null is a special case since it is typeless.
04665     if (EatIfPresent(lltok::kw_null)) {
04666       Elts.push_back(nullptr);
04667       continue;
04668     }
04669 
04670     Value *V = nullptr;
04671     if (ParseTypeAndValue(V, PFS)) return true;
04672     Elts.push_back(V);
04673   } while (EatIfPresent(lltok::comma));
04674 
04675   return false;
04676 }
04677 
04678 //===----------------------------------------------------------------------===//
04679 // Use-list order directives.
04680 //===----------------------------------------------------------------------===//
04681 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
04682                                 SMLoc Loc) {
04683   if (V->use_empty())
04684     return Error(Loc, "value has no uses");
04685 
04686   unsigned NumUses = 0;
04687   SmallDenseMap<const Use *, unsigned, 16> Order;
04688   for (const Use &U : V->uses()) {
04689     if (++NumUses > Indexes.size())
04690       break;
04691     Order[&U] = Indexes[NumUses - 1];
04692   }
04693   if (NumUses < 2)
04694     return Error(Loc, "value only has one use");
04695   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
04696     return Error(Loc, "wrong number of indexes, expected " +
04697                           Twine(std::distance(V->use_begin(), V->use_end())));
04698 
04699   V->sortUseList([&](const Use &L, const Use &R) {
04700     return Order.lookup(&L) < Order.lookup(&R);
04701   });
04702   return false;
04703 }
04704 
04705 /// ParseUseListOrderIndexes
04706 ///   ::= '{' uint32 (',' uint32)+ '}'
04707 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
04708   SMLoc Loc = Lex.getLoc();
04709   if (ParseToken(lltok::lbrace, "expected '{' here"))
04710     return true;
04711   if (Lex.getKind() == lltok::rbrace)
04712     return Lex.Error("expected non-empty list of uselistorder indexes");
04713 
04714   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
04715   // indexes should be distinct numbers in the range [0, size-1], and should
04716   // not be in order.
04717   unsigned Offset = 0;
04718   unsigned Max = 0;
04719   bool IsOrdered = true;
04720   assert(Indexes.empty() && "Expected empty order vector");
04721   do {
04722     unsigned Index;
04723     if (ParseUInt32(Index))
04724       return true;
04725 
04726     // Update consistency checks.
04727     Offset += Index - Indexes.size();
04728     Max = std::max(Max, Index);
04729     IsOrdered &= Index == Indexes.size();
04730 
04731     Indexes.push_back(Index);
04732   } while (EatIfPresent(lltok::comma));
04733 
04734   if (ParseToken(lltok::rbrace, "expected '}' here"))
04735     return true;
04736 
04737   if (Indexes.size() < 2)
04738     return Error(Loc, "expected >= 2 uselistorder indexes");
04739   if (Offset != 0 || Max >= Indexes.size())
04740     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
04741   if (IsOrdered)
04742     return Error(Loc, "expected uselistorder indexes to change the order");
04743 
04744   return false;
04745 }
04746 
04747 /// ParseUseListOrder
04748 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
04749 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
04750   SMLoc Loc = Lex.getLoc();
04751   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
04752     return true;
04753 
04754   Value *V;
04755   SmallVector<unsigned, 16> Indexes;
04756   if (ParseTypeAndValue(V, PFS) ||
04757       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
04758       ParseUseListOrderIndexes(Indexes))
04759     return true;
04760 
04761   return sortUseListOrder(V, Indexes, Loc);
04762 }
04763 
04764 /// ParseUseListOrderBB
04765 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
04766 bool LLParser::ParseUseListOrderBB() {
04767   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
04768   SMLoc Loc = Lex.getLoc();
04769   Lex.Lex();
04770 
04771   ValID Fn, Label;
04772   SmallVector<unsigned, 16> Indexes;
04773   if (ParseValID(Fn) ||
04774       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
04775       ParseValID(Label) ||
04776       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
04777       ParseUseListOrderIndexes(Indexes))
04778     return true;
04779 
04780   // Check the function.
04781   GlobalValue *GV;
04782   if (Fn.Kind == ValID::t_GlobalName)
04783     GV = M->getNamedValue(Fn.StrVal);
04784   else if (Fn.Kind == ValID::t_GlobalID)
04785     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
04786   else
04787     return Error(Fn.Loc, "expected function name in uselistorder_bb");
04788   if (!GV)
04789     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
04790   auto *F = dyn_cast<Function>(GV);
04791   if (!F)
04792     return Error(Fn.Loc, "expected function name in uselistorder_bb");
04793   if (F->isDeclaration())
04794     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
04795 
04796   // Check the basic block.
04797   if (Label.Kind == ValID::t_LocalID)
04798     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
04799   if (Label.Kind != ValID::t_LocalName)
04800     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
04801   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
04802   if (!V)
04803     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
04804   if (!isa<BasicBlock>(V))
04805     return Error(Label.Loc, "expected basic block in uselistorder_bb");
04806 
04807   return sortUseListOrder(V, Indexes, Loc);
04808 }