LCOV - code coverage report
Current view: top level - lib/AsmParser - LLParser.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 2701 3020 89.4 %
Date: 2018-02-19 17:12:42 Functions: 275 276 99.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- LLParser.cpp - Parser Class ---------------------------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : //  This file defines the parser class for .ll files.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "LLParser.h"
      15             : #include "llvm/ADT/DenseMap.h"
      16             : #include "llvm/ADT/None.h"
      17             : #include "llvm/ADT/Optional.h"
      18             : #include "llvm/ADT/STLExtras.h"
      19             : #include "llvm/ADT/SmallPtrSet.h"
      20             : #include "llvm/AsmParser/SlotMapping.h"
      21             : #include "llvm/BinaryFormat/Dwarf.h"
      22             : #include "llvm/IR/Argument.h"
      23             : #include "llvm/IR/AutoUpgrade.h"
      24             : #include "llvm/IR/BasicBlock.h"
      25             : #include "llvm/IR/CallingConv.h"
      26             : #include "llvm/IR/Comdat.h"
      27             : #include "llvm/IR/Constants.h"
      28             : #include "llvm/IR/DebugInfoMetadata.h"
      29             : #include "llvm/IR/DerivedTypes.h"
      30             : #include "llvm/IR/Function.h"
      31             : #include "llvm/IR/GlobalIFunc.h"
      32             : #include "llvm/IR/GlobalObject.h"
      33             : #include "llvm/IR/InlineAsm.h"
      34             : #include "llvm/IR/Instruction.h"
      35             : #include "llvm/IR/Instructions.h"
      36             : #include "llvm/IR/Intrinsics.h"
      37             : #include "llvm/IR/LLVMContext.h"
      38             : #include "llvm/IR/Metadata.h"
      39             : #include "llvm/IR/Module.h"
      40             : #include "llvm/IR/Operator.h"
      41             : #include "llvm/IR/Type.h"
      42             : #include "llvm/IR/Value.h"
      43             : #include "llvm/IR/ValueSymbolTable.h"
      44             : #include "llvm/Support/Casting.h"
      45             : #include "llvm/Support/ErrorHandling.h"
      46             : #include "llvm/Support/MathExtras.h"
      47             : #include "llvm/Support/SaveAndRestore.h"
      48             : #include "llvm/Support/raw_ostream.h"
      49             : #include <algorithm>
      50             : #include <cassert>
      51             : #include <cstring>
      52             : #include <iterator>
      53             : #include <vector>
      54             : 
      55             : using namespace llvm;
      56             : 
      57          49 : static std::string getTypeString(Type *T) {
      58             :   std::string Result;
      59          49 :   raw_string_ostream Tmp(Result);
      60             :   Tmp << *T;
      61          49 :   return Tmp.str();
      62             : }
      63             : 
      64             : /// Run: module ::= toplevelentity*
      65       30510 : bool LLParser::Run() {
      66             :   // Prime the lexer.
      67       30510 :   Lex.Lex();
      68             : 
      69       30510 :   if (Context.shouldDiscardValueNames())
      70           0 :     return Error(
      71             :         Lex.getLoc(),
      72             :         "Can't read textual IR with a Context that discards named Values");
      73             : 
      74       60805 :   return ParseTopLevelEntities() ||
      75       30295 :          ValidateEndOfModule();
      76             : }
      77             : 
      78         509 : bool LLParser::parseStandaloneConstantValue(Constant *&C,
      79             :                                             const SlotMapping *Slots) {
      80         509 :   restoreParsingState(Slots);
      81         509 :   Lex.Lex();
      82             : 
      83         509 :   Type *Ty = nullptr;
      84         509 :   if (ParseType(Ty) || parseConstantValue(Ty, C))
      85             :     return true;
      86         504 :   if (Lex.getKind() != lltok::Eof)
      87           2 :     return Error(Lex.getLoc(), "expected end of string");
      88             :   return false;
      89             : }
      90             : 
      91          22 : bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
      92             :                                     const SlotMapping *Slots) {
      93          22 :   restoreParsingState(Slots);
      94          22 :   Lex.Lex();
      95             : 
      96          22 :   Read = 0;
      97          22 :   SMLoc Start = Lex.getLoc();
      98          22 :   Ty = nullptr;
      99          22 :   if (ParseType(Ty))
     100             :     return true;
     101          22 :   SMLoc End = Lex.getLoc();
     102          22 :   Read = End.getPointer() - Start.getPointer();
     103             : 
     104          22 :   return false;
     105             : }
     106             : 
     107         531 : void LLParser::restoreParsingState(const SlotMapping *Slots) {
     108         531 :   if (!Slots)
     109             :     return;
     110         499 :   NumberedVals = Slots->GlobalValues;
     111             :   NumberedMetadata = Slots->MetadataNodes;
     112        1047 :   for (const auto &I : Slots->NamedTypes)
     113             :     NamedTypes.insert(
     114          49 :         std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
     115         523 :   for (const auto &I : Slots->Types)
     116             :     NumberedTypes.insert(
     117          48 :         std::make_pair(I.first, std::make_pair(I.second, LocTy())));
     118             : }
     119             : 
     120             : /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
     121             : /// module.
     122       30295 : bool LLParser::ValidateEndOfModule() {
     123             :   // Handle any function attribute group forward references.
     124      418007 :   for (const auto &RAG : ForwardRefAttrGroups) {
     125      387712 :     Value *V = RAG.first;
     126             :     const std::vector<unsigned> &Attrs = RAG.second;
     127             :     AttrBuilder B;
     128             : 
     129      387712 :     for (const auto &Attr : Attrs)
     130       49816 :       B.merge(NumberedAttrBuilders[Attr]);
     131             : 
     132             :     if (Function *Fn = dyn_cast<Function>(V)) {
     133      265026 :       AttributeList AS = Fn->getAttributes();
     134      265026 :       AttrBuilder FnAttrs(AS.getFnAttributes());
     135      265026 :       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
     136             : 
     137      265026 :       FnAttrs.merge(B);
     138             : 
     139             :       // If the alignment was parsed as an attribute, move to the alignment
     140             :       // field.
     141      265026 :       if (FnAttrs.hasAlignmentAttr()) {
     142           0 :         Fn->setAlignment(FnAttrs.getAlignment());
     143           0 :         FnAttrs.removeAttribute(Attribute::Alignment);
     144             :       }
     145             : 
     146      265026 :       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
     147      530052 :                             AttributeSet::get(Context, FnAttrs));
     148             :       Fn->setAttributes(AS);
     149             :     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
     150      120847 :       AttributeList AS = CI->getAttributes();
     151      120847 :       AttrBuilder FnAttrs(AS.getFnAttributes());
     152      120847 :       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
     153      120847 :       FnAttrs.merge(B);
     154      120847 :       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
     155      241694 :                             AttributeSet::get(Context, FnAttrs));
     156             :       CI->setAttributes(AS);
     157             :     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
     158        1808 :       AttributeList AS = II->getAttributes();
     159        1808 :       AttrBuilder FnAttrs(AS.getFnAttributes());
     160        1808 :       AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
     161        1808 :       FnAttrs.merge(B);
     162        1808 :       AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
     163        3616 :                             AttributeSet::get(Context, FnAttrs));
     164             :       II->setAttributes(AS);
     165             :     } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
     166          31 :       AttrBuilder Attrs(GV->getAttributes());
     167          31 :       Attrs.merge(B);
     168          31 :       GV->setAttributes(AttributeSet::get(Context,Attrs));
     169             :     } else {
     170           0 :       llvm_unreachable("invalid object with forward attribute group reference");
     171             :     }
     172             :   }
     173             : 
     174             :   // If there are entries in ForwardRefBlockAddresses at this point, the
     175             :   // function was never defined.
     176       30295 :   if (!ForwardRefBlockAddresses.empty())
     177           0 :     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
     178             :                  "expected function name in blockaddress");
     179             : 
     180       30796 :   for (const auto &NT : NumberedTypes)
     181         501 :     if (NT.second.second.isValid())
     182             :       return Error(NT.second.second,
     183           0 :                    "use of undefined type '%" + Twine(NT.first) + "'");
     184             : 
     185             :   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
     186       71695 :        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
     187       11107 :     if (I->second.second.isValid())
     188             :       return Error(I->second.second,
     189           4 :                    "use of undefined type named '" + I->getKey() + "'");
     190             : 
     191       30293 :   if (!ForwardRefComdats.empty())
     192           1 :     return Error(ForwardRefComdats.begin()->second,
     193           2 :                  "use of undefined comdat '$" +
     194           2 :                      ForwardRefComdats.begin()->first + "'");
     195             : 
     196       30292 :   if (!ForwardRefVals.empty())
     197           0 :     return Error(ForwardRefVals.begin()->second.second,
     198           0 :                  "use of undefined value '@" + ForwardRefVals.begin()->first +
     199             :                  "'");
     200             : 
     201       30292 :   if (!ForwardRefValIDs.empty())
     202             :     return Error(ForwardRefValIDs.begin()->second.second,
     203           0 :                  "use of undefined value '@" +
     204           0 :                  Twine(ForwardRefValIDs.begin()->first) + "'");
     205             : 
     206       30292 :   if (!ForwardRefMDNodes.empty())
     207             :     return Error(ForwardRefMDNodes.begin()->second.second,
     208           2 :                  "use of undefined metadata '!" +
     209           6 :                  Twine(ForwardRefMDNodes.begin()->first) + "'");
     210             : 
     211             :   // Resolve metadata cycles.
     212       80081 :   for (auto &N : NumberedMetadata) {
     213       49791 :     if (N.second && !N.second->isResolved())
     214         174 :       N.second->resolveCycles();
     215             :   }
     216             : 
     217       37294 :   for (auto *Inst : InstsWithTBAATag) {
     218             :     MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
     219             :     assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
     220        3502 :     auto *UpgradedMD = UpgradeTBAANode(*MD);
     221        3502 :     if (MD != UpgradedMD)
     222         243 :       Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
     223             :   }
     224             : 
     225             :   // Look for intrinsic functions and CallInst that need to be upgraded
     226      591900 :   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
     227      265660 :     UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
     228             : 
     229             :   // Some types could be renamed during loading if several modules are
     230             :   // loaded in the same LLVMContext (LTO scenario). In this case we should
     231             :   // remangle intrinsics names as well.
     232      587180 :   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
     233             :     Function *F = &*FI++;
     234      263300 :     if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
     235           0 :       F->replaceAllUsesWith(Remangled.getValue());
     236           0 :       F->eraseFromParent();
     237             :     }
     238             :   }
     239             : 
     240       30290 :   if (UpgradeDebugInfo)
     241       12080 :     llvm::UpgradeDebugInfo(*M);
     242             : 
     243       30290 :   UpgradeModuleFlags(*M);
     244       30290 :   UpgradeSectionAttributes(*M);
     245             : 
     246       30290 :   if (!Slots)
     247             :     return false;
     248             :   // Initialize the slot mapping.
     249             :   // Because by this point we've parsed and validated everything, we can "steal"
     250             :   // the mapping from LLParser as it doesn't need it anymore.
     251         661 :   Slots->GlobalValues = std::move(NumberedVals);
     252         661 :   Slots->MetadataNodes = std::move(NumberedMetadata);
     253        1365 :   for (const auto &I : NamedTypes)
     254          86 :     Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
     255         664 :   for (const auto &I : NumberedTypes)
     256           6 :     Slots->Types.insert(std::make_pair(I.first, I.second.first));
     257             : 
     258             :   return false;
     259             : }
     260             : 
     261             : //===----------------------------------------------------------------------===//
     262             : // Top-Level Entities
     263             : //===----------------------------------------------------------------------===//
     264             : 
     265       30510 : bool LLParser::ParseTopLevelEntities() {
     266             :   while (true) {
     267      410650 :     switch (Lex.getKind()) {
     268           3 :     default:         return TokError("expected top-level entity");
     269             :     case lltok::Eof: return false;
     270       53651 :     case lltok::kw_declare: if (ParseDeclare()) return true; break;
     271      211476 :     case lltok::kw_define:  if (ParseDefine()) return true; break;
     272         325 :     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
     273       12240 :     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
     274        1446 :     case lltok::kw_source_filename:
     275        1446 :       if (ParseSourceFileName())
     276             :         return true;
     277             :       break;
     278           0 :     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
     279         501 :     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
     280       11119 :     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
     281         674 :     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
     282       25534 :     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
     283         596 :     case lltok::ComdatVar:  if (parseComdat()) return true; break;
     284       49859 :     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
     285        4932 :     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
     286        7870 :     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
     287         117 :     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
     288          12 :     case lltok::kw_uselistorder_bb:
     289          12 :       if (ParseUseListOrderBB())
     290             :         return true;
     291             :       break;
     292             :     }
     293             :   }
     294             : }
     295             : 
     296             : /// toplevelentity
     297             : ///   ::= 'module' 'asm' STRINGCONSTANT
     298         325 : bool LLParser::ParseModuleAsm() {
     299             :   assert(Lex.getKind() == lltok::kw_module);
     300         325 :   Lex.Lex();
     301             : 
     302             :   std::string AsmStr;
     303         650 :   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
     304         325 :       ParseStringConstant(AsmStr)) return true;
     305             : 
     306         650 :   M->appendModuleInlineAsm(AsmStr);
     307         325 :   return false;
     308             : }
     309             : 
     310             : /// toplevelentity
     311             : ///   ::= 'target' 'triple' '=' STRINGCONSTANT
     312             : ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
     313       12240 : bool LLParser::ParseTargetDefinition() {
     314             :   assert(Lex.getKind() == lltok::kw_target);
     315             :   std::string Str;
     316       24480 :   switch (Lex.Lex()) {
     317           0 :   default: return TokError("unknown target property");
     318        4754 :   case lltok::kw_triple:
     319             :     Lex.Lex();
     320        9508 :     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
     321        4754 :         ParseStringConstant(Str))
     322             :       return true;
     323        9508 :     M->setTargetTriple(Str);
     324        4754 :     return false;
     325        7486 :   case lltok::kw_datalayout:
     326             :     Lex.Lex();
     327       14972 :     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
     328        7486 :         ParseStringConstant(Str))
     329             :       return true;
     330        7486 :     if (DataLayoutStr.empty())
     331       14968 :       M->setDataLayout(Str);
     332             :     return false;
     333             :   }
     334             : }
     335             : 
     336             : /// toplevelentity
     337             : ///   ::= 'source_filename' '=' STRINGCONSTANT
     338        1446 : bool LLParser::ParseSourceFileName() {
     339             :   assert(Lex.getKind() == lltok::kw_source_filename);
     340             :   std::string Str;
     341        1446 :   Lex.Lex();
     342        2892 :   if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
     343        1446 :       ParseStringConstant(Str))
     344             :     return true;
     345        2892 :   M->setSourceFileName(Str);
     346        1446 :   return false;
     347             : }
     348             : 
     349             : /// toplevelentity
     350             : ///   ::= 'deplibs' '=' '[' ']'
     351             : ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
     352             : /// FIXME: Remove in 4.0. Currently parse, but ignore.
     353           0 : bool LLParser::ParseDepLibs() {
     354             :   assert(Lex.getKind() == lltok::kw_deplibs);
     355           0 :   Lex.Lex();
     356           0 :   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
     357           0 :       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
     358             :     return true;
     359             : 
     360             :   if (EatIfPresent(lltok::rsquare))
     361             :     return false;
     362             : 
     363             :   do {
     364             :     std::string Str;
     365           0 :     if (ParseStringConstant(Str)) return true;
     366             :   } while (EatIfPresent(lltok::comma));
     367             : 
     368           0 :   return ParseToken(lltok::rsquare, "expected ']' at end of list");
     369             : }
     370             : 
     371             : /// ParseUnnamedType:
     372             : ///   ::= LocalVarID '=' 'type' type
     373         501 : bool LLParser::ParseUnnamedType() {
     374         501 :   LocTy TypeLoc = Lex.getLoc();
     375         501 :   unsigned TypeID = Lex.getUIntVal();
     376         501 :   Lex.Lex(); // eat LocalVarID;
     377             : 
     378        1002 :   if (ParseToken(lltok::equal, "expected '=' after name") ||
     379         501 :       ParseToken(lltok::kw_type, "expected 'type' after '='"))
     380             :     return true;
     381             : 
     382         501 :   Type *Result = nullptr;
     383         501 :   if (ParseStructDefinition(TypeLoc, "",
     384         501 :                             NumberedTypes[TypeID], Result)) return true;
     385             : 
     386        1002 :   if (!isa<StructType>(Result)) {
     387           4 :     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
     388           4 :     if (Entry.first)
     389           0 :       return Error(TypeLoc, "non-struct types may not be recursive");
     390           4 :     Entry.first = Result;
     391           4 :     Entry.second = SMLoc();
     392             :   }
     393             : 
     394             :   return false;
     395             : }
     396             : 
     397             : /// toplevelentity
     398             : ///   ::= LocalVar '=' 'type' type
     399       11119 : bool LLParser::ParseNamedType() {
     400             :   std::string Name = Lex.getStrVal();
     401       11119 :   LocTy NameLoc = Lex.getLoc();
     402       11119 :   Lex.Lex();  // eat LocalVar.
     403             : 
     404       22238 :   if (ParseToken(lltok::equal, "expected '=' after name") ||
     405       11119 :       ParseToken(lltok::kw_type, "expected 'type' after name"))
     406             :     return true;
     407             : 
     408       11119 :   Type *Result = nullptr;
     409       22238 :   if (ParseStructDefinition(NameLoc, Name,
     410             :                             NamedTypes[Name], Result)) return true;
     411             : 
     412       22238 :   if (!isa<StructType>(Result)) {
     413             :     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
     414         440 :     if (Entry.first)
     415           0 :       return Error(NameLoc, "non-struct types may not be recursive");
     416         440 :     Entry.first = Result;
     417         440 :     Entry.second = SMLoc();
     418             :   }
     419             : 
     420             :   return false;
     421             : }
     422             : 
     423             : /// toplevelentity
     424             : ///   ::= 'declare' FunctionHeader
     425       53651 : bool LLParser::ParseDeclare() {
     426             :   assert(Lex.getKind() == lltok::kw_declare);
     427       53651 :   Lex.Lex();
     428             : 
     429             :   std::vector<std::pair<unsigned, MDNode *>> MDs;
     430       53691 :   while (Lex.getKind() == lltok::MetadataVar) {
     431             :     unsigned MDK;
     432             :     MDNode *N;
     433          20 :     if (ParseMetadataAttachment(MDK, N))
     434           0 :       return true;
     435          20 :     MDs.push_back({MDK, N});
     436             :   }
     437             : 
     438             :   Function *F;
     439       53651 :   if (ParseFunctionHeader(F, false))
     440             :     return true;
     441       53663 :   for (auto &MD : MDs)
     442          20 :     F->addMetadata(MD.first, *MD.second);
     443             :   return false;
     444             : }
     445             : 
     446             : /// toplevelentity
     447             : ///   ::= 'define' FunctionHeader (!dbg !56)* '{' ...
     448      211476 : bool LLParser::ParseDefine() {
     449             :   assert(Lex.getKind() == lltok::kw_define);
     450      211476 :   Lex.Lex();
     451             : 
     452             :   Function *F;
     453      422946 :   return ParseFunctionHeader(F, true) ||
     454      422946 :          ParseOptionalFunctionMetadata(*F) ||
     455      422946 :          ParseFunctionBody(*F);
     456             : }
     457             : 
     458             : /// ParseGlobalType
     459             : ///   ::= 'constant'
     460             : ///   ::= 'global'
     461       25226 : bool LLParser::ParseGlobalType(bool &IsConstant) {
     462       25226 :   if (Lex.getKind() == lltok::kw_constant)
     463        4109 :     IsConstant = true;
     464       21117 :   else if (Lex.getKind() == lltok::kw_global)
     465       21117 :     IsConstant = false;
     466             :   else {
     467           0 :     IsConstant = false;
     468           0 :     return TokError("expected 'global' or 'constant'");
     469             :   }
     470       25226 :   Lex.Lex();
     471       25226 :   return false;
     472             : }
     473             : 
     474      291325 : bool LLParser::ParseOptionalUnnamedAddr(
     475             :     GlobalVariable::UnnamedAddr &UnnamedAddr) {
     476             :   if (EatIfPresent(lltok::kw_unnamed_addr))
     477        2704 :     UnnamedAddr = GlobalValue::UnnamedAddr::Global;
     478             :   else if (EatIfPresent(lltok::kw_local_unnamed_addr))
     479        4448 :     UnnamedAddr = GlobalValue::UnnamedAddr::Local;
     480             :   else
     481      284173 :     UnnamedAddr = GlobalValue::UnnamedAddr::None;
     482      291325 :   return false;
     483             : }
     484             : 
     485             : /// ParseUnnamedGlobal:
     486             : ///   OptionalVisibility (ALIAS | IFUNC) ...
     487             : ///   OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
     488             : ///   OptionalDLLStorageClass
     489             : ///                                                     ...   -> global variable
     490             : ///   GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
     491             : ///   GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
     492             : ///                OptionalDLLStorageClass
     493             : ///                                                     ...   -> global variable
     494         674 : bool LLParser::ParseUnnamedGlobal() {
     495        1348 :   unsigned VarID = NumberedVals.size();
     496             :   std::string Name;
     497         674 :   LocTy NameLoc = Lex.getLoc();
     498             : 
     499             :   // Handle the GlobalID form.
     500         674 :   if (Lex.getKind() == lltok::GlobalID) {
     501         674 :     if (Lex.getUIntVal() != VarID)
     502           0 :       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
     503           0 :                    Twine(VarID) + "'");
     504         674 :     Lex.Lex(); // eat GlobalID;
     505             : 
     506         674 :     if (ParseToken(lltok::equal, "expected '=' after name"))
     507             :       return true;
     508             :   }
     509             : 
     510             :   bool HasLinkage;
     511             :   unsigned Linkage, Visibility, DLLStorageClass;
     512             :   bool DSOLocal;
     513             :   GlobalVariable::ThreadLocalMode TLM;
     514             :   GlobalVariable::UnnamedAddr UnnamedAddr;
     515         674 :   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
     516         674 :                            DSOLocal) ||
     517        1348 :       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
     518             :     return true;
     519             : 
     520         674 :   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
     521         670 :     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
     522         670 :                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
     523             : 
     524           4 :   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
     525           4 :                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
     526             : }
     527             : 
     528             : /// ParseNamedGlobal:
     529             : ///   GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
     530             : ///   GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
     531             : ///                 OptionalVisibility OptionalDLLStorageClass
     532             : ///                                                     ...   -> global variable
     533       25534 : bool LLParser::ParseNamedGlobal() {
     534             :   assert(Lex.getKind() == lltok::GlobalVar);
     535       25534 :   LocTy NameLoc = Lex.getLoc();
     536             :   std::string Name = Lex.getStrVal();
     537       25534 :   Lex.Lex();
     538             : 
     539             :   bool HasLinkage;
     540             :   unsigned Linkage, Visibility, DLLStorageClass;
     541             :   bool DSOLocal;
     542             :   GlobalVariable::ThreadLocalMode TLM;
     543             :   GlobalVariable::UnnamedAddr UnnamedAddr;
     544       51067 :   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
     545       25533 :       ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
     546       25533 :                            DSOLocal) ||
     547       76600 :       ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
     548             :     return true;
     549             : 
     550       25533 :   if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
     551       24560 :     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
     552       24560 :                        DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
     553             : 
     554         973 :   return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
     555         973 :                              DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
     556             : }
     557             : 
     558         596 : bool LLParser::parseComdat() {
     559             :   assert(Lex.getKind() == lltok::ComdatVar);
     560             :   std::string Name = Lex.getStrVal();
     561         596 :   LocTy NameLoc = Lex.getLoc();
     562         596 :   Lex.Lex();
     563             : 
     564         596 :   if (ParseToken(lltok::equal, "expected '=' here"))
     565             :     return true;
     566             : 
     567         596 :   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
     568           0 :     return TokError("expected comdat type");
     569             : 
     570             :   Comdat::SelectionKind SK;
     571         596 :   switch (Lex.getKind()) {
     572             :   default:
     573           0 :     return TokError("unknown selection kind");
     574             :   case lltok::kw_any:
     575             :     SK = Comdat::Any;
     576             :     break;
     577           5 :   case lltok::kw_exactmatch:
     578             :     SK = Comdat::ExactMatch;
     579           5 :     break;
     580          45 :   case lltok::kw_largest:
     581             :     SK = Comdat::Largest;
     582          45 :     break;
     583           7 :   case lltok::kw_noduplicates:
     584             :     SK = Comdat::NoDuplicates;
     585           7 :     break;
     586           7 :   case lltok::kw_samesize:
     587             :     SK = Comdat::SameSize;
     588           7 :     break;
     589             :   }
     590             :   Lex.Lex();
     591             : 
     592             :   // See if the comdat was forward referenced, if so, use the comdat.
     593         596 :   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
     594         596 :   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
     595        1194 :   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
     596           4 :     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
     597             : 
     598             :   Comdat *C;
     599        1190 :   if (I != ComdatSymTab.end())
     600           1 :     C = &I->second;
     601             :   else
     602        1188 :     C = M->getOrInsertComdat(Name);
     603             :   C->setSelectionKind(SK);
     604             : 
     605         595 :   return false;
     606             : }
     607             : 
     608             : // MDString:
     609             : //   ::= '!' STRINGCONSTANT
     610       10919 : bool LLParser::ParseMDString(MDString *&Result) {
     611             :   std::string Str;
     612       10919 :   if (ParseStringConstant(Str)) return true;
     613       10919 :   Result = MDString::get(Context, Str);
     614       10919 :   return false;
     615             : }
     616             : 
     617             : // MDNode:
     618             : //   ::= '!' MDNodeNumber
     619      103537 : bool LLParser::ParseMDNodeID(MDNode *&Result) {
     620             :   // !{ ..., !42, ... }
     621      103537 :   LocTy IDLoc = Lex.getLoc();
     622      103537 :   unsigned MID = 0;
     623      103537 :   if (ParseUInt32(MID))
     624             :     return true;
     625             : 
     626             :   // If not a forward reference, just return it now.
     627             :   if (NumberedMetadata.count(MID)) {
     628      110354 :     Result = NumberedMetadata[MID];
     629       55177 :     return false;
     630             :   }
     631             : 
     632             :   // Otherwise, create MDNode forward reference.
     633       48360 :   auto &FwdRef = ForwardRefMDNodes[MID];
     634       48360 :   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
     635             : 
     636       48360 :   Result = FwdRef.first.get();
     637       48360 :   NumberedMetadata[MID].reset(Result);
     638       48360 :   return false;
     639             : }
     640             : 
     641             : /// ParseNamedMetadata:
     642             : ///   !foo = !{ !1, !2 }
     643        4932 : bool LLParser::ParseNamedMetadata() {
     644             :   assert(Lex.getKind() == lltok::MetadataVar);
     645             :   std::string Name = Lex.getStrVal();
     646        4932 :   Lex.Lex();
     647             : 
     648        9864 :   if (ParseToken(lltok::equal, "expected '=' here") ||
     649        9864 :       ParseToken(lltok::exclaim, "Expected '!' here") ||
     650        4932 :       ParseToken(lltok::lbrace, "Expected '{' here"))
     651             :     return true;
     652             : 
     653        9864 :   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
     654        4932 :   if (Lex.getKind() != lltok::rbrace)
     655             :     do {
     656        8788 :       MDNode *N = nullptr;
     657             :       // Parse DIExpressions inline as a special case. They are still MDNodes,
     658             :       // so they can still appear in named metadata. Remove this logic if they
     659             :       // become plain Metadata.
     660        8828 :       if (Lex.getKind() == lltok::MetadataVar &&
     661             :           Lex.getStrVal() == "DIExpression") {
     662          40 :         if (ParseDIExpression(N, /*IsDistinct=*/false))
     663           0 :           return true;
     664       17496 :       } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
     665        8748 :                  ParseMDNodeID(N)) {
     666             :         return true;
     667             :       }
     668        8788 :       NMD->addOperand(N);
     669             :     } while (EatIfPresent(lltok::comma));
     670             : 
     671        4932 :   return ParseToken(lltok::rbrace, "expected end of metadata node");
     672             : }
     673             : 
     674             : /// ParseStandaloneMetadata:
     675             : ///   !42 = !{...}
     676       49859 : bool LLParser::ParseStandaloneMetadata() {
     677             :   assert(Lex.getKind() == lltok::exclaim);
     678       49859 :   Lex.Lex();
     679       49859 :   unsigned MetadataID = 0;
     680             : 
     681             :   MDNode *Init;
     682       99718 :   if (ParseUInt32(MetadataID) ||
     683       49859 :       ParseToken(lltok::equal, "expected '=' here"))
     684             :     return true;
     685             : 
     686             :   // Detect common error, from old metadata syntax.
     687       49859 :   if (Lex.getKind() == lltok::Type)
     688           1 :     return TokError("unexpected type in metadata definition");
     689             : 
     690             :   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
     691       49858 :   if (Lex.getKind() == lltok::MetadataVar) {
     692       32411 :     if (ParseSpecializedMDNode(Init, IsDistinct))
     693             :       return true;
     694       34894 :   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
     695       17447 :              ParseMDTuple(Init, IsDistinct))
     696             :     return true;
     697             : 
     698             :   // See if this was forward referenced, if so, handle it.
     699             :   auto FI = ForwardRefMDNodes.find(MetadataID);
     700       49805 :   if (FI != ForwardRefMDNodes.end()) {
     701       48356 :     FI->second.first->replaceAllUsesWith(Init);
     702             :     ForwardRefMDNodes.erase(FI);
     703             : 
     704             :     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
     705             :   } else {
     706             :     if (NumberedMetadata.count(MetadataID))
     707           0 :       return TokError("Metadata id is already used");
     708        1449 :     NumberedMetadata[MetadataID].reset(Init);
     709             :   }
     710             : 
     711             :   return false;
     712             : }
     713             : 
     714             : static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
     715        4919 :   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
     716             :          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
     717             : }
     718             : 
     719             : // If there was an explicit dso_local, update GV. In the absence of an explicit
     720             : // dso_local we keep the default value.
     721             : static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
     722      291291 :   if (DSOLocal)
     723             :     GV.setDSOLocal(true);
     724             : }
     725             : 
     726             : /// parseIndirectSymbol:
     727             : ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier 
     728             : ///                     OptionalVisibility OptionalDLLStorageClass
     729             : ///                     OptionalThreadLocal OptionalUnnamedAddr
     730             : //                      'alias|ifunc' IndirectSymbol
     731             : ///
     732             : /// IndirectSymbol
     733             : ///   ::= TypeAndValue
     734             : ///
     735             : /// Everything through OptionalUnnamedAddr has already been parsed.
     736             : ///
     737         977 : bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
     738             :                                    unsigned L, unsigned Visibility,
     739             :                                    unsigned DLLStorageClass, bool DSOLocal,
     740             :                                    GlobalVariable::ThreadLocalMode TLM,
     741             :                                    GlobalVariable::UnnamedAddr UnnamedAddr) {
     742             :   bool IsAlias;
     743         977 :   if (Lex.getKind() == lltok::kw_alias)
     744             :     IsAlias = true;
     745          37 :   else if (Lex.getKind() == lltok::kw_ifunc)
     746             :     IsAlias = false;
     747             :   else
     748           0 :     llvm_unreachable("Not an alias or ifunc!");
     749         977 :   Lex.Lex();
     750             : 
     751             :   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
     752             : 
     753         977 :   if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
     754           0 :     return Error(NameLoc, "invalid linkage type for alias");
     755             : 
     756             :   if (!isValidVisibilityForLinkage(Visibility, L))
     757           4 :     return Error(NameLoc,
     758             :                  "symbol with local linkage must have default visibility");
     759             : 
     760             :   Type *Ty;
     761         973 :   LocTy ExplicitTypeLoc = Lex.getLoc();
     762        1946 :   if (ParseType(Ty) ||
     763         973 :       ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
     764             :     return true;
     765             : 
     766             :   Constant *Aliasee;
     767         973 :   LocTy AliaseeLoc = Lex.getLoc();
     768        1792 :   if (Lex.getKind() != lltok::kw_bitcast &&
     769         720 :       Lex.getKind() != lltok::kw_getelementptr &&
     770        1682 :       Lex.getKind() != lltok::kw_addrspacecast &&
     771             :       Lex.getKind() != lltok::kw_inttoptr) {
     772         701 :     if (ParseGlobalTypeAndValue(Aliasee))
     773             :       return true;
     774             :   } else {
     775             :     // The bitcast dest type is not present, it is implied by the dest type.
     776         543 :     ValID ID;
     777         272 :     if (ParseValID(ID))
     778           1 :       return true;
     779         271 :     if (ID.Kind != ValID::t_Constant)
     780           0 :       return Error(AliaseeLoc, "invalid aliasee");
     781         271 :     Aliasee = ID.ConstantVal;
     782             :   }
     783             : 
     784         972 :   Type *AliaseeType = Aliasee->getType();
     785             :   auto *PTy = dyn_cast<PointerType>(AliaseeType);
     786             :   if (!PTy)
     787           0 :     return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
     788             :   unsigned AddrSpace = PTy->getAddressSpace();
     789             : 
     790         972 :   if (IsAlias && Ty != PTy->getElementType())
     791           1 :     return Error(
     792             :         ExplicitTypeLoc,
     793             :         "explicit pointee type doesn't match operand's pointee type");
     794             : 
     795        1045 :   if (!IsAlias && !PTy->getElementType()->isFunctionTy())
     796           0 :     return Error(
     797             :         ExplicitTypeLoc,
     798             :         "explicit pointee type should be a function type");
     799             : 
     800             :   GlobalValue *GVal = nullptr;
     801             : 
     802             :   // See if the alias was forward referenced, if so, prepare to replace the
     803             :   // forward reference.
     804         971 :   if (!Name.empty()) {
     805        1934 :     GVal = M->getNamedValue(Name);
     806         967 :     if (GVal) {
     807          55 :       if (!ForwardRefVals.erase(Name))
     808           4 :         return Error(NameLoc, "redefinition of global '@" + Name + "'");
     809             :     }
     810             :   } else {
     811           8 :     auto I = ForwardRefValIDs.find(NumberedVals.size());
     812           4 :     if (I != ForwardRefValIDs.end()) {
     813           1 :       GVal = I->second.first;
     814             :       ForwardRefValIDs.erase(I);
     815             :     }
     816             :   }
     817             : 
     818             :   // Okay, create the alias but do not insert it into the module yet.
     819             :   std::unique_ptr<GlobalIndirectSymbol> GA;
     820         970 :   if (IsAlias)
     821        1866 :     GA.reset(GlobalAlias::create(Ty, AddrSpace,
     822             :                                  (GlobalValue::LinkageTypes)Linkage, Name,
     823             :                                  Aliasee, /*Parent*/ nullptr));
     824             :   else
     825          74 :     GA.reset(GlobalIFunc::create(Ty, AddrSpace,
     826             :                                  (GlobalValue::LinkageTypes)Linkage, Name,
     827             :                                  Aliasee, /*Parent*/ nullptr));
     828             :   GA->setThreadLocalMode(TLM);
     829             :   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
     830             :   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
     831             :   GA->setUnnamedAddr(UnnamedAddr);
     832             :   maybeSetDSOLocal(DSOLocal, *GA);
     833             : 
     834         970 :   if (Name.empty())
     835           8 :     NumberedVals.push_back(GA.get());
     836             : 
     837         970 :   if (GVal) {
     838             :     // Verify that types agree.
     839          55 :     if (GVal->getType() != GA->getType())
     840           0 :       return Error(
     841             :           ExplicitTypeLoc,
     842             :           "forward reference and definition of alias have different types");
     843             : 
     844             :     // If they agree, just RAUW the old value with the alias and remove the
     845             :     // forward ref info.
     846          55 :     GVal->replaceAllUsesWith(GA.get());
     847          55 :     GVal->eraseFromParent();
     848             :   }
     849             : 
     850             :   // Insert into the module, we know its name won't collide now.
     851         970 :   if (IsAlias)
     852         933 :     M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
     853             :   else
     854          37 :     M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
     855             :   assert(GA->getName() == Name && "Should not be a name conflict!");
     856             : 
     857             :   // The module owns this now
     858             :   GA.release();
     859             : 
     860             :   return false;
     861             : }
     862             : 
     863             : /// ParseGlobal
     864             : ///   ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
     865             : ///       OptionalVisibility OptionalDLLStorageClass
     866             : ///       OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
     867             : ///       OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
     868             : ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
     869             : ///       OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
     870             : ///       OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
     871             : ///       Const OptionalAttrs
     872             : ///
     873             : /// Everything up to and including OptionalUnnamedAddr has been parsed
     874             : /// already.
     875             : ///
     876       25230 : bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
     877             :                            unsigned Linkage, bool HasLinkage,
     878             :                            unsigned Visibility, unsigned DLLStorageClass,
     879             :                            bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
     880             :                            GlobalVariable::UnnamedAddr UnnamedAddr) {
     881             :   if (!isValidVisibilityForLinkage(Visibility, Linkage))
     882           4 :     return Error(NameLoc,
     883             :                  "symbol with local linkage must have default visibility");
     884             : 
     885             :   unsigned AddrSpace;
     886             :   bool IsConstant, IsExternallyInitialized;
     887             :   LocTy IsExternallyInitializedLoc;
     888             :   LocTy TyLoc;
     889             : 
     890       25226 :   Type *Ty = nullptr;
     891       25226 :   if (ParseOptionalAddrSpace(AddrSpace) ||
     892             :       ParseOptionalToken(lltok::kw_externally_initialized,
     893             :                          IsExternallyInitialized,
     894       25226 :                          &IsExternallyInitializedLoc) ||
     895       75678 :       ParseGlobalType(IsConstant) ||
     896             :       ParseType(Ty, TyLoc))
     897             :     return true;
     898             : 
     899             :   // If the linkage is specified and is external, then no initializer is
     900             :   // present.
     901       25224 :   Constant *Init = nullptr;
     902       25224 :   if (!HasLinkage ||
     903             :       !GlobalValue::isValidDeclarationLinkage(
     904             :           (GlobalValue::LinkageTypes)Linkage)) {
     905       18888 :     if (ParseGlobalValue(Ty, Init))
     906             :       return true;
     907             :   }
     908             : 
     909       50424 :   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
     910           2 :     return Error(TyLoc, "invalid type for global variable");
     911             : 
     912             :   GlobalValue *GVal = nullptr;
     913             : 
     914             :   // See if the global was forward referenced, if so, use the global.
     915       25210 :   if (!Name.empty()) {
     916       49092 :     GVal = M->getNamedValue(Name);
     917       24546 :     if (GVal) {
     918         347 :       if (!ForwardRefVals.erase(Name))
     919           4 :         return Error(NameLoc, "redefinition of global '@" + Name + "'");
     920             :     }
     921             :   } else {
     922        1328 :     auto I = ForwardRefValIDs.find(NumberedVals.size());
     923         664 :     if (I != ForwardRefValIDs.end()) {
     924          22 :       GVal = I->second.first;
     925             :       ForwardRefValIDs.erase(I);
     926             :     }
     927             :   }
     928             : 
     929             :   GlobalVariable *GV;
     930       24567 :   if (!GVal) {
     931       49682 :     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
     932             :                             Name, nullptr, GlobalVariable::NotThreadLocal,
     933       49682 :                             AddrSpace);
     934             :   } else {
     935         368 :     if (GVal->getValueType() != Ty)
     936           1 :       return Error(TyLoc,
     937             :             "forward reference and definition of global have different types");
     938             : 
     939             :     GV = cast<GlobalVariable>(GVal);
     940             : 
     941             :     // Move the forward-reference to the correct spot in the module.
     942         734 :     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
     943             :   }
     944             : 
     945       25208 :   if (Name.empty())
     946        1328 :     NumberedVals.push_back(GV);
     947             : 
     948             :   // Set the parsed properties on the global.
     949       25208 :   if (Init)
     950       18873 :     GV->setInitializer(Init);
     951       25208 :   GV->setConstant(IsConstant);
     952             :   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
     953             :   maybeSetDSOLocal(DSOLocal, *GV);
     954             :   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
     955             :   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
     956             :   GV->setExternallyInitialized(IsExternallyInitialized);
     957             :   GV->setThreadLocalMode(TLM);
     958             :   GV->setUnnamedAddr(UnnamedAddr);
     959             : 
     960             :   // Parse attributes on the global.
     961       40387 :   while (Lex.getKind() == lltok::comma) {
     962       15179 :     Lex.Lex();
     963             : 
     964       15179 :     if (Lex.getKind() == lltok::kw_section) {
     965             :       Lex.Lex();
     966        1068 :       GV->setSection(Lex.getStrVal());
     967         534 :       if (ParseToken(lltok::StringConstant, "expected global section string"))
     968             :         return true;
     969       14645 :     } else if (Lex.getKind() == lltok::kw_align) {
     970             :       unsigned Alignment;
     971       13278 :       if (ParseOptionalAlignment(Alignment)) return true;
     972       13278 :       GV->setAlignment(Alignment);
     973        1367 :     } else if (Lex.getKind() == lltok::MetadataVar) {
     974        1030 :       if (ParseGlobalObjectMetadataAttachment(*GV))
     975             :         return true;
     976             :     } else {
     977             :       Comdat *C;
     978         337 :       if (parseOptionalComdat(Name, C))
     979           0 :         return true;
     980         337 :       if (C)
     981             :         GV->setComdat(C);
     982             :       else
     983           0 :         return TokError("unknown global variable property!");
     984             :     }
     985             :   }
     986             : 
     987             :   AttrBuilder Attrs;
     988       25208 :   LocTy BuiltinLoc;
     989             :   std::vector<unsigned> FwdRefAttrGrps;
     990       25208 :   if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
     991             :     return true;
     992       50410 :   if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
     993          31 :     GV->setAttributes(AttributeSet::get(Context, Attrs));
     994          31 :     ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
     995             :   }
     996             : 
     997             :   return false;
     998             : }
     999             : 
    1000             : /// ParseUnnamedAttrGrp
    1001             : ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
    1002        7870 : bool LLParser::ParseUnnamedAttrGrp() {
    1003             :   assert(Lex.getKind() == lltok::kw_attributes);
    1004        7870 :   LocTy AttrGrpLoc = Lex.getLoc();
    1005        7870 :   Lex.Lex();
    1006             : 
    1007        7870 :   if (Lex.getKind() != lltok::AttrGrpID)
    1008           1 :     return TokError("expected attribute group id");
    1009             : 
    1010        7869 :   unsigned VarID = Lex.getUIntVal();
    1011             :   std::vector<unsigned> unused;
    1012        7869 :   LocTy BuiltinLoc;
    1013             :   Lex.Lex();
    1014             : 
    1015       15738 :   if (ParseToken(lltok::equal, "expected '=' here") ||
    1016       15738 :       ParseToken(lltok::lbrace, "expected '{' here") ||
    1017        7869 :       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
    1018       15738 :                                  BuiltinLoc) ||
    1019        7869 :       ParseToken(lltok::rbrace, "expected end of attribute group"))
    1020             :     return true;
    1021             : 
    1022        7869 :   if (!NumberedAttrBuilders[VarID].hasAttributes())
    1023           0 :     return Error(AttrGrpLoc, "attribute group has no attributes");
    1024             : 
    1025             :   return false;
    1026             : }
    1027             : 
    1028             : /// ParseFnAttributeValuePairs
    1029             : ///   ::= <attr> | <attr> '=' <value>
    1030      420857 : bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
    1031             :                                           std::vector<unsigned> &FwdRefAttrGrps,
    1032             :                                           bool inAttrGrp, LocTy &BuiltinLoc) {
    1033             :   bool HaveError = false;
    1034             : 
    1035      420857 :   B.clear();
    1036             : 
    1037             :   while (true) {
    1038      603529 :     lltok::Kind Token = Lex.getKind();
    1039      603529 :     if (Token == lltok::kw_builtin)
    1040          36 :       BuiltinLoc = Lex.getLoc();
    1041      603529 :     switch (Token) {
    1042      412986 :     default:
    1043      412986 :       if (!inAttrGrp) return HaveError;
    1044           0 :       return Error(Lex.getLoc(), "unterminated attribute group");
    1045             :     case lltok::rbrace:
    1046             :       // Finished.
    1047             :       return false;
    1048             : 
    1049       49816 :     case lltok::AttrGrpID: {
    1050             :       // Allow a function to reference an attribute group:
    1051             :       //
    1052             :       //   define void @foo() #1 { ... }
    1053       49816 :       if (inAttrGrp)
    1054           0 :         HaveError |=
    1055           0 :           Error(Lex.getLoc(),
    1056             :               "cannot have an attribute group reference in an attribute group");
    1057             : 
    1058       49816 :       unsigned AttrGrpNum = Lex.getUIntVal();
    1059       49816 :       if (inAttrGrp) break;
    1060             : 
    1061             :       // Save the reference to the attribute group. We'll fill it in later.
    1062       49816 :       FwdRefAttrGrps.push_back(AttrGrpNum);
    1063       49816 :       break;
    1064             :     }
    1065             :     // Target-dependent attributes:
    1066       16449 :     case lltok::StringConstant: {
    1067       16449 :       if (ParseStringAttribute(B))
    1068             :         return true;
    1069       16449 :       continue;
    1070             :     }
    1071             : 
    1072             :     // Target-independent attributes:
    1073         610 :     case lltok::kw_align: {
    1074             :       // As a hack, we allow function alignment to be initially parsed as an
    1075             :       // attribute on a function declaration/definition or added to an attribute
    1076             :       // group and later moved to the alignment field.
    1077             :       unsigned Alignment;
    1078         610 :       if (inAttrGrp) {
    1079           1 :         Lex.Lex();
    1080           2 :         if (ParseToken(lltok::equal, "expected '=' here") ||
    1081           1 :             ParseUInt32(Alignment))
    1082           0 :           return true;
    1083             :       } else {
    1084         609 :         if (ParseOptionalAlignment(Alignment))
    1085             :           return true;
    1086             :       }
    1087         610 :       B.addAlignmentAttr(Alignment);
    1088         610 :       continue;
    1089             :     }
    1090          47 :     case lltok::kw_alignstack: {
    1091             :       unsigned Alignment;
    1092          47 :       if (inAttrGrp) {
    1093          13 :         Lex.Lex();
    1094          26 :         if (ParseToken(lltok::equal, "expected '=' here") ||
    1095          13 :             ParseUInt32(Alignment))
    1096           0 :           return true;
    1097             :       } else {
    1098          34 :         if (ParseOptionalStackAlignment(Alignment))
    1099             :           return true;
    1100             :       }
    1101          47 :       B.addStackAlignmentAttr(Alignment);
    1102          47 :       continue;
    1103             :     }
    1104             :     case lltok::kw_allocsize: {
    1105             :       unsigned ElemSizeArg;
    1106             :       Optional<unsigned> NumElemsArg;
    1107             :       // inAttrGrp doesn't matter; we only support allocsize(a[, b])
    1108          23 :       if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
    1109             :         return true;
    1110          22 :       B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
    1111             :       continue;
    1112             :     }
    1113         237 :     case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
    1114         279 :     case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
    1115          36 :     case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
    1116          32 :     case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
    1117         163 :     case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
    1118          18 :     case lltok::kw_inaccessiblememonly:
    1119          18 :       B.addAttribute(Attribute::InaccessibleMemOnly); break;
    1120          15 :     case lltok::kw_inaccessiblemem_or_argmemonly:
    1121          15 :       B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
    1122         145 :     case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
    1123           9 :     case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
    1124         647 :     case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
    1125          23 :     case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
    1126         115 :     case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
    1127          31 :     case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
    1128          46 :     case lltok::kw_noimplicitfloat:
    1129          46 :       B.addAttribute(Attribute::NoImplicitFloat); break;
    1130        1094 :     case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
    1131          41 :     case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
    1132         192 :     case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
    1133         466 :     case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
    1134         247 :     case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
    1135       74570 :     case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
    1136         112 :     case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
    1137        5348 :     case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
    1138       18622 :     case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
    1139        2300 :     case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
    1140          75 :     case lltok::kw_returns_twice:
    1141          75 :       B.addAttribute(Attribute::ReturnsTwice); break;
    1142         235 :     case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
    1143        5125 :     case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
    1144          72 :     case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
    1145          70 :     case lltok::kw_sspstrong:
    1146          70 :       B.addAttribute(Attribute::StackProtectStrong); break;
    1147         194 :     case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
    1148         323 :     case lltok::kw_sanitize_address:
    1149         323 :       B.addAttribute(Attribute::SanitizeAddress); break;
    1150          78 :     case lltok::kw_sanitize_hwaddress:
    1151          78 :       B.addAttribute(Attribute::SanitizeHWAddress); break;
    1152          66 :     case lltok::kw_sanitize_thread:
    1153          66 :       B.addAttribute(Attribute::SanitizeThread); break;
    1154         277 :     case lltok::kw_sanitize_memory:
    1155         277 :       B.addAttribute(Attribute::SanitizeMemory); break;
    1156           6 :     case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
    1157        4400 :     case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
    1158          19 :     case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
    1159             : 
    1160             :     // Error handling.
    1161             :     case lltok::kw_inreg:
    1162             :     case lltok::kw_signext:
    1163             :     case lltok::kw_zeroext:
    1164           0 :       HaveError |=
    1165           0 :         Error(Lex.getLoc(),
    1166             :               "invalid use of attribute on a function");
    1167           0 :       break;
    1168             :     case lltok::kw_byval:
    1169             :     case lltok::kw_dereferenceable:
    1170             :     case lltok::kw_dereferenceable_or_null:
    1171             :     case lltok::kw_inalloca:
    1172             :     case lltok::kw_nest:
    1173             :     case lltok::kw_noalias:
    1174             :     case lltok::kw_nocapture:
    1175             :     case lltok::kw_nonnull:
    1176             :     case lltok::kw_returned:
    1177             :     case lltok::kw_sret:
    1178             :     case lltok::kw_swifterror:
    1179             :     case lltok::kw_swiftself:
    1180           0 :       HaveError |=
    1181           0 :         Error(Lex.getLoc(),
    1182             :               "invalid use of parameter-only attribute on a function");
    1183       16449 :       break;
    1184             :     }
    1185             : 
    1186      165544 :     Lex.Lex();
    1187             :   }
    1188             : }
    1189             : 
    1190             : //===----------------------------------------------------------------------===//
    1191             : // GlobalValue Reference/Resolution Routines.
    1192             : //===----------------------------------------------------------------------===//
    1193             : 
    1194       33804 : static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
    1195             :                                               const std::string &Name) {
    1196       33804 :   if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
    1197       33408 :     return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
    1198             :   else
    1199             :     return new GlobalVariable(*M, PTy->getElementType(), false,
    1200             :                               GlobalValue::ExternalWeakLinkage, nullptr, Name,
    1201             :                               nullptr, GlobalVariable::NotThreadLocal,
    1202         396 :                               PTy->getAddressSpace());
    1203             : }
    1204             : 
    1205             : /// GetGlobalVal - Get a value with the specified name or ID, creating a
    1206             : /// forward reference record if needed.  This can return null if the value
    1207             : /// exists but does not have the right type.
    1208      186150 : GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
    1209             :                                     LocTy Loc) {
    1210             :   PointerType *PTy = dyn_cast<PointerType>(Ty);
    1211             :   if (!PTy) {
    1212           0 :     Error(Loc, "global variable reference must have pointer type");
    1213           0 :     return nullptr;
    1214             :   }
    1215             : 
    1216             :   // Look this name up in the normal function symbol table.
    1217             :   GlobalValue *Val =
    1218      186150 :     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
    1219             : 
    1220             :   // If this is a forward reference for the value, see if we already created a
    1221             :   // forward ref record.
    1222             :   if (!Val) {
    1223             :     auto I = ForwardRefVals.find(Name);
    1224       33763 :     if (I != ForwardRefVals.end())
    1225           0 :       Val = I->second.first;
    1226             :   }
    1227             : 
    1228             :   // If we have the value in the symbol table or fwd-ref table, return it.
    1229      186150 :   if (Val) {
    1230      152387 :     if (Val->getType() == Ty) return Val;
    1231          10 :     Error(Loc, "'@" + Name + "' defined with type '" +
    1232           8 :           getTypeString(Val->getType()) + "'");
    1233           2 :     return nullptr;
    1234             :   }
    1235             : 
    1236             :   // Otherwise, create a new forward reference for this value and remember it.
    1237       33763 :   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
    1238       33763 :   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
    1239       33763 :   return FwdVal;
    1240             : }
    1241             : 
    1242         643 : GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
    1243             :   PointerType *PTy = dyn_cast<PointerType>(Ty);
    1244             :   if (!PTy) {
    1245           0 :     Error(Loc, "global variable reference must have pointer type");
    1246           0 :     return nullptr;
    1247             :   }
    1248             : 
    1249        1880 :   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
    1250             : 
    1251             :   // If this is a forward reference for the value, see if we already created a
    1252             :   // forward ref record.
    1253         594 :   if (!Val) {
    1254             :     auto I = ForwardRefValIDs.find(ID);
    1255          49 :     if (I != ForwardRefValIDs.end())
    1256           8 :       Val = I->second.first;
    1257             :   }
    1258             : 
    1259             :   // If we have the value in the symbol table or fwd-ref table, return it.
    1260         643 :   if (Val) {
    1261         602 :     if (Val->getType() == Ty) return Val;
    1262           0 :     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
    1263           0 :           getTypeString(Val->getType()) + "'");
    1264           0 :     return nullptr;
    1265             :   }
    1266             : 
    1267             :   // Otherwise, create a new forward reference for this value and remember it.
    1268          82 :   GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
    1269          41 :   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
    1270          41 :   return FwdVal;
    1271             : }
    1272             : 
    1273             : //===----------------------------------------------------------------------===//
    1274             : // Comdat Reference/Resolution Routines.
    1275             : //===----------------------------------------------------------------------===//
    1276             : 
    1277         693 : Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
    1278             :   // Look this name up in the comdat symbol table.
    1279         693 :   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
    1280         693 :   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
    1281        1386 :   if (I != ComdatSymTab.end())
    1282         691 :     return &I->second;
    1283             : 
    1284             :   // Otherwise, create a new forward reference for this value and remember it.
    1285           4 :   Comdat *C = M->getOrInsertComdat(Name);
    1286           2 :   ForwardRefComdats[Name] = Loc;
    1287           2 :   return C;
    1288             : }
    1289             : 
    1290             : //===----------------------------------------------------------------------===//
    1291             : // Helper Routines.
    1292             : //===----------------------------------------------------------------------===//
    1293             : 
    1294             : /// ParseToken - If the current token has the specified kind, eat it and return
    1295             : /// success.  Otherwise, emit the specified error and return failure.
    1296     5699487 : bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
    1297     5699487 :   if (Lex.getKind() != T)
    1298           5 :     return TokError(ErrMsg);
    1299     5699482 :   Lex.Lex();
    1300     5699482 :   return false;
    1301             : }
    1302             : 
    1303             : /// ParseStringConstant
    1304             : ///   ::= StringConstant
    1305       77433 : bool LLParser::ParseStringConstant(std::string &Result) {
    1306       77433 :   if (Lex.getKind() != lltok::StringConstant)
    1307           0 :     return TokError("expected string constant");
    1308             :   Result = Lex.getStrVal();
    1309       77433 :   Lex.Lex();
    1310       77433 :   return false;
    1311             : }
    1312             : 
    1313             : /// ParseUInt32
    1314             : ///   ::= uint32
    1315      492564 : bool LLParser::ParseUInt32(uint32_t &Val) {
    1316      492564 :   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
    1317           0 :     return TokError("expected integer");
    1318      492564 :   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
    1319      492564 :   if (Val64 != unsigned(Val64))
    1320           0 :     return TokError("expected 32-bit integer (too large)");
    1321      492564 :   Val = Val64;
    1322      492564 :   Lex.Lex();
    1323      492564 :   return false;
    1324             : }
    1325             : 
    1326             : /// ParseUInt64
    1327             : ///   ::= uint64
    1328         469 : bool LLParser::ParseUInt64(uint64_t &Val) {
    1329         469 :   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
    1330           0 :     return TokError("expected integer");
    1331         938 :   Val = Lex.getAPSIntVal().getLimitedValue();
    1332         469 :   Lex.Lex();
    1333         469 :   return false;
    1334             : }
    1335             : 
    1336             : /// ParseTLSModel
    1337             : ///   := 'localdynamic'
    1338             : ///   := 'initialexec'
    1339             : ///   := 'localexec'
    1340         148 : bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
    1341         148 :   switch (Lex.getKind()) {
    1342             :     default:
    1343           0 :       return TokError("expected localdynamic, initialexec or localexec");
    1344          51 :     case lltok::kw_localdynamic:
    1345          51 :       TLM = GlobalVariable::LocalDynamicTLSModel;
    1346          51 :       break;
    1347          52 :     case lltok::kw_initialexec:
    1348          52 :       TLM = GlobalVariable::InitialExecTLSModel;
    1349          52 :       break;
    1350          45 :     case lltok::kw_localexec:
    1351          45 :       TLM = GlobalVariable::LocalExecTLSModel;
    1352          45 :       break;
    1353             :   }
    1354             : 
    1355         148 :   Lex.Lex();
    1356         148 :   return false;
    1357             : }
    1358             : 
    1359             : /// ParseOptionalThreadLocal
    1360             : ///   := /*empty*/
    1361             : ///   := 'thread_local'
    1362             : ///   := 'thread_local' '(' tlsmodel ')'
    1363       26207 : bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
    1364       26207 :   TLM = GlobalVariable::NotThreadLocal;
    1365             :   if (!EatIfPresent(lltok::kw_thread_local))
    1366             :     return false;
    1367             : 
    1368         690 :   TLM = GlobalVariable::GeneralDynamicTLSModel;
    1369         690 :   if (Lex.getKind() == lltok::lparen) {
    1370             :     Lex.Lex();
    1371         296 :     return ParseTLSModel(TLM) ||
    1372         148 :       ParseToken(lltok::rparen, "expected ')' after thread local model");
    1373             :   }
    1374             :   return false;
    1375             : }
    1376             : 
    1377             : /// ParseOptionalAddrSpace
    1378             : ///   := /*empty*/
    1379             : ///   := 'addrspace' '(' uint32 ')'
    1380      116636 : bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
    1381      116636 :   AddrSpace = 0;
    1382             :   if (!EatIfPresent(lltok::kw_addrspace))
    1383             :     return false;
    1384      183824 :   return ParseToken(lltok::lparen, "expected '(' in address space") ||
    1385      183824 :          ParseUInt32(AddrSpace) ||
    1386       91912 :          ParseToken(lltok::rparen, "expected ')' in address space");
    1387             : }
    1388             : 
    1389             : /// ParseStringAttribute
    1390             : ///   := StringConstant
    1391             : ///   := StringConstant '=' StringConstant
    1392       16479 : bool LLParser::ParseStringAttribute(AttrBuilder &B) {
    1393             :   std::string Attr = Lex.getStrVal();
    1394       16479 :   Lex.Lex();
    1395             :   std::string Val;
    1396       15361 :   if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
    1397             :     return true;
    1398       16479 :   B.addAttribute(Attr, Val);
    1399       16479 :   return false;
    1400             : }
    1401             : 
    1402             : /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
    1403      698135 : bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
    1404             :   bool HaveError = false;
    1405             : 
    1406      698135 :   B.clear();
    1407             : 
    1408             :   while (true) {
    1409      743784 :     lltok::Kind Token = Lex.getKind();
    1410      743784 :     switch (Token) {
    1411             :     default:  // End of attributes.
    1412             :       return HaveError;
    1413          14 :     case lltok::StringConstant: {
    1414          14 :       if (ParseStringAttribute(B))
    1415             :         return true;
    1416          14 :       continue;
    1417             :     }
    1418        4689 :     case lltok::kw_align: {
    1419             :       unsigned Alignment;
    1420        4689 :       if (ParseOptionalAlignment(Alignment))
    1421           1 :         return true;
    1422        4688 :       B.addAlignmentAttr(Alignment);
    1423        4688 :       continue;
    1424             :     }
    1425        1678 :     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
    1426         364 :     case lltok::kw_dereferenceable: {
    1427             :       uint64_t Bytes;
    1428         364 :       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
    1429           0 :         return true;
    1430         364 :       B.addDereferenceableAttr(Bytes);
    1431         364 :       continue;
    1432             :     }
    1433          20 :     case lltok::kw_dereferenceable_or_null: {
    1434             :       uint64_t Bytes;
    1435          20 :       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
    1436           0 :         return true;
    1437          20 :       B.addDereferenceableOrNullAttr(Bytes);
    1438          20 :       continue;
    1439             :     }
    1440         128 :     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
    1441        2102 :     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
    1442          59 :     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
    1443        4747 :     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
    1444       12320 :     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
    1445        1139 :     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
    1446         216 :     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
    1447        3184 :     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
    1448         183 :     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
    1449        8478 :     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
    1450        1045 :     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
    1451         328 :     case lltok::kw_swifterror:      B.addAttribute(Attribute::SwiftError); break;
    1452         206 :     case lltok::kw_swiftself:       B.addAttribute(Attribute::SwiftSelf); break;
    1453         198 :     case lltok::kw_writeonly:       B.addAttribute(Attribute::WriteOnly); break;
    1454        4551 :     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
    1455             : 
    1456             :     case lltok::kw_alignstack:
    1457             :     case lltok::kw_alwaysinline:
    1458             :     case lltok::kw_argmemonly:
    1459             :     case lltok::kw_builtin:
    1460             :     case lltok::kw_inlinehint:
    1461             :     case lltok::kw_jumptable:
    1462             :     case lltok::kw_minsize:
    1463             :     case lltok::kw_naked:
    1464             :     case lltok::kw_nobuiltin:
    1465             :     case lltok::kw_noduplicate:
    1466             :     case lltok::kw_noimplicitfloat:
    1467             :     case lltok::kw_noinline:
    1468             :     case lltok::kw_nonlazybind:
    1469             :     case lltok::kw_noredzone:
    1470             :     case lltok::kw_noreturn:
    1471             :     case lltok::kw_nounwind:
    1472             :     case lltok::kw_optnone:
    1473             :     case lltok::kw_optsize:
    1474             :     case lltok::kw_returns_twice:
    1475             :     case lltok::kw_sanitize_address:
    1476             :     case lltok::kw_sanitize_hwaddress:
    1477             :     case lltok::kw_sanitize_memory:
    1478             :     case lltok::kw_sanitize_thread:
    1479             :     case lltok::kw_ssp:
    1480             :     case lltok::kw_sspreq:
    1481             :     case lltok::kw_sspstrong:
    1482             :     case lltok::kw_safestack:
    1483             :     case lltok::kw_strictfp:
    1484             :     case lltok::kw_uwtable:
    1485           2 :       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
    1486          15 :       break;
    1487             :     }
    1488             : 
    1489       40563 :     Lex.Lex();
    1490             :   }
    1491             : }
    1492             : 
    1493             : /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
    1494      387796 : bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
    1495             :   bool HaveError = false;
    1496             : 
    1497      387796 :   B.clear();
    1498             : 
    1499             :   while (true) {
    1500      396751 :     lltok::Kind Token = Lex.getKind();
    1501      396751 :     switch (Token) {
    1502             :     default:  // End of attributes.
    1503             :       return HaveError;
    1504          16 :     case lltok::StringConstant: {
    1505          16 :       if (ParseStringAttribute(B))
    1506             :         return true;
    1507          16 :       continue;
    1508             :     }
    1509          71 :     case lltok::kw_dereferenceable: {
    1510             :       uint64_t Bytes;
    1511          71 :       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
    1512           0 :         return true;
    1513          71 :       B.addDereferenceableAttr(Bytes);
    1514          71 :       continue;
    1515             :     }
    1516          14 :     case lltok::kw_dereferenceable_or_null: {
    1517             :       uint64_t Bytes;
    1518          14 :       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
    1519           0 :         return true;
    1520          14 :       B.addDereferenceableOrNullAttr(Bytes);
    1521          14 :       continue;
    1522             :     }
    1523           4 :     case lltok::kw_align: {
    1524             :       unsigned Alignment;
    1525           4 :       if (ParseOptionalAlignment(Alignment))
    1526           0 :         return true;
    1527           4 :       B.addAlignmentAttr(Alignment);
    1528           4 :       continue;
    1529             :     }
    1530          78 :     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
    1531         508 :     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
    1532          65 :     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
    1533        4521 :     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
    1534        3676 :     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
    1535             : 
    1536             :     // Error handling.
    1537             :     case lltok::kw_byval:
    1538             :     case lltok::kw_inalloca:
    1539             :     case lltok::kw_nest:
    1540             :     case lltok::kw_nocapture:
    1541             :     case lltok::kw_returned:
    1542             :     case lltok::kw_sret:
    1543             :     case lltok::kw_swifterror:
    1544             :     case lltok::kw_swiftself:
    1545           2 :       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
    1546           1 :       break;
    1547             : 
    1548             :     case lltok::kw_alignstack:
    1549             :     case lltok::kw_alwaysinline:
    1550             :     case lltok::kw_argmemonly:
    1551             :     case lltok::kw_builtin:
    1552             :     case lltok::kw_cold:
    1553             :     case lltok::kw_inlinehint:
    1554             :     case lltok::kw_jumptable:
    1555             :     case lltok::kw_minsize:
    1556             :     case lltok::kw_naked:
    1557             :     case lltok::kw_nobuiltin:
    1558             :     case lltok::kw_noduplicate:
    1559             :     case lltok::kw_noimplicitfloat:
    1560             :     case lltok::kw_noinline:
    1561             :     case lltok::kw_nonlazybind:
    1562             :     case lltok::kw_noredzone:
    1563             :     case lltok::kw_noreturn:
    1564             :     case lltok::kw_nounwind:
    1565             :     case lltok::kw_optnone:
    1566             :     case lltok::kw_optsize:
    1567             :     case lltok::kw_returns_twice:
    1568             :     case lltok::kw_sanitize_address:
    1569             :     case lltok::kw_sanitize_hwaddress:
    1570             :     case lltok::kw_sanitize_memory:
    1571             :     case lltok::kw_sanitize_thread:
    1572             :     case lltok::kw_ssp:
    1573             :     case lltok::kw_sspreq:
    1574             :     case lltok::kw_sspstrong:
    1575             :     case lltok::kw_safestack:
    1576             :     case lltok::kw_strictfp:
    1577             :     case lltok::kw_uwtable:
    1578           2 :       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
    1579           1 :       break;
    1580             : 
    1581             :     case lltok::kw_readnone:
    1582             :     case lltok::kw_readonly:
    1583          16 :       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
    1584             :     }
    1585             : 
    1586        8850 :     Lex.Lex();
    1587             :   }
    1588             : }
    1589             : 
    1590      291334 : static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
    1591      291334 :   HasLinkage = true;
    1592      291334 :   switch (Kind) {
    1593      273360 :   default:
    1594      273360 :     HasLinkage = false;
    1595      273360 :     return GlobalValue::ExternalLinkage;
    1596             :   case lltok::kw_private:
    1597             :     return GlobalValue::PrivateLinkage;
    1598        3286 :   case lltok::kw_internal:
    1599        3286 :     return GlobalValue::InternalLinkage;
    1600         683 :   case lltok::kw_weak:
    1601         683 :     return GlobalValue::WeakAnyLinkage;
    1602         283 :   case lltok::kw_weak_odr:
    1603         283 :     return GlobalValue::WeakODRLinkage;
    1604         138 :   case lltok::kw_linkonce:
    1605         138 :     return GlobalValue::LinkOnceAnyLinkage;
    1606         764 :   case lltok::kw_linkonce_odr:
    1607         764 :     return GlobalValue::LinkOnceODRLinkage;
    1608         130 :   case lltok::kw_available_externally:
    1609         130 :     return GlobalValue::AvailableExternallyLinkage;
    1610         327 :   case lltok::kw_appending:
    1611         327 :     return GlobalValue::AppendingLinkage;
    1612        4336 :   case lltok::kw_common:
    1613        4336 :     return GlobalValue::CommonLinkage;
    1614         105 :   case lltok::kw_extern_weak:
    1615         105 :     return GlobalValue::ExternalWeakLinkage;
    1616        6289 :   case lltok::kw_external:
    1617        6289 :     return GlobalValue::ExternalLinkage;
    1618             :   }
    1619             : }
    1620             : 
    1621             : /// ParseOptionalLinkage
    1622             : ///   ::= /*empty*/
    1623             : ///   ::= 'private'
    1624             : ///   ::= 'internal'
    1625             : ///   ::= 'weak'
    1626             : ///   ::= 'weak_odr'
    1627             : ///   ::= 'linkonce'
    1628             : ///   ::= 'linkonce_odr'
    1629             : ///   ::= 'available_externally'
    1630             : ///   ::= 'appending'
    1631             : ///   ::= 'common'
    1632             : ///   ::= 'extern_weak'
    1633             : ///   ::= 'external'
    1634      291334 : bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
    1635             :                                     unsigned &Visibility,
    1636             :                                     unsigned &DLLStorageClass,
    1637             :                                     bool &DSOLocal) {
    1638      291334 :   Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
    1639      291334 :   if (HasLinkage)
    1640       17974 :     Lex.Lex();
    1641      291334 :   ParseOptionalDSOLocal(DSOLocal);
    1642      291334 :   ParseOptionalVisibility(Visibility);
    1643      291334 :   ParseOptionalDLLStorageClass(DLLStorageClass);
    1644             : 
    1645      291334 :   if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
    1646           2 :     return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
    1647             :   }
    1648             : 
    1649             :   return false;
    1650             : }
    1651             : 
    1652      291334 : void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
    1653      291334 :   switch (Lex.getKind()) {
    1654      290980 :   default:
    1655      290980 :     DSOLocal = false;
    1656      290980 :     break;
    1657         206 :   case lltok::kw_dso_local:
    1658         206 :     DSOLocal = true;
    1659         206 :     Lex.Lex();
    1660             :     break;
    1661         148 :   case lltok::kw_dso_preemptable:
    1662         148 :     DSOLocal = false;
    1663         148 :     Lex.Lex();
    1664             :     break;
    1665             :   }
    1666      291334 : }
    1667             : 
    1668             : /// ParseOptionalVisibility
    1669             : ///   ::= /*empty*/
    1670             : ///   ::= 'default'
    1671             : ///   ::= 'hidden'
    1672             : ///   ::= 'protected'
    1673             : ///
    1674      291334 : void LLParser::ParseOptionalVisibility(unsigned &Res) {
    1675      291334 :   switch (Lex.getKind()) {
    1676      290416 :   default:
    1677      290416 :     Res = GlobalValue::DefaultVisibility;
    1678      290416 :     return;
    1679           9 :   case lltok::kw_default:
    1680           9 :     Res = GlobalValue::DefaultVisibility;
    1681           9 :     break;
    1682         803 :   case lltok::kw_hidden:
    1683         803 :     Res = GlobalValue::HiddenVisibility;
    1684         803 :     break;
    1685         106 :   case lltok::kw_protected:
    1686         106 :     Res = GlobalValue::ProtectedVisibility;
    1687         106 :     break;
    1688             :   }
    1689         918 :   Lex.Lex();
    1690             : }
    1691             : 
    1692             : /// ParseOptionalDLLStorageClass
    1693             : ///   ::= /*empty*/
    1694             : ///   ::= 'dllimport'
    1695             : ///   ::= 'dllexport'
    1696             : ///
    1697      291334 : void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
    1698      291334 :   switch (Lex.getKind()) {
    1699      290919 :   default:
    1700      290919 :     Res = GlobalValue::DefaultStorageClass;
    1701      290919 :     return;
    1702         116 :   case lltok::kw_dllimport:
    1703         116 :     Res = GlobalValue::DLLImportStorageClass;
    1704         116 :     break;
    1705         299 :   case lltok::kw_dllexport:
    1706         299 :     Res = GlobalValue::DLLExportStorageClass;
    1707         299 :     break;
    1708             :   }
    1709         415 :   Lex.Lex();
    1710             : }
    1711             : 
    1712             : /// ParseOptionalCallingConv
    1713             : ///   ::= /*empty*/
    1714             : ///   ::= 'ccc'
    1715             : ///   ::= 'fastcc'
    1716             : ///   ::= 'intel_ocl_bicc'
    1717             : ///   ::= 'coldcc'
    1718             : ///   ::= 'x86_stdcallcc'
    1719             : ///   ::= 'x86_fastcallcc'
    1720             : ///   ::= 'x86_thiscallcc'
    1721             : ///   ::= 'x86_vectorcallcc'
    1722             : ///   ::= 'arm_apcscc'
    1723             : ///   ::= 'arm_aapcscc'
    1724             : ///   ::= 'arm_aapcs_vfpcc'
    1725             : ///   ::= 'msp430_intrcc'
    1726             : ///   ::= 'avr_intrcc'
    1727             : ///   ::= 'avr_signalcc'
    1728             : ///   ::= 'ptx_kernel'
    1729             : ///   ::= 'ptx_device'
    1730             : ///   ::= 'spir_func'
    1731             : ///   ::= 'spir_kernel'
    1732             : ///   ::= 'x86_64_sysvcc'
    1733             : ///   ::= 'win64cc'
    1734             : ///   ::= 'webkit_jscc'
    1735             : ///   ::= 'anyregcc'
    1736             : ///   ::= 'preserve_mostcc'
    1737             : ///   ::= 'preserve_allcc'
    1738             : ///   ::= 'ghccc'
    1739             : ///   ::= 'swiftcc'
    1740             : ///   ::= 'x86_intrcc'
    1741             : ///   ::= 'hhvmcc'
    1742             : ///   ::= 'hhvm_ccc'
    1743             : ///   ::= 'cxx_fast_tlscc'
    1744             : ///   ::= 'amdgpu_vs'
    1745             : ///   ::= 'amdgpu_ls'
    1746             : ///   ::= 'amdgpu_hs'
    1747             : ///   ::= 'amdgpu_es'
    1748             : ///   ::= 'amdgpu_gs'
    1749             : ///   ::= 'amdgpu_ps'
    1750             : ///   ::= 'amdgpu_cs'
    1751             : ///   ::= 'amdgpu_kernel'
    1752             : ///   ::= 'cc' UINT
    1753             : ///
    1754      387796 : bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
    1755      387796 :   switch (Lex.getKind()) {
    1756      363175 :   default:                       CC = CallingConv::C; return false;
    1757           3 :   case lltok::kw_ccc:            CC = CallingConv::C; break;
    1758        1664 :   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
    1759         116 :   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
    1760          84 :   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
    1761          92 :   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
    1762         200 :   case lltok::kw_x86_regcallcc:  CC = CallingConv::X86_RegCall; break;
    1763         281 :   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
    1764          66 :   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
    1765          40 :   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
    1766         608 :   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
    1767         724 :   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
    1768          13 :   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
    1769           3 :   case lltok::kw_avr_intrcc:     CC = CallingConv::AVR_INTR; break;
    1770           3 :   case lltok::kw_avr_signalcc:   CC = CallingConv::AVR_SIGNAL; break;
    1771          21 :   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
    1772         185 :   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
    1773          23 :   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
    1774          42 :   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
    1775          92 :   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
    1776          11 :   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
    1777          46 :   case lltok::kw_win64cc:        CC = CallingConv::Win64; break;
    1778          33 :   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
    1779          68 :   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
    1780          15 :   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
    1781          11 :   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
    1782          56 :   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
    1783         442 :   case lltok::kw_swiftcc:        CC = CallingConv::Swift; break;
    1784          30 :   case lltok::kw_x86_intrcc:     CC = CallingConv::X86_INTR; break;
    1785          27 :   case lltok::kw_hhvmcc:         CC = CallingConv::HHVM; break;
    1786          16 :   case lltok::kw_hhvm_ccc:       CC = CallingConv::HHVM_C; break;
    1787         108 :   case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
    1788         173 :   case lltok::kw_amdgpu_vs:      CC = CallingConv::AMDGPU_VS; break;
    1789           5 :   case lltok::kw_amdgpu_ls:      CC = CallingConv::AMDGPU_LS; break;
    1790          14 :   case lltok::kw_amdgpu_hs:      CC = CallingConv::AMDGPU_HS; break;
    1791           5 :   case lltok::kw_amdgpu_es:      CC = CallingConv::AMDGPU_ES; break;
    1792          69 :   case lltok::kw_amdgpu_gs:      CC = CallingConv::AMDGPU_GS; break;
    1793         725 :   case lltok::kw_amdgpu_ps:      CC = CallingConv::AMDGPU_PS; break;
    1794          26 :   case lltok::kw_amdgpu_cs:      CC = CallingConv::AMDGPU_CS; break;
    1795       18372 :   case lltok::kw_amdgpu_kernel:  CC = CallingConv::AMDGPU_KERNEL; break;
    1796         109 :   case lltok::kw_cc: {
    1797         109 :       Lex.Lex();
    1798         109 :       return ParseUInt32(CC);
    1799             :     }
    1800             :   }
    1801             : 
    1802       24512 :   Lex.Lex();
    1803       24512 :   return false;
    1804             : }
    1805             : 
    1806             : /// ParseMetadataAttachment
    1807             : ///   ::= !dbg !42
    1808       27911 : bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
    1809             :   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
    1810             : 
    1811             :   std::string Name = Lex.getStrVal();
    1812       55822 :   Kind = M->getMDKindID(Name);
    1813       27911 :   Lex.Lex();
    1814             : 
    1815       55822 :   return ParseMDNode(MD);
    1816             : }
    1817             : 
    1818             : /// ParseInstructionMetadata
    1819             : ///   ::= !dbg !42 (',' !dbg !57)*
    1820       22474 : bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
    1821             :   do {
    1822       23670 :     if (Lex.getKind() != lltok::MetadataVar)
    1823           2 :       return TokError("expected metadata after comma");
    1824             : 
    1825             :     unsigned MDK;
    1826             :     MDNode *N;
    1827       23668 :     if (ParseMetadataAttachment(MDK, N))
    1828             :       return true;
    1829             : 
    1830       23666 :     Inst.setMetadata(MDK, N);
    1831       23666 :     if (MDK == LLVMContext::MD_tbaa)
    1832        3503 :       InstsWithTBAATag.push_back(&Inst);
    1833             : 
    1834             :     // If this is the end of the list, we're done.
    1835             :   } while (EatIfPresent(lltok::comma));
    1836             :   return false;
    1837             : }
    1838             : 
    1839             : /// ParseGlobalObjectMetadataAttachment
    1840             : ///   ::= !dbg !57
    1841        4223 : bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
    1842             :   unsigned MDK;
    1843             :   MDNode *N;
    1844        4223 :   if (ParseMetadataAttachment(MDK, N))
    1845             :     return true;
    1846             : 
    1847        4223 :   GO.addMetadata(MDK, *N);
    1848        4223 :   return false;
    1849             : }
    1850             : 
    1851             : /// ParseOptionalFunctionMetadata
    1852             : ///   ::= (!dbg !57)*
    1853      211470 : bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
    1854      214663 :   while (Lex.getKind() == lltok::MetadataVar)
    1855        3193 :     if (ParseGlobalObjectMetadataAttachment(F))
    1856             :       return true;
    1857             :   return false;
    1858             : }
    1859             : 
    1860             : /// ParseOptionalAlignment
    1861             : ///   ::= /* empty */
    1862             : ///   ::= 'align' 4
    1863      502753 : bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
    1864      502753 :   Alignment = 0;
    1865             :   if (!EatIfPresent(lltok::kw_align))
    1866             :     return false;
    1867      237743 :   LocTy AlignLoc = Lex.getLoc();
    1868      237743 :   if (ParseUInt32(Alignment)) return true;
    1869      237743 :   if (!isPowerOf2_32(Alignment))
    1870           1 :     return Error(AlignLoc, "alignment is not a power of two");
    1871      237742 :   if (Alignment > Value::MaximumAlignment)
    1872           3 :     return Error(AlignLoc, "huge alignments are not supported yet");
    1873             :   return false;
    1874             : }
    1875             : 
    1876             : /// ParseOptionalDerefAttrBytes
    1877             : ///   ::= /* empty */
    1878             : ///   ::= AttrKind '(' 4 ')'
    1879             : ///
    1880             : /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
    1881         469 : bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
    1882             :                                            uint64_t &Bytes) {
    1883             :   assert((AttrKind == lltok::kw_dereferenceable ||
    1884             :           AttrKind == lltok::kw_dereferenceable_or_null) &&
    1885             :          "contract!");
    1886             : 
    1887         469 :   Bytes = 0;
    1888             :   if (!EatIfPresent(AttrKind))
    1889             :     return false;
    1890         469 :   LocTy ParenLoc = Lex.getLoc();
    1891             :   if (!EatIfPresent(lltok::lparen))
    1892           0 :     return Error(ParenLoc, "expected '('");
    1893         469 :   LocTy DerefLoc = Lex.getLoc();
    1894         469 :   if (ParseUInt64(Bytes)) return true;
    1895         469 :   ParenLoc = Lex.getLoc();
    1896             :   if (!EatIfPresent(lltok::rparen))
    1897           0 :     return Error(ParenLoc, "expected ')'");
    1898         469 :   if (!Bytes)
    1899           0 :     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
    1900             :   return false;
    1901             : }
    1902             : 
    1903             : /// ParseOptionalCommaAlign
    1904             : ///   ::=
    1905             : ///   ::= ',' align 4
    1906             : ///
    1907             : /// This returns with AteExtraComma set to true if it ate an excess comma at the
    1908             : /// end.
    1909      264670 : bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
    1910             :                                        bool &AteExtraComma) {
    1911      264670 :   AteExtraComma = false;
    1912             :   while (EatIfPresent(lltok::comma)) {
    1913             :     // Metadata at the end is an early exit.
    1914      185021 :     if (Lex.getKind() == lltok::MetadataVar) {
    1915        7916 :       AteExtraComma = true;
    1916        7916 :       return false;
    1917             :     }
    1918             : 
    1919      177105 :     if (Lex.getKind() != lltok::kw_align)
    1920           0 :       return Error(Lex.getLoc(), "expected metadata or 'align'");
    1921             : 
    1922      177105 :     if (ParseOptionalAlignment(Alignment)) return true;
    1923             :   }
    1924             : 
    1925             :   return false;
    1926             : }
    1927             : 
    1928             : /// ParseOptionalCommaAddrSpace
    1929             : ///   ::=
    1930             : ///   ::= ',' addrspace(1)
    1931             : ///
    1932             : /// This returns with AteExtraComma set to true if it ate an excess comma at the
    1933             : /// end.
    1934       41951 : bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
    1935             :                                            LocTy &Loc,
    1936             :                                            bool &AteExtraComma) {
    1937       41951 :   AteExtraComma = false;
    1938             :   while (EatIfPresent(lltok::comma)) {
    1939             :     // Metadata at the end is an early exit.
    1940         556 :     if (Lex.getKind() == lltok::MetadataVar) {
    1941          46 :       AteExtraComma = true;
    1942          46 :       return false;
    1943             :     }
    1944             : 
    1945         510 :     Loc = Lex.getLoc();
    1946         510 :     if (Lex.getKind() != lltok::kw_addrspace)
    1947           0 :       return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
    1948             : 
    1949         510 :     if (ParseOptionalAddrSpace(AddrSpace))
    1950             :       return true;
    1951             :   }
    1952             : 
    1953             :   return false;
    1954             : }
    1955             : 
    1956          23 : bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
    1957             :                                        Optional<unsigned> &HowManyArg) {
    1958          23 :   Lex.Lex();
    1959             : 
    1960          23 :   auto StartParen = Lex.getLoc();
    1961             :   if (!EatIfPresent(lltok::lparen))
    1962           0 :     return Error(StartParen, "expected '('");
    1963             : 
    1964          23 :   if (ParseUInt32(BaseSizeArg))
    1965             :     return true;
    1966             : 
    1967             :   if (EatIfPresent(lltok::comma)) {
    1968          12 :     auto HowManyAt = Lex.getLoc();
    1969             :     unsigned HowMany;
    1970          12 :     if (ParseUInt32(HowMany))
    1971           1 :       return true;
    1972          12 :     if (HowMany == BaseSizeArg)
    1973           1 :       return Error(HowManyAt,
    1974             :                    "'allocsize' indices can't refer to the same parameter");
    1975             :     HowManyArg = HowMany;
    1976             :   } else
    1977             :     HowManyArg = None;
    1978             : 
    1979          22 :   auto EndParen = Lex.getLoc();
    1980             :   if (!EatIfPresent(lltok::rparen))
    1981           0 :     return Error(EndParen, "expected ')'");
    1982             :   return false;
    1983             : }
    1984             : 
    1985             : /// ParseScopeAndOrdering
    1986             : ///   if isAtomic: ::= SyncScope? AtomicOrdering
    1987             : ///   else: ::=
    1988             : ///
    1989             : /// This sets Scope and Ordering to the parsed values.
    1990      272194 : bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
    1991             :                                      AtomicOrdering &Ordering) {
    1992      272194 :   if (!isAtomic)
    1993             :     return false;
    1994             : 
    1995        9492 :   return ParseScope(SSID) || ParseOrdering(Ordering);
    1996             : }
    1997             : 
    1998             : /// ParseScope
    1999             : ///   ::= syncscope("singlethread" | "<target scope>")?
    2000             : ///
    2001             : /// This sets synchronization scope ID to the ID of the parsed value.
    2002        9492 : bool LLParser::ParseScope(SyncScope::ID &SSID) {
    2003        9492 :   SSID = SyncScope::System;
    2004             :   if (EatIfPresent(lltok::kw_syncscope)) {
    2005         871 :     auto StartParenAt = Lex.getLoc();
    2006             :     if (!EatIfPresent(lltok::lparen))
    2007           0 :       return Error(StartParenAt, "Expected '(' in syncscope");
    2008             : 
    2009             :     std::string SSN;
    2010         871 :     auto SSNAt = Lex.getLoc();
    2011         871 :     if (ParseStringConstant(SSN))
    2012           0 :       return Error(SSNAt, "Expected synchronization scope name");
    2013             : 
    2014         871 :     auto EndParenAt = Lex.getLoc();
    2015             :     if (!EatIfPresent(lltok::rparen))
    2016           0 :       return Error(EndParenAt, "Expected ')' in syncscope");
    2017             : 
    2018        1742 :     SSID = Context.getOrInsertSyncScopeID(SSN);
    2019             :   }
    2020             : 
    2021             :   return false;
    2022             : }
    2023             : 
    2024             : /// ParseOrdering
    2025             : ///   ::= AtomicOrdering
    2026             : ///
    2027             : /// This sets Ordering to the parsed value.
    2028       10552 : bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
    2029       10552 :   switch (Lex.getKind()) {
    2030           0 :   default: return TokError("Expected ordering on atomic instruction");
    2031         426 :   case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
    2032        2477 :   case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
    2033             :   // Not specified yet:
    2034             :   // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
    2035        1388 :   case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
    2036         889 :   case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
    2037         516 :   case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
    2038        4856 :   case lltok::kw_seq_cst:
    2039        4856 :     Ordering = AtomicOrdering::SequentiallyConsistent;
    2040        4856 :     break;
    2041             :   }
    2042       10552 :   Lex.Lex();
    2043       10552 :   return false;
    2044             : }
    2045             : 
    2046             : /// ParseOptionalStackAlignment
    2047             : ///   ::= /* empty */
    2048             : ///   ::= 'alignstack' '(' 4 ')'
    2049          34 : bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
    2050          34 :   Alignment = 0;
    2051             :   if (!EatIfPresent(lltok::kw_alignstack))
    2052             :     return false;
    2053          34 :   LocTy ParenLoc = Lex.getLoc();
    2054             :   if (!EatIfPresent(lltok::lparen))
    2055           0 :     return Error(ParenLoc, "expected '('");
    2056          34 :   LocTy AlignLoc = Lex.getLoc();
    2057          34 :   if (ParseUInt32(Alignment)) return true;
    2058          34 :   ParenLoc = Lex.getLoc();
    2059             :   if (!EatIfPresent(lltok::rparen))
    2060           0 :     return Error(ParenLoc, "expected ')'");
    2061          34 :   if (!isPowerOf2_32(Alignment))
    2062           0 :     return Error(AlignLoc, "stack alignment is not a power of two");
    2063             :   return false;
    2064             : }
    2065             : 
    2066             : /// ParseIndexList - This parses the index list for an insert/extractvalue
    2067             : /// instruction.  This sets AteExtraComma in the case where we eat an extra
    2068             : /// comma at the end of the line and find that it is followed by metadata.
    2069             : /// Clients that don't allow metadata can call the version of this function that
    2070             : /// only takes one argument.
    2071             : ///
    2072             : /// ParseIndexList
    2073             : ///    ::=  (',' uint32)+
    2074             : ///
    2075        5871 : bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
    2076             :                               bool &AteExtraComma) {
    2077        5871 :   AteExtraComma = false;
    2078             : 
    2079        5871 :   if (Lex.getKind() != lltok::comma)
    2080           0 :     return TokError("expected ',' as start of index list");
    2081             : 
    2082        6117 :   while (EatIfPresent(lltok::comma)) {
    2083        6185 :     if (Lex.getKind() == lltok::MetadataVar) {
    2084          69 :       if (Indices.empty()) return TokError("expected index");
    2085          67 :       AteExtraComma = true;
    2086          67 :       return false;
    2087             :     }
    2088        6117 :     unsigned Idx = 0;
    2089        6117 :     if (ParseUInt32(Idx)) return true;
    2090        6117 :     Indices.push_back(Idx);
    2091             :   }
    2092             : 
    2093             :   return false;
    2094             : }
    2095             : 
    2096             : //===----------------------------------------------------------------------===//
    2097             : // Type Parsing.
    2098             : //===----------------------------------------------------------------------===//
    2099             : 
    2100             : /// ParseType - Parse a type.
    2101     5357236 : bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
    2102     5357236 :   SMLoc TypeLoc = Lex.getLoc();
    2103     5357236 :   switch (Lex.getKind()) {
    2104             :   default:
    2105           5 :     return TokError(Msg);
    2106     4071860 :   case lltok::Type:
    2107             :     // Type ::= 'float' | 'void' (etc)
    2108     4071860 :     Result = Lex.getTyVal();
    2109     4071860 :     Lex.Lex();
    2110             :     break;
    2111       19134 :   case lltok::lbrace:
    2112             :     // Type ::= StructType
    2113       19134 :     if (ParseAnonStructType(Result, false))
    2114             :       return true;
    2115             :     break;
    2116      120443 :   case lltok::lsquare:
    2117             :     // Type ::= '[' ... ']'
    2118      120443 :     Lex.Lex(); // eat the lsquare.
    2119      120443 :     if (ParseArrayVectorType(Result, false))
    2120             :       return true;
    2121             :     break;
    2122     1062367 :   case lltok::less: // Either vector or packed struct.
    2123             :     // Type ::= '<' ... '>'
    2124     1062367 :     Lex.Lex();
    2125     1062367 :     if (Lex.getKind() == lltok::lbrace) {
    2126        1486 :       if (ParseAnonStructType(Result, true) ||
    2127         743 :           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
    2128             :         return true;
    2129     1061624 :     } else if (ParseArrayVectorType(Result, true))
    2130             :       return true;
    2131             :     break;
    2132       81274 :   case lltok::LocalVar: {
    2133             :     // Type ::= %foo
    2134       81274 :     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
    2135             : 
    2136             :     // If the type hasn't been defined yet, create a forward definition and
    2137             :     // remember where that forward def'n was seen (in case it never is defined).
    2138       81274 :     if (!Entry.first) {
    2139        4065 :       Entry.first = StructType::create(Context, Lex.getStrVal());
    2140        4065 :       Entry.second = Lex.getLoc();
    2141             :     }
    2142       81274 :     Result = Entry.first;
    2143       81274 :     Lex.Lex();
    2144             :     break;
    2145             :   }
    2146             : 
    2147        2153 :   case lltok::LocalVarID: {
    2148             :     // Type ::= %4
    2149        2153 :     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
    2150             : 
    2151             :     // If the type hasn't been defined yet, create a forward definition and
    2152             :     // remember where that forward def'n was seen (in case it never is defined).
    2153        2153 :     if (!Entry.first) {
    2154         145 :       Entry.first = StructType::create(Context);
    2155         145 :       Entry.second = Lex.getLoc();
    2156             :     }
    2157        2153 :     Result = Entry.first;
    2158        2153 :     Lex.Lex();
    2159             :     break;
    2160             :   }
    2161             :   }
    2162             : 
    2163             :   // Parse the type suffixes.
    2164             :   while (true) {
    2165     6075600 :     switch (Lex.getKind()) {
    2166             :     // End of type.
    2167     5357229 :     default:
    2168    10112117 :       if (!AllowVoid && Result->isVoidTy())
    2169           0 :         return Error(TypeLoc, "void type only allowed for function results");
    2170             :       return false;
    2171             : 
    2172             :     // Type ::= Type '*'
    2173      610270 :     case lltok::star:
    2174     1220540 :       if (Result->isLabelTy())
    2175           1 :         return TokError("basic block pointers are invalid");
    2176      610269 :       if (Result->isVoidTy())
    2177           0 :         return TokError("pointers to void are invalid - use i8* instead");
    2178      610269 :       if (!PointerType::isValidElementType(Result))
    2179           0 :         return TokError("pointer to this type is invalid");
    2180     1220538 :       Result = PointerType::getUnqual(Result);
    2181      610269 :       Lex.Lex();
    2182             :       break;
    2183             : 
    2184             :     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
    2185       90477 :     case lltok::kw_addrspace: {
    2186      180954 :       if (Result->isLabelTy())
    2187           0 :         return TokError("basic block pointers are invalid");
    2188       90477 :       if (Result->isVoidTy())
    2189           0 :         return TokError("pointers to void are invalid; use i8* instead");
    2190       90477 :       if (!PointerType::isValidElementType(Result))
    2191           0 :         return TokError("pointer to this type is invalid");
    2192             :       unsigned AddrSpace;
    2193      180954 :       if (ParseOptionalAddrSpace(AddrSpace) ||
    2194       90477 :           ParseToken(lltok::star, "expected '*' in address space"))
    2195             :         return true;
    2196             : 
    2197       90477 :       Result = PointerType::get(Result, AddrSpace);
    2198       90477 :       break;
    2199             :     }
    2200             : 
    2201             :     /// Types '(' ArgTypeListI ')' OptFuncAttrs
    2202       17624 :     case lltok::lparen:
    2203       17624 :       if (ParseFunctionType(Result))
    2204             :         return true;
    2205             :       break;
    2206             :     }
    2207             :   }
    2208             : }
    2209             : 
    2210             : /// ParseParameterList
    2211             : ///    ::= '(' ')'
    2212             : ///    ::= '(' Arg (',' Arg)* ')'
    2213             : ///  Arg
    2214             : ///    ::= Type OptionalAttributes Value OptionalAttributes
    2215      122670 : bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
    2216             :                                   PerFunctionState &PFS, bool IsMustTailCall,
    2217             :                                   bool InVarArgsFunc) {
    2218      122670 :   if (ParseToken(lltok::lparen, "expected '(' in call"))
    2219             :     return true;
    2220             : 
    2221      356271 :   while (Lex.getKind() != lltok::rparen) {
    2222             :     // If this isn't the first argument, we need a comma.
    2223      368860 :     if (!ArgList.empty() &&
    2224      135215 :         ParseToken(lltok::comma, "expected ',' in argument list"))
    2225          44 :       return true;
    2226             : 
    2227             :     // Parse an ellipsis if this is a musttail call in a variadic function.
    2228      233645 :     if (Lex.getKind() == lltok::dotdotdot) {
    2229             :       const char *Msg = "unexpected ellipsis in argument list for ";
    2230          38 :       if (!IsMustTailCall)
    2231           0 :         return TokError(Twine(Msg) + "non-musttail call");
    2232          38 :       if (!InVarArgsFunc)
    2233           1 :         return TokError(Twine(Msg) + "musttail call in non-varargs function");
    2234          37 :       Lex.Lex();  // Lex the '...', it is purely for readability.
    2235          37 :       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
    2236             :     }
    2237             : 
    2238             :     // Parse the argument.
    2239             :     LocTy ArgLoc;
    2240      233607 :     Type *ArgTy = nullptr;
    2241             :     AttrBuilder ArgAttrs;
    2242             :     Value *V;
    2243      233607 :     if (ParseType(ArgTy, ArgLoc))
    2244             :       return true;
    2245             : 
    2246      467214 :     if (ArgTy->isMetadataTy()) {
    2247        7244 :       if (ParseMetadataAsValue(V, PFS))
    2248             :         return true;
    2249             :     } else {
    2250             :       // Otherwise, handle normal operands.
    2251      452725 :       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
    2252             :         return true;
    2253             :     }
    2254      467202 :     ArgList.push_back(ParamInfo(
    2255             :         ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
    2256             :   }
    2257             : 
    2258      122626 :   if (IsMustTailCall && InVarArgsFunc)
    2259           1 :     return TokError("expected '...' at end of argument list for musttail call "
    2260             :                     "in varargs function");
    2261             : 
    2262      122625 :   Lex.Lex();  // Lex the ')'.
    2263      122625 :   return false;
    2264             : }
    2265             : 
    2266             : /// ParseOptionalOperandBundles
    2267             : ///    ::= /*empty*/
    2268             : ///    ::= '[' OperandBundle [, OperandBundle ]* ']'
    2269             : ///
    2270             : /// OperandBundle
    2271             : ///    ::= bundle-tag '(' ')'
    2272             : ///    ::= bundle-tag '(' Type Value [, Type Value ]* ')'
    2273             : ///
    2274             : /// bundle-tag ::= String Constant
    2275      122662 : bool LLParser::ParseOptionalOperandBundles(
    2276             :     SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
    2277      122662 :   LocTy BeginLoc = Lex.getLoc();
    2278             :   if (!EatIfPresent(lltok::lsquare))
    2279             :     return false;
    2280             : 
    2281        2117 :   while (Lex.getKind() != lltok::rsquare) {
    2282             :     // If this isn't the first operand bundle, we need a comma.
    2283        1117 :     if (!BundleList.empty() &&
    2284          39 :         ParseToken(lltok::comma, "expected ',' in input list"))
    2285           0 :       return true;
    2286             : 
    2287             :     std::string Tag;
    2288        1078 :     if (ParseStringConstant(Tag))
    2289             :       return true;
    2290             : 
    2291        1078 :     if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
    2292             :       return true;
    2293             : 
    2294             :     std::vector<Value *> Inputs;
    2295        3240 :     while (Lex.getKind() != lltok::rparen) {
    2296             :       // If this isn't the first input, we need a comma.
    2297        1624 :       if (!Inputs.empty() &&
    2298         543 :           ParseToken(lltok::comma, "expected ',' in input list"))
    2299           0 :         return true;
    2300             : 
    2301        1081 :       Type *Ty = nullptr;
    2302        1081 :       Value *Input = nullptr;
    2303        2162 :       if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
    2304             :         return true;
    2305        1081 :       Inputs.push_back(Input);
    2306             :     }
    2307             : 
    2308        1078 :     BundleList.emplace_back(std::move(Tag), std::move(Inputs));
    2309             : 
    2310             :     Lex.Lex(); // Lex the ')'.
    2311             :   }
    2312             : 
    2313        1039 :   if (BundleList.empty())
    2314           0 :     return Error(BeginLoc, "operand bundle set must not be empty");
    2315             : 
    2316             :   Lex.Lex(); // Lex the ']'.
    2317        1039 :   return false;
    2318             : }
    2319             : 
    2320             : /// ParseArgumentList - Parse the argument list for a function type or function
    2321             : /// prototype.
    2322             : ///   ::= '(' ArgTypeListI ')'
    2323             : /// ArgTypeListI
    2324             : ///   ::= /*empty*/
    2325             : ///   ::= '...'
    2326             : ///   ::= ArgTypeList ',' '...'
    2327             : ///   ::= ArgType (',' ArgType)*
    2328             : ///
    2329      282744 : bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
    2330             :                                  bool &isVarArg){
    2331      282744 :   isVarArg = false;
    2332             :   assert(Lex.getKind() == lltok::lparen);
    2333      282744 :   Lex.Lex(); // eat the (.
    2334             : 
    2335      282744 :   if (Lex.getKind() == lltok::rparen) {
    2336             :     // empty
    2337      238671 :   } else if (Lex.getKind() == lltok::dotdotdot) {
    2338        6228 :     isVarArg = true;
    2339             :     Lex.Lex();
    2340             :   } else {
    2341      232443 :     LocTy TypeLoc = Lex.getLoc();
    2342      232443 :     Type *ArgTy = nullptr;
    2343             :     AttrBuilder Attrs;
    2344             :     std::string Name;
    2345             : 
    2346      464885 :     if (ParseType(ArgTy) ||
    2347      232442 :         ParseOptionalParamAttrs(Attrs)) return true;
    2348             : 
    2349      464882 :     if (ArgTy->isVoidTy())
    2350           0 :       return Error(TypeLoc, "argument can not have void type");
    2351             : 
    2352      232441 :     if (Lex.getKind() == lltok::LocalVar) {
    2353             :       Name = Lex.getStrVal();
    2354             :       Lex.Lex();
    2355             :     }
    2356             : 
    2357      232441 :     if (!FunctionType::isValidArgumentType(ArgTy))
    2358           0 :       return Error(TypeLoc, "invalid type for function argument");
    2359             : 
    2360      232441 :     ArgList.emplace_back(TypeLoc, ArgTy,
    2361      464882 :                          AttributeSet::get(ArgTy->getContext(), Attrs),
    2362             :                          std::move(Name));
    2363             : 
    2364      239330 :     while (EatIfPresent(lltok::comma)) {
    2365             :       // Handle ... at end of arg list.
    2366             :       if (EatIfPresent(lltok::dotdotdot)) {
    2367        3975 :         isVarArg = true;
    2368        3975 :         break;
    2369             :       }
    2370             : 
    2371             :       // Otherwise must be an argument type.
    2372      239330 :       TypeLoc = Lex.getLoc();
    2373      239330 :       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
    2374             : 
    2375      478660 :       if (ArgTy->isVoidTy())
    2376           0 :         return Error(TypeLoc, "argument can not have void type");
    2377             : 
    2378      239330 :       if (Lex.getKind() == lltok::LocalVar) {
    2379             :         Name = Lex.getStrVal();
    2380             :         Lex.Lex();
    2381             :       } else {
    2382             :         Name = "";
    2383             :       }
    2384             : 
    2385      239330 :       if (!ArgTy->isFirstClassType())
    2386           0 :         return Error(TypeLoc, "invalid type for function argument");
    2387             : 
    2388      239330 :       ArgList.emplace_back(TypeLoc, ArgTy,
    2389      478660 :                            AttributeSet::get(ArgTy->getContext(), Attrs),
    2390             :                            std::move(Name));
    2391             :     }
    2392             :   }
    2393             : 
    2394      282742 :   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
    2395             : }
    2396             : 
    2397             : /// ParseFunctionType
    2398             : ///  ::= Type ArgumentList OptionalAttrs
    2399       17624 : bool LLParser::ParseFunctionType(Type *&Result) {
    2400             :   assert(Lex.getKind() == lltok::lparen);
    2401             : 
    2402       17624 :   if (!FunctionType::isValidReturnType(Result))
    2403           0 :     return TokError("invalid function return type");
    2404             : 
    2405       17624 :   SmallVector<ArgInfo, 8> ArgList;
    2406             :   bool isVarArg;
    2407       17624 :   if (ParseArgumentList(ArgList, isVarArg))
    2408             :     return true;
    2409             : 
    2410             :   // Reject names on the arguments lists.
    2411       34178 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
    2412       33108 :     if (!ArgList[i].Name.empty())
    2413           0 :       return Error(ArgList[i].Loc, "argument name invalid in function type");
    2414       16554 :     if (ArgList[i].Attrs.hasAttributes())
    2415           0 :       return Error(ArgList[i].Loc,
    2416             :                    "argument attributes invalid in function type");
    2417             :   }
    2418             : 
    2419             :   SmallVector<Type*, 16> ArgListTy;
    2420       50732 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
    2421       33108 :     ArgListTy.push_back(ArgList[i].Ty);
    2422             : 
    2423       35248 :   Result = FunctionType::get(Result, ArgListTy, isVarArg);
    2424             :   return false;
    2425             : }
    2426             : 
    2427             : /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
    2428             : /// other structs.
    2429       19877 : bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
    2430             :   SmallVector<Type*, 8> Elts;
    2431       19877 :   if (ParseStructBody(Elts)) return true;
    2432             : 
    2433       39754 :   Result = StructType::get(Context, Elts, Packed);
    2434       19877 :   return false;
    2435             : }
    2436             : 
    2437             : /// ParseStructDefinition - Parse a struct in a 'type' definition.
    2438       11620 : bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
    2439             :                                      std::pair<Type*, LocTy> &Entry,
    2440             :                                      Type *&ResultTy) {
    2441             :   // If the type was already defined, diagnose the redefinition.
    2442       15825 :   if (Entry.first && !Entry.second.isValid())
    2443           0 :     return Error(TypeLoc, "redefinition of type");
    2444             : 
    2445             :   // If we have opaque, just return without filling in the definition for the
    2446             :   // struct.  This counts as a definition as far as the .ll file goes.
    2447             :   if (EatIfPresent(lltok::kw_opaque)) {
    2448             :     // This type is being defined, so clear the location to indicate this.
    2449         708 :     Entry.second = SMLoc();
    2450             : 
    2451             :     // If this type number has never been uttered, create it.
    2452         708 :     if (!Entry.first)
    2453         395 :       Entry.first = StructType::create(Context, Name);
    2454         708 :     ResultTy = Entry.first;
    2455         708 :     return false;
    2456             :   }
    2457             : 
    2458             :   // If the type starts with '<', then it is either a packed struct or a vector.
    2459             :   bool isPacked = EatIfPresent(lltok::less);
    2460             : 
    2461             :   // If we don't have a struct, then we have a random type alias, which we
    2462             :   // accept for compatibility with old files.  These types are not allowed to be
    2463             :   // forward referenced and not allowed to be recursive.
    2464       10912 :   if (Lex.getKind() != lltok::lbrace) {
    2465         444 :     if (Entry.first)
    2466           0 :       return Error(TypeLoc, "forward references to non-struct type");
    2467             : 
    2468         444 :     ResultTy = nullptr;
    2469         444 :     if (isPacked)
    2470         374 :       return ParseArrayVectorType(ResultTy, true);
    2471          70 :     return ParseType(ResultTy);
    2472             :   }
    2473             : 
    2474             :   // This type is being defined, so clear the location to indicate this.
    2475       10468 :   Entry.second = SMLoc();
    2476             : 
    2477             :   // If this type number has never been uttered, create it.
    2478       10468 :   if (!Entry.first)
    2479        6576 :     Entry.first = StructType::create(Context, Name);
    2480             : 
    2481       10468 :   StructType *STy = cast<StructType>(Entry.first);
    2482             : 
    2483             :   SmallVector<Type*, 8> Body;
    2484       10468 :   if (ParseStructBody(Body) ||
    2485         729 :       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
    2486             :     return true;
    2487             : 
    2488       20936 :   STy->setBody(Body, isPacked);
    2489       10468 :   ResultTy = STy;
    2490       10468 :   return false;
    2491             : }
    2492             : 
    2493             : /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
    2494             : ///   StructType
    2495             : ///     ::= '{' '}'
    2496             : ///     ::= '{' Type (',' Type)* '}'
    2497             : ///     ::= '<' '{' '}' '>'
    2498             : ///     ::= '<' '{' Type (',' Type)* '}' '>'
    2499       30345 : bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
    2500             :   assert(Lex.getKind() == lltok::lbrace);
    2501       30345 :   Lex.Lex(); // Consume the '{'
    2502             : 
    2503             :   // Handle the empty struct.
    2504             :   if (EatIfPresent(lltok::rbrace))
    2505             :     return false;
    2506             : 
    2507       29772 :   LocTy EltTyLoc = Lex.getLoc();
    2508       29772 :   Type *Ty = nullptr;
    2509       29772 :   if (ParseType(Ty)) return true;
    2510       29772 :   Body.push_back(Ty);
    2511             : 
    2512       29772 :   if (!StructType::isValidElementType(Ty))
    2513           0 :     return Error(EltTyLoc, "invalid element type for struct");
    2514             : 
    2515       72646 :   while (EatIfPresent(lltok::comma)) {
    2516       72646 :     EltTyLoc = Lex.getLoc();
    2517       72646 :     if (ParseType(Ty)) return true;
    2518             : 
    2519       72646 :     if (!StructType::isValidElementType(Ty))
    2520           0 :       return Error(EltTyLoc, "invalid element type for struct");
    2521             : 
    2522       72646 :     Body.push_back(Ty);
    2523             :   }
    2524             : 
    2525       29772 :   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
    2526             : }
    2527             : 
    2528             : /// ParseArrayVectorType - Parse an array or vector type, assuming the first
    2529             : /// token has already been consumed.
    2530             : ///   Type
    2531             : ///     ::= '[' APSINTVAL 'x' Types ']'
    2532             : ///     ::= '<' APSINTVAL 'x' Types '>'
    2533     1182441 : bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
    2534     2364882 :   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
    2535     1182441 :       Lex.getAPSIntVal().getBitWidth() > 64)
    2536           0 :     return TokError("expected number in address space");
    2537             : 
    2538     1182441 :   LocTy SizeLoc = Lex.getLoc();
    2539             :   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
    2540     1182441 :   Lex.Lex();
    2541             : 
    2542     1182441 :   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
    2543             :       return true;
    2544             : 
    2545     1182441 :   LocTy TypeLoc = Lex.getLoc();
    2546     1182441 :   Type *EltTy = nullptr;
    2547     1182441 :   if (ParseType(EltTy)) return true;
    2548             : 
    2549     1182441 :   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
    2550             :                  "expected end of sequential type"))
    2551             :     return true;
    2552             : 
    2553     1182441 :   if (isVector) {
    2554     1061998 :     if (Size == 0)
    2555           0 :       return Error(SizeLoc, "zero element vector is illegal");
    2556     1061998 :     if ((unsigned)Size != Size)
    2557           0 :       return Error(SizeLoc, "size too large for vector");
    2558     1061998 :     if (!VectorType::isValidElementType(EltTy))
    2559           0 :       return Error(TypeLoc, "invalid vector element type");
    2560     1061998 :     Result = VectorType::get(EltTy, unsigned(Size));
    2561             :   } else {
    2562      120443 :     if (!ArrayType::isValidElementType(EltTy))
    2563           1 :       return Error(TypeLoc, "invalid array element type");
    2564      120442 :     Result = ArrayType::get(EltTy, Size);
    2565             :   }
    2566             :   return false;
    2567             : }
    2568             : 
    2569             : //===----------------------------------------------------------------------===//
    2570             : // Function Semantic Analysis.
    2571             : //===----------------------------------------------------------------------===//
    2572             : 
    2573      211470 : LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
    2574      211470 :                                              int functionNumber)
    2575      634410 :   : P(p), F(f), FunctionNumber(functionNumber) {
    2576             : 
    2577             :   // Insert unnamed arguments into the NumberedVals list.
    2578      566507 :   for (Argument &A : F.args())
    2579      355037 :     if (!A.hasName())
    2580        6950 :       NumberedVals.push_back(&A);
    2581      211470 : }
    2582             : 
    2583      422940 : LLParser::PerFunctionState::~PerFunctionState() {
    2584             :   // If there were any forward referenced non-basicblock values, delete them.
    2585             : 
    2586      211477 :   for (const auto &P : ForwardRefVals) {
    2587          14 :     if (isa<BasicBlock>(P.second.first))
    2588           1 :       continue;
    2589           6 :     P.second.first->replaceAllUsesWith(
    2590           6 :         UndefValue::get(P.second.first->getType()));
    2591           6 :     P.second.first->deleteValue();
    2592             :   }
    2593             : 
    2594      211471 :   for (const auto &P : ForwardRefValIDs) {
    2595           2 :     if (isa<BasicBlock>(P.second.first))
    2596           0 :       continue;
    2597           1 :     P.second.first->replaceAllUsesWith(
    2598           1 :         UndefValue::get(P.second.first->getType()));
    2599           1 :     P.second.first->deleteValue();
    2600             :   }
    2601      211470 : }
    2602             : 
    2603      211403 : bool LLParser::PerFunctionState::FinishFunction() {
    2604      211403 :   if (!ForwardRefVals.empty())
    2605           4 :     return P.Error(ForwardRefVals.begin()->second.second,
    2606           6 :                    "use of undefined value '%" + ForwardRefVals.begin()->first +
    2607             :                    "'");
    2608      211401 :   if (!ForwardRefValIDs.empty())
    2609           0 :     return P.Error(ForwardRefValIDs.begin()->second.second,
    2610           0 :                    "use of undefined value '%" +
    2611           0 :                    Twine(ForwardRefValIDs.begin()->first) + "'");
    2612             :   return false;
    2613             : }
    2614             : 
    2615             : /// GetVal - Get a value with the specified name or ID, creating a
    2616             : /// forward reference record if needed.  This can return null if the value
    2617             : /// exists but does not have the right type.
    2618     1436878 : Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
    2619             :                                           LocTy Loc) {
    2620             :   // Look this name up in the normal function symbol table.
    2621     1436878 :   Value *Val = F.getValueSymbolTable()->lookup(Name);
    2622             : 
    2623             :   // If this is a forward reference for the value, see if we already created a
    2624             :   // forward ref record.
    2625     1436878 :   if (!Val) {
    2626             :     auto I = ForwardRefVals.find(Name);
    2627      171555 :     if (I != ForwardRefVals.end())
    2628         797 :       Val = I->second.first;
    2629             :   }
    2630             : 
    2631             :   // If we have the value in the symbol table or fwd-ref table, return it.
    2632     1436878 :   if (Val) {
    2633     1266120 :     if (Val->getType() == Ty) return Val;
    2634           3 :     if (Ty->isLabelTy())
    2635           0 :       P.Error(Loc, "'%" + Name + "' is not a basic block");
    2636             :     else
    2637          18 :       P.Error(Loc, "'%" + Name + "' defined with type '" +
    2638          12 :               getTypeString(Val->getType()) + "'");
    2639             :     return nullptr;
    2640             :   }
    2641             : 
    2642             :   // Don't make placeholders with invalid type.
    2643             :   if (!Ty->isFirstClassType()) {
    2644           0 :     P.Error(Loc, "invalid use of a non-first-class type");
    2645           0 :     return nullptr;
    2646             :   }
    2647             : 
    2648             :   // Otherwise, create a new forward reference for this value and remember it.
    2649             :   Value *FwdVal;
    2650      170758 :   if (Ty->isLabelTy()) {
    2651      468774 :     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
    2652             :   } else {
    2653       14500 :     FwdVal = new Argument(Ty, Name);
    2654             :   }
    2655             : 
    2656      170758 :   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
    2657      170758 :   return FwdVal;
    2658             : }
    2659             : 
    2660      375568 : Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
    2661             :   // Look this name up in the normal function symbol table.
    2662      984004 :   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
    2663             : 
    2664             :   // If this is a forward reference for the value, see if we already created a
    2665             :   // forward ref record.
    2666      232868 :   if (!Val) {
    2667             :     auto I = ForwardRefValIDs.find(ID);
    2668      142700 :     if (I != ForwardRefValIDs.end())
    2669        2788 :       Val = I->second.first;
    2670             :   }
    2671             : 
    2672             :   // If we have the value in the symbol table or fwd-ref table, return it.
    2673      375568 :   if (Val) {
    2674      235656 :     if (Val->getType() == Ty) return Val;
    2675           3 :     if (Ty->isLabelTy())
    2676           0 :       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
    2677             :     else
    2678           9 :       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
    2679          12 :               getTypeString(Val->getType()) + "'");
    2680             :     return nullptr;
    2681             :   }
    2682             : 
    2683             :   if (!Ty->isFirstClassType()) {
    2684           0 :     P.Error(Loc, "invalid use of a non-first-class type");
    2685           0 :     return nullptr;
    2686             :   }
    2687             : 
    2688             :   // Otherwise, create a new forward reference for this value and remember it.
    2689             :   Value *FwdVal;
    2690      139912 :   if (Ty->isLabelTy()) {
    2691      416844 :     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
    2692             :   } else {
    2693         964 :     FwdVal = new Argument(Ty);
    2694             :   }
    2695             : 
    2696      139912 :   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
    2697      139912 :   return FwdVal;
    2698             : }
    2699             : 
    2700             : /// SetInstName - After an instruction is parsed and inserted into its
    2701             : /// basic block, this installs its name.
    2702     1274695 : bool LLParser::PerFunctionState::SetInstName(int NameID,
    2703             :                                              const std::string &NameStr,
    2704             :                                              LocTy NameLoc, Instruction *Inst) {
    2705             :   // If this instruction has void type, it cannot have a name or ID specified.
    2706     2549390 :   if (Inst->getType()->isVoidTy()) {
    2707      902496 :     if (NameID != -1 || !NameStr.empty())
    2708           0 :       return P.Error(NameLoc, "instructions returning void cannot have a name");
    2709             :     return false;
    2710             :   }
    2711             : 
    2712             :   // If this was a numbered instruction, verify that the instruction is the
    2713             :   // expected value and resolve any forward references.
    2714      823447 :   if (NameStr.empty()) {
    2715             :     // If neither a name nor an ID was specified, just use the next ID.
    2716      215344 :     if (NameID == -1)
    2717       11676 :       NameID = NumberedVals.size();
    2718             : 
    2719      430688 :     if (unsigned(NameID) != NumberedVals.size())
    2720           0 :       return P.Error(NameLoc, "instruction expected to be numbered '%" +
    2721           0 :                      Twine(NumberedVals.size()) + "'");
    2722             : 
    2723             :     auto FI = ForwardRefValIDs.find(NameID);
    2724      215344 :     if (FI != ForwardRefValIDs.end()) {
    2725         963 :       Value *Sentinel = FI->second.first;
    2726         963 :       if (Sentinel->getType() != Inst->getType())
    2727           0 :         return P.Error(NameLoc, "instruction forward referenced with type '" +
    2728           0 :                        getTypeString(FI->second.first->getType()) + "'");
    2729             : 
    2730         963 :       Sentinel->replaceAllUsesWith(Inst);
    2731         963 :       Sentinel->deleteValue();
    2732             :       ForwardRefValIDs.erase(FI);
    2733             :     }
    2734             : 
    2735      430688 :     NumberedVals.push_back(Inst);
    2736      215344 :     return false;
    2737             :   }
    2738             : 
    2739             :   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
    2740             :   auto FI = ForwardRefVals.find(NameStr);
    2741      608103 :   if (FI != ForwardRefVals.end()) {
    2742       14494 :     Value *Sentinel = FI->second.first;
    2743       14494 :     if (Sentinel->getType() != Inst->getType())
    2744           0 :       return P.Error(NameLoc, "instruction forward referenced with type '" +
    2745           0 :                      getTypeString(FI->second.first->getType()) + "'");
    2746             : 
    2747       14494 :     Sentinel->replaceAllUsesWith(Inst);
    2748       14494 :     Sentinel->deleteValue();
    2749             :     ForwardRefVals.erase(FI);
    2750             :   }
    2751             : 
    2752             :   // Set the name on the instruction.
    2753     1216206 :   Inst->setName(NameStr);
    2754             : 
    2755      608103 :   if (Inst->getName() != NameStr)
    2756           3 :     return P.Error(NameLoc, "multiple definition of local value named '" +
    2757           2 :                    NameStr + "'");
    2758             :   return false;
    2759             : }
    2760             : 
    2761             : /// GetBB - Get a basic block with the specified name or ID, creating a
    2762             : /// forward reference record if needed.
    2763      156731 : BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
    2764             :                                               LocTy Loc) {
    2765      156731 :   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
    2766      313462 :                                       Type::getLabelTy(F.getContext()), Loc));
    2767             : }
    2768             : 
    2769      138961 : BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
    2770      138961 :   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
    2771      277922 :                                       Type::getLabelTy(F.getContext()), Loc));
    2772             : }
    2773             : 
    2774             : /// DefineBB - Define the specified basic block, which is either named or
    2775             : /// unnamed.  If there is an error, this returns null otherwise it returns
    2776             : /// the block being defined.
    2777      295206 : BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
    2778             :                                                  LocTy Loc) {
    2779             :   BasicBlock *BB;
    2780      295206 :   if (Name.empty())
    2781      277896 :     BB = GetBB(NumberedVals.size(), Loc);
    2782             :   else
    2783      156258 :     BB = GetBB(Name, Loc);
    2784      295206 :   if (!BB) return nullptr; // Already diagnosed error.
    2785             : 
    2786             :   // Move the block to the end of the function.  Forward ref'd blocks are
    2787             :   // inserted wherever they happen to be referenced.
    2788      590410 :   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
    2789             : 
    2790             :   // Remove the block from forward ref sets.
    2791      295205 :   if (Name.empty()) {
    2792      416844 :     ForwardRefValIDs.erase(NumberedVals.size());
    2793      277896 :     NumberedVals.push_back(BB);
    2794             :   } else {
    2795             :     // BB forward references are already in the function symbol table.
    2796             :     ForwardRefVals.erase(Name);
    2797             :   }
    2798             : 
    2799             :   return BB;
    2800             : }
    2801             : 
    2802             : //===----------------------------------------------------------------------===//
    2803             : // Constants.
    2804             : //===----------------------------------------------------------------------===//
    2805             : 
    2806             : /// ParseValID - Parse an abstract value that doesn't necessarily have a
    2807             : /// type implied.  For example, if we parse "4" we don't know what integer type
    2808             : /// it has.  The value will later be combined with its type and checked for
    2809             : /// sanity.  PFS is used to convert function-local operands of metadata (since
    2810             : /// metadata operands are not just parsed here but also converted to values).
    2811             : /// PFS can be null when we are not parsing metadata values inside a function.
    2812     3101228 : bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
    2813     3101228 :   ID.Loc = Lex.getLoc();
    2814     3101228 :   switch (Lex.getKind()) {
    2815           1 :   default: return TokError("expected value token");
    2816         643 :   case lltok::GlobalID:  // @42
    2817         643 :     ID.UIntVal = Lex.getUIntVal();
    2818         643 :     ID.Kind = ValID::t_GlobalID;
    2819         643 :     break;
    2820      186782 :   case lltok::GlobalVar:  // @foo
    2821      186782 :     ID.StrVal = Lex.getStrVal();
    2822      186782 :     ID.Kind = ValID::t_GlobalName;
    2823      186782 :     break;
    2824      236626 :   case lltok::LocalVarID:  // %42
    2825      236626 :     ID.UIntVal = Lex.getUIntVal();
    2826      236626 :     ID.Kind = ValID::t_LocalID;
    2827      236626 :     break;
    2828     1280755 :   case lltok::LocalVar:  // %foo
    2829     1280755 :     ID.StrVal = Lex.getStrVal();
    2830     1280755 :     ID.Kind = ValID::t_LocalName;
    2831     1280755 :     break;
    2832     1046029 :   case lltok::APSInt:
    2833             :     ID.APSIntVal = Lex.getAPSIntVal();
    2834     1046029 :     ID.Kind = ValID::t_APSInt;
    2835     1046029 :     break;
    2836       42073 :   case lltok::APFloat:
    2837             :     ID.APFloatVal = Lex.getAPFloatVal();
    2838       42073 :     ID.Kind = ValID::t_APFloat;
    2839       42073 :     break;
    2840        6497 :   case lltok::kw_true:
    2841        6497 :     ID.ConstantVal = ConstantInt::getTrue(Context);
    2842        6497 :     ID.Kind = ValID::t_Constant;
    2843        6497 :     break;
    2844       14115 :   case lltok::kw_false:
    2845       14115 :     ID.ConstantVal = ConstantInt::getFalse(Context);
    2846       14115 :     ID.Kind = ValID::t_Constant;
    2847       14115 :     break;
    2848        6807 :   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
    2849      133247 :   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
    2850       24787 :   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
    2851         443 :   case lltok::kw_none: ID.Kind = ValID::t_None; break;
    2852             : 
    2853        1560 :   case lltok::lbrace: {
    2854             :     // ValID ::= '{' ConstVector '}'
    2855        1560 :     Lex.Lex();
    2856             :     SmallVector<Constant*, 16> Elts;
    2857        3115 :     if (ParseGlobalValueVector(Elts) ||
    2858        1555 :         ParseToken(lltok::rbrace, "expected end of struct constant"))
    2859             :       return true;
    2860             : 
    2861        3110 :     ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
    2862        1555 :     ID.UIntVal = Elts.size();
    2863        3110 :     memcpy(ID.ConstantStructElts.get(), Elts.data(),
    2864             :            Elts.size() * sizeof(Elts[0]));
    2865        1555 :     ID.Kind = ValID::t_ConstantStruct;
    2866        1555 :     return false;
    2867             :   }
    2868       60872 :   case lltok::less: {
    2869             :     // ValID ::= '<' ConstVector '>'         --> Vector.
    2870             :     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
    2871       60872 :     Lex.Lex();
    2872             :     bool isPackedStruct = EatIfPresent(lltok::lbrace);
    2873             : 
    2874             :     SmallVector<Constant*, 16> Elts;
    2875       60872 :     LocTy FirstEltLoc = Lex.getLoc();
    2876      121744 :     if (ParseGlobalValueVector(Elts) ||
    2877          88 :         (isPackedStruct &&
    2878      121832 :          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
    2879       60872 :         ParseToken(lltok::greater, "expected end of constant"))
    2880             :       return true;
    2881             : 
    2882       60872 :     if (isPackedStruct) {
    2883         176 :       ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
    2884         176 :       memcpy(ID.ConstantStructElts.get(), Elts.data(),
    2885             :              Elts.size() * sizeof(Elts[0]));
    2886          88 :       ID.UIntVal = Elts.size();
    2887          88 :       ID.Kind = ValID::t_PackedConstantStruct;
    2888          88 :       return false;
    2889             :     }
    2890             : 
    2891       60784 :     if (Elts.empty())
    2892           0 :       return Error(ID.Loc, "constant vector must not be empty");
    2893             : 
    2894       60784 :     if (!Elts[0]->getType()->isIntegerTy() &&
    2895       60801 :         !Elts[0]->getType()->isFloatingPointTy() &&
    2896             :         !Elts[0]->getType()->isPointerTy())
    2897           0 :       return Error(FirstEltLoc,
    2898             :             "vector elements must have integer, pointer or floating point type");
    2899             : 
    2900             :     // Verify that all the vector elements have the same type.
    2901     1503190 :     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
    2902     1381622 :       if (Elts[i]->getType() != Elts[0]->getType())
    2903             :         return Error(FirstEltLoc,
    2904           0 :                      "vector element #" + Twine(i) +
    2905           0 :                     " is not of type '" + getTypeString(Elts[0]->getType()));
    2906             : 
    2907       60784 :     ID.ConstantVal = ConstantVector::get(Elts);
    2908       60784 :     ID.Kind = ValID::t_Constant;
    2909       60784 :     return false;
    2910             :   }
    2911        1211 :   case lltok::lsquare: {   // Array Constant
    2912        1211 :     Lex.Lex();
    2913             :     SmallVector<Constant*, 16> Elts;
    2914        1211 :     LocTy FirstEltLoc = Lex.getLoc();
    2915        2422 :     if (ParseGlobalValueVector(Elts) ||
    2916        1211 :         ParseToken(lltok::rsquare, "expected end of array constant"))
    2917             :       return true;
    2918             : 
    2919             :     // Handle empty element.
    2920        1211 :     if (Elts.empty()) {
    2921             :       // Use undef instead of an array because it's inconvenient to determine
    2922             :       // the element type at this point, there being no elements to examine.
    2923          16 :       ID.Kind = ValID::t_EmptyArray;
    2924          16 :       return false;
    2925             :     }
    2926             : 
    2927        1195 :     if (!Elts[0]->getType()->isFirstClassType())
    2928           0 :       return Error(FirstEltLoc, "invalid array element type: " +
    2929           0 :                    getTypeString(Elts[0]->getType()));
    2930             : 
    2931        1195 :     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
    2932             : 
    2933             :     // Verify all elements are correct type!
    2934       12462 :     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
    2935       10072 :       if (Elts[i]->getType() != Elts[0]->getType())
    2936             :         return Error(FirstEltLoc,
    2937           0 :                      "array element #" + Twine(i) +
    2938           0 :                      " is not of type '" + getTypeString(Elts[0]->getType()));
    2939             :     }
    2940             : 
    2941        1195 :     ID.ConstantVal = ConstantArray::get(ATy, Elts);
    2942        1195 :     ID.Kind = ValID::t_Constant;
    2943        1195 :     return false;
    2944             :   }
    2945        1763 :   case lltok::kw_c:  // c "foo"
    2946        1763 :     Lex.Lex();
    2947        1763 :     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
    2948             :                                                   false);
    2949        1763 :     if (ParseToken(lltok::StringConstant, "expected string")) return true;
    2950        1763 :     ID.Kind = ValID::t_Constant;
    2951        1763 :     return false;
    2952             : 
    2953       11820 :   case lltok::kw_asm: {
    2954             :     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
    2955             :     //             STRINGCONSTANT
    2956             :     bool HasSideEffect, AlignStack, AsmDialect;
    2957       11820 :     Lex.Lex();
    2958       11820 :     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
    2959             :         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
    2960       11820 :         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
    2961       23640 :         ParseStringConstant(ID.StrVal) ||
    2962       23640 :         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
    2963       11820 :         ParseToken(lltok::StringConstant, "expected constraint string"))
    2964             :       return true;
    2965       11820 :     ID.StrVal2 = Lex.getStrVal();
    2966       23640 :     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
    2967       11820 :       (unsigned(AsmDialect)<<2);
    2968       11820 :     ID.Kind = ValID::t_InlineAsm;
    2969       11820 :     return false;
    2970             :   }
    2971             : 
    2972         611 :   case lltok::kw_blockaddress: {
    2973             :     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
    2974         611 :     Lex.Lex();
    2975             : 
    2976        1222 :     ValID Fn, Label;
    2977             : 
    2978        1222 :     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
    2979        1222 :         ParseValID(Fn) ||
    2980        1222 :         ParseToken(lltok::comma, "expected comma in block address expression")||
    2981        1833 :         ParseValID(Label) ||
    2982         611 :         ParseToken(lltok::rparen, "expected ')' in block address expression"))
    2983             :       return true;
    2984             : 
    2985         611 :     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
    2986           0 :       return Error(Fn.Loc, "expected function name in blockaddress");
    2987         611 :     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
    2988           0 :       return Error(Label.Loc, "expected basic block name in blockaddress");
    2989             : 
    2990             :     // Try to find the function (but skip it if it's forward-referenced).
    2991             :     GlobalValue *GV = nullptr;
    2992         611 :     if (Fn.Kind == ValID::t_GlobalID) {
    2993           0 :       if (Fn.UIntVal < NumberedVals.size())
    2994           0 :         GV = NumberedVals[Fn.UIntVal];
    2995             :     } else if (!ForwardRefVals.count(Fn.StrVal)) {
    2996        1222 :       GV = M->getNamedValue(Fn.StrVal);
    2997             :     }
    2998             :     Function *F = nullptr;
    2999         611 :     if (GV) {
    3000             :       // Confirm that it's actually a function with a definition.
    3001         290 :       if (!isa<Function>(GV))
    3002           0 :         return Error(Fn.Loc, "expected function name in blockaddress");
    3003             :       F = cast<Function>(GV);
    3004         290 :       if (F->isDeclaration())
    3005           0 :         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
    3006             :     }
    3007             : 
    3008             :     if (!F) {
    3009             :       // Make a global variable as a placeholder for this reference.
    3010             :       GlobalValue *&FwdRef =
    3011         321 :           ForwardRefBlockAddresses.insert(std::make_pair(
    3012             :                                               std::move(Fn),
    3013         321 :                                               std::map<ValID, GlobalValue *>()))
    3014         321 :               .first->second.insert(std::make_pair(std::move(Label), nullptr))
    3015             :               .first->second;
    3016         321 :       if (!FwdRef)
    3017         807 :         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
    3018         269 :                                     GlobalValue::InternalLinkage, nullptr, "");
    3019         321 :       ID.ConstantVal = FwdRef;
    3020         321 :       ID.Kind = ValID::t_Constant;
    3021         321 :       return false;
    3022             :     }
    3023             : 
    3024             :     // We found the function; now find the basic block.  Don't use PFS, since we
    3025             :     // might be inside a constant expression.
    3026             :     BasicBlock *BB;
    3027         578 :     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
    3028         217 :       if (Label.Kind == ValID::t_LocalID)
    3029           4 :         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
    3030             :       else
    3031         213 :         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
    3032         217 :       if (!BB)
    3033           0 :         return Error(Label.Loc, "referenced value is not a basic block");
    3034             :     } else {
    3035          73 :       if (Label.Kind == ValID::t_LocalID)
    3036           0 :         return Error(Label.Loc, "cannot take address of numeric label after "
    3037             :                                 "the function is defined");
    3038             :       BB = dyn_cast_or_null<BasicBlock>(
    3039             :           F->getValueSymbolTable()->lookup(Label.StrVal));
    3040             :       if (!BB)
    3041           0 :         return Error(Label.Loc, "referenced value is not a basic block");
    3042             :     }
    3043             : 
    3044         290 :     ID.ConstantVal = BlockAddress::get(F, BB);
    3045         290 :     ID.Kind = ValID::t_Constant;
    3046         290 :     return false;
    3047             :   }
    3048             : 
    3049        7772 :   case lltok::kw_trunc:
    3050             :   case lltok::kw_zext:
    3051             :   case lltok::kw_sext:
    3052             :   case lltok::kw_fptrunc:
    3053             :   case lltok::kw_fpext:
    3054             :   case lltok::kw_bitcast:
    3055             :   case lltok::kw_addrspacecast:
    3056             :   case lltok::kw_uitofp:
    3057             :   case lltok::kw_sitofp:
    3058             :   case lltok::kw_fptoui:
    3059             :   case lltok::kw_fptosi:
    3060             :   case lltok::kw_inttoptr:
    3061             :   case lltok::kw_ptrtoint: {
    3062        7772 :     unsigned Opc = Lex.getUIntVal();
    3063        7772 :     Type *DestTy = nullptr;
    3064             :     Constant *SrcVal;
    3065        7772 :     Lex.Lex();
    3066       15544 :     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
    3067       15543 :         ParseGlobalTypeAndValue(SrcVal) ||
    3068       15542 :         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
    3069       15543 :         ParseType(DestTy) ||
    3070        7771 :         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
    3071             :       return true;
    3072        7771 :     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
    3073          30 :       return Error(ID.Loc, "invalid cast opcode for cast from '" +
    3074          50 :                    getTypeString(SrcVal->getType()) + "' to '" +
    3075          40 :                    getTypeString(DestTy) + "'");
    3076        7761 :     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
    3077             :                                                  SrcVal, DestTy);
    3078        7761 :     ID.Kind = ValID::t_Constant;
    3079        7761 :     return false;
    3080             :   }
    3081          11 :   case lltok::kw_extractvalue: {
    3082          11 :     Lex.Lex();
    3083             :     Constant *Val;
    3084             :     SmallVector<unsigned, 4> Indices;
    3085          22 :     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
    3086          22 :         ParseGlobalTypeAndValue(Val) ||
    3087          33 :         ParseIndexList(Indices) ||
    3088          11 :         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
    3089             :       return true;
    3090             : 
    3091          11 :     if (!Val->getType()->isAggregateType())
    3092           0 :       return Error(ID.Loc, "extractvalue operand must be aggregate type");
    3093          11 :     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
    3094           0 :       return Error(ID.Loc, "invalid indices for extractvalue");
    3095          11 :     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
    3096          11 :     ID.Kind = ValID::t_Constant;
    3097          11 :     return false;
    3098             :   }
    3099          10 :   case lltok::kw_insertvalue: {
    3100          10 :     Lex.Lex();
    3101             :     Constant *Val0, *Val1;
    3102             :     SmallVector<unsigned, 4> Indices;
    3103          20 :     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
    3104          20 :         ParseGlobalTypeAndValue(Val0) ||
    3105          20 :         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
    3106          20 :         ParseGlobalTypeAndValue(Val1) ||
    3107          30 :         ParseIndexList(Indices) ||
    3108          10 :         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
    3109             :       return true;
    3110          10 :     if (!Val0->getType()->isAggregateType())
    3111           0 :       return Error(ID.Loc, "insertvalue operand must be aggregate type");
    3112             :     Type *IndexedType =
    3113          10 :         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
    3114          10 :     if (!IndexedType)
    3115           0 :       return Error(ID.Loc, "invalid indices for insertvalue");
    3116          10 :     if (IndexedType != Val1->getType())
    3117           3 :       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
    3118           4 :                                getTypeString(Val1->getType()) +
    3119           5 :                                "' instead of '" + getTypeString(IndexedType) +
    3120             :                                "'");
    3121           9 :     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
    3122           9 :     ID.Kind = ValID::t_Constant;
    3123           9 :     return false;
    3124             :   }
    3125         267 :   case lltok::kw_icmp:
    3126             :   case lltok::kw_fcmp: {
    3127         267 :     unsigned PredVal, Opc = Lex.getUIntVal();
    3128             :     Constant *Val0, *Val1;
    3129         267 :     Lex.Lex();
    3130         534 :     if (ParseCmpPredicate(PredVal, Opc) ||
    3131         534 :         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
    3132         534 :         ParseGlobalTypeAndValue(Val0) ||
    3133         534 :         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
    3134         801 :         ParseGlobalTypeAndValue(Val1) ||
    3135         267 :         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
    3136             :       return true;
    3137             : 
    3138         267 :     if (Val0->getType() != Val1->getType())
    3139           0 :       return Error(ID.Loc, "compare operands must have the same type");
    3140             : 
    3141         267 :     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
    3142             : 
    3143         267 :     if (Opc == Instruction::FCmp) {
    3144             :       if (!Val0->getType()->isFPOrFPVectorTy())
    3145           0 :         return Error(ID.Loc, "fcmp requires floating point operands");
    3146           6 :       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
    3147             :     } else {
    3148             :       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
    3149         261 :       if (!Val0->getType()->isIntOrIntVectorTy() &&
    3150             :           !Val0->getType()->isPtrOrPtrVectorTy())
    3151           0 :         return Error(ID.Loc, "icmp requires pointer or integer operands");
    3152         261 :       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
    3153             :     }
    3154         267 :     ID.Kind = ValID::t_Constant;
    3155         267 :     return false;
    3156             :   }
    3157             : 
    3158             :   // Binary Operators.
    3159         629 :   case lltok::kw_add:
    3160             :   case lltok::kw_fadd:
    3161             :   case lltok::kw_sub:
    3162             :   case lltok::kw_fsub:
    3163             :   case lltok::kw_mul:
    3164             :   case lltok::kw_fmul:
    3165             :   case lltok::kw_udiv:
    3166             :   case lltok::kw_sdiv:
    3167             :   case lltok::kw_fdiv:
    3168             :   case lltok::kw_urem:
    3169             :   case lltok::kw_srem:
    3170             :   case lltok::kw_frem:
    3171             :   case lltok::kw_shl:
    3172             :   case lltok::kw_lshr:
    3173             :   case lltok::kw_ashr: {
    3174             :     bool NUW = false;
    3175             :     bool NSW = false;
    3176             :     bool Exact = false;
    3177         629 :     unsigned Opc = Lex.getUIntVal();
    3178             :     Constant *Val0, *Val1;
    3179         629 :     Lex.Lex();
    3180         629 :     LocTy ModifierLoc = Lex.getLoc();
    3181         629 :     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
    3182         270 :         Opc == Instruction::Mul || Opc == Instruction::Shl) {
    3183             :       if (EatIfPresent(lltok::kw_nuw))
    3184             :         NUW = true;
    3185             :       if (EatIfPresent(lltok::kw_nsw)) {
    3186             :         NSW = true;
    3187             :         if (EatIfPresent(lltok::kw_nuw))
    3188             :           NUW = true;
    3189             :       }
    3190         310 :     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
    3191         219 :                Opc == Instruction::LShr || Opc == Instruction::AShr) {
    3192             :       if (EatIfPresent(lltok::kw_exact))
    3193             :         Exact = true;
    3194             :     }
    3195        1258 :     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
    3196        1258 :         ParseGlobalTypeAndValue(Val0) ||
    3197        1258 :         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
    3198        1887 :         ParseGlobalTypeAndValue(Val1) ||
    3199         629 :         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
    3200             :       return true;
    3201         629 :     if (Val0->getType() != Val1->getType())
    3202           0 :       return Error(ID.Loc, "operands of constexpr must have same type");
    3203         629 :     if (!Val0->getType()->isIntOrIntVectorTy()) {
    3204          29 :       if (NUW)
    3205           0 :         return Error(ModifierLoc, "nuw only applies to integer operations");
    3206          29 :       if (NSW)
    3207           0 :         return Error(ModifierLoc, "nsw only applies to integer operations");
    3208             :     }
    3209             :     // Check that the type is valid for the operator.
    3210             :     switch (Opc) {
    3211             :     case Instruction::Add:
    3212             :     case Instruction::Sub:
    3213             :     case Instruction::Mul:
    3214             :     case Instruction::UDiv:
    3215             :     case Instruction::SDiv:
    3216             :     case Instruction::URem:
    3217             :     case Instruction::SRem:
    3218             :     case Instruction::Shl:
    3219             :     case Instruction::AShr:
    3220             :     case Instruction::LShr:
    3221         601 :       if (!Val0->getType()->isIntOrIntVectorTy())
    3222           1 :         return Error(ID.Loc, "constexpr requires integer operands");
    3223             :       break;
    3224             :     case Instruction::FAdd:
    3225             :     case Instruction::FSub:
    3226             :     case Instruction::FMul:
    3227             :     case Instruction::FDiv:
    3228             :     case Instruction::FRem:
    3229             :       if (!Val0->getType()->isFPOrFPVectorTy())
    3230           0 :         return Error(ID.Loc, "constexpr requires fp operands");
    3231             :       break;
    3232           0 :     default: llvm_unreachable("Unknown binary operator!");
    3233             :     }
    3234             :     unsigned Flags = 0;
    3235         628 :     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
    3236         628 :     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
    3237         628 :     if (Exact) Flags |= PossiblyExactOperator::IsExact;
    3238         628 :     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
    3239         628 :     ID.ConstantVal = C;
    3240         628 :     ID.Kind = ValID::t_Constant;
    3241         628 :     return false;
    3242             :   }
    3243             : 
    3244             :   // Logical Operations
    3245         111 :   case lltok::kw_and:
    3246             :   case lltok::kw_or:
    3247             :   case lltok::kw_xor: {
    3248         111 :     unsigned Opc = Lex.getUIntVal();
    3249             :     Constant *Val0, *Val1;
    3250         111 :     Lex.Lex();
    3251         222 :     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
    3252         222 :         ParseGlobalTypeAndValue(Val0) ||
    3253         222 :         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
    3254         333 :         ParseGlobalTypeAndValue(Val1) ||
    3255         111 :         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
    3256             :       return true;
    3257         111 :     if (Val0->getType() != Val1->getType())
    3258           0 :       return Error(ID.Loc, "operands of constexpr must have same type");
    3259         111 :     if (!Val0->getType()->isIntOrIntVectorTy())
    3260           0 :       return Error(ID.Loc,
    3261             :                    "constexpr requires integer or integer vector operands");
    3262         111 :     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
    3263         111 :     ID.Kind = ValID::t_Constant;
    3264         111 :     return false;
    3265             :   }
    3266             : 
    3267       35786 :   case lltok::kw_getelementptr:
    3268             :   case lltok::kw_shufflevector:
    3269             :   case lltok::kw_insertelement:
    3270             :   case lltok::kw_extractelement:
    3271             :   case lltok::kw_select: {
    3272       35786 :     unsigned Opc = Lex.getUIntVal();
    3273             :     SmallVector<Constant*, 16> Elts;
    3274             :     bool InBounds = false;
    3275             :     Type *Ty;
    3276       35786 :     Lex.Lex();
    3277             : 
    3278       35786 :     if (Opc == Instruction::GetElementPtr)
    3279             :       InBounds = EatIfPresent(lltok::kw_inbounds);
    3280             : 
    3281       35786 :     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
    3282             :       return true;
    3283             : 
    3284       35786 :     LocTy ExplicitTypeLoc = Lex.getLoc();
    3285       35786 :     if (Opc == Instruction::GetElementPtr) {
    3286       71408 :       if (ParseType(Ty) ||
    3287       35704 :           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
    3288             :         return true;
    3289             :     }
    3290             : 
    3291             :     Optional<unsigned> InRangeOp;
    3292       35786 :     if (ParseGlobalValueVector(
    3293       71571 :             Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
    3294       35785 :         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
    3295             :       return true;
    3296             : 
    3297       35785 :     if (Opc == Instruction::GetElementPtr) {
    3298       71406 :       if (Elts.size() == 0 ||
    3299       35703 :           !Elts[0]->getType()->isPtrOrPtrVectorTy())
    3300           0 :         return Error(ID.Loc, "base of getelementptr must be a pointer");
    3301             : 
    3302             :       Type *BaseType = Elts[0]->getType();
    3303             :       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
    3304       35703 :       if (Ty != BasePointerType->getElementType())
    3305           0 :         return Error(
    3306             :             ExplicitTypeLoc,
    3307             :             "explicit pointee type doesn't match operand's pointee type");
    3308             : 
    3309             :       unsigned GEPWidth =
    3310       35703 :           BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
    3311             : 
    3312       35703 :       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
    3313      178949 :       for (Constant *Val : Indices) {
    3314       71625 :         Type *ValTy = Val->getType();
    3315       71625 :         if (!ValTy->isIntOrIntVectorTy())
    3316           0 :           return Error(ID.Loc, "getelementptr index must be an integer");
    3317       71625 :         if (ValTy->isVectorTy()) {
    3318             :           unsigned ValNumEl = ValTy->getVectorNumElements();
    3319          38 :           if (GEPWidth && (ValNumEl != GEPWidth))
    3320           2 :             return Error(
    3321             :                 ID.Loc,
    3322             :                 "getelementptr vector index has a wrong number of elements");
    3323             :           // GEPWidth may have been unknown because the base is a scalar,
    3324             :           // but it is known now.
    3325             :           GEPWidth = ValNumEl;
    3326             :         }
    3327             :       }
    3328             : 
    3329             :       SmallPtrSet<Type*, 4> Visited;
    3330       35701 :       if (!Indices.empty() && !Ty->isSized(&Visited))
    3331           0 :         return Error(ID.Loc, "base element of getelementptr must be sized");
    3332             : 
    3333       35701 :       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
    3334           0 :         return Error(ID.Loc, "invalid getelementptr indices");
    3335             : 
    3336       35701 :       if (InRangeOp) {
    3337          64 :         if (*InRangeOp == 0)
    3338           0 :           return Error(ID.Loc,
    3339             :                        "inrange keyword may not appear on pointer operand");
    3340          64 :         --*InRangeOp;
    3341             :       }
    3342             : 
    3343      107103 :       ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
    3344             :                                                       InBounds, InRangeOp);
    3345          82 :     } else if (Opc == Instruction::Select) {
    3346          49 :       if (Elts.size() != 3)
    3347           0 :         return Error(ID.Loc, "expected three operands to select");
    3348          98 :       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
    3349          49 :                                                               Elts[2]))
    3350           0 :         return Error(ID.Loc, Reason);
    3351          49 :       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
    3352          33 :     } else if (Opc == Instruction::ShuffleVector) {
    3353          10 :       if (Elts.size() != 3)
    3354           0 :         return Error(ID.Loc, "expected three operands to shufflevector");
    3355          10 :       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
    3356           0 :         return Error(ID.Loc, "invalid operands to shufflevector");
    3357          10 :       ID.ConstantVal =
    3358          10 :                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
    3359          23 :     } else if (Opc == Instruction::ExtractElement) {
    3360          21 :       if (Elts.size() != 2)
    3361           0 :         return Error(ID.Loc, "expected two operands to extractelement");
    3362          21 :       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
    3363           0 :         return Error(ID.Loc, "invalid extractelement operands");
    3364          21 :       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
    3365             :     } else {
    3366             :       assert(Opc == Instruction::InsertElement && "Unknown opcode");
    3367           2 :       if (Elts.size() != 3)
    3368           0 :       return Error(ID.Loc, "expected three operands to insertelement");
    3369           2 :       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
    3370           0 :         return Error(ID.Loc, "invalid insertelement operands");
    3371           2 :       ID.ConstantVal =
    3372           2 :                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
    3373             :     }
    3374             : 
    3375       35783 :     ID.Kind = ValID::t_Constant;
    3376       35783 :     return false;
    3377             :   }
    3378             :   }
    3379             : 
    3380     2978804 :   Lex.Lex();
    3381     2978804 :   return false;
    3382             : }
    3383             : 
    3384             : /// ParseGlobalValue - Parse a global value with the specified type.
    3385      899337 : bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
    3386      899337 :   C = nullptr;
    3387     1798674 :   ValID ID;
    3388      899337 :   Value *V = nullptr;
    3389     1798657 :   bool Parsed = ParseValID(ID) ||
    3390      899320 :                 ConvertValIDToValue(Ty, ID, V, nullptr);
    3391     1798655 :   if (V && !(C = dyn_cast<Constant>(V)))
    3392           0 :     return Error(ID.Loc, "global values must be constants");
    3393             :   return Parsed;
    3394             : }
    3395             : 
    3396      880449 : bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
    3397      880449 :   Type *Ty = nullptr;
    3398     1760898 :   return ParseType(Ty) ||
    3399     1760898 :          ParseGlobalValue(Ty, V);
    3400             : }
    3401             : 
    3402      265454 : bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
    3403      265454 :   C = nullptr;
    3404             : 
    3405      265454 :   LocTy KwLoc = Lex.getLoc();
    3406             :   if (!EatIfPresent(lltok::kw_comdat))
    3407             :     return false;
    3408             : 
    3409             :   if (EatIfPresent(lltok::lparen)) {
    3410         289 :     if (Lex.getKind() != lltok::ComdatVar)
    3411           0 :       return TokError("expected comdat variable");
    3412         578 :     C = getComdat(Lex.getStrVal(), Lex.getLoc());
    3413             :     Lex.Lex();
    3414         289 :     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
    3415             :       return true;
    3416             :   } else {
    3417         405 :     if (GlobalName.empty())
    3418           1 :       return TokError("comdat cannot be unnamed");
    3419         808 :     C = getComdat(GlobalName, KwLoc);
    3420             :   }
    3421             : 
    3422             :   return false;
    3423             : }
    3424             : 
    3425             : /// ParseGlobalValueVector
    3426             : ///   ::= /*empty*/
    3427             : ///   ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
    3428       99429 : bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
    3429             :                                       Optional<unsigned> *InRangeOp) {
    3430             :   // Empty list.
    3431      198849 :   if (Lex.getKind() == lltok::rbrace ||
    3432       99404 :       Lex.getKind() == lltok::rsquare ||
    3433      198833 :       Lex.getKind() == lltok::greater ||
    3434             :       Lex.getKind() == lltok::rparen)
    3435             :     return false;
    3436             : 
    3437             :   do {
    3438      868868 :     if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
    3439          64 :       *InRangeOp = Elts.size();
    3440             : 
    3441             :     Constant *C;
    3442      868868 :     if (ParseGlobalTypeAndValue(C)) return true;
    3443      868862 :     Elts.push_back(C);
    3444             :   } while (EatIfPresent(lltok::comma));
    3445             : 
    3446             :   return false;
    3447             : }
    3448             : 
    3449       17747 : bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
    3450             :   SmallVector<Metadata *, 16> Elts;
    3451       17747 :   if (ParseMDNodeVector(Elts))
    3452             :     return true;
    3453             : 
    3454       35478 :   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
    3455       17739 :   return false;
    3456             : }
    3457             : 
    3458             : /// MDNode:
    3459             : ///  ::= !{ ... }
    3460             : ///  ::= !7
    3461             : ///  ::= !DILocation(...)
    3462       27911 : bool LLParser::ParseMDNode(MDNode *&N) {
    3463       27911 :   if (Lex.getKind() == lltok::MetadataVar)
    3464          95 :     return ParseSpecializedMDNode(N);
    3465             : 
    3466       55632 :   return ParseToken(lltok::exclaim, "expected '!' here") ||
    3467       27816 :          ParseMDNodeTail(N);
    3468             : }
    3469             : 
    3470       95089 : bool LLParser::ParseMDNodeTail(MDNode *&N) {
    3471             :   // !{ ... }
    3472       95089 :   if (Lex.getKind() == lltok::lbrace)
    3473         300 :     return ParseMDTuple(N);
    3474             : 
    3475             :   // !42
    3476       94789 :   return ParseMDNodeID(N);
    3477             : }
    3478             : 
    3479             : namespace {
    3480             : 
    3481             : /// Structure to represent an optional metadata field.
    3482             : template <class FieldTy> struct MDFieldImpl {
    3483             :   typedef MDFieldImpl ImplTy;
    3484             :   FieldTy Val;
    3485             :   bool Seen;
    3486             : 
    3487             :   void assign(FieldTy Val) {
    3488      130194 :     Seen = true;
    3489      130182 :     this->Val = std::move(Val);
    3490             :   }
    3491             : 
    3492      215885 :   explicit MDFieldImpl(FieldTy Default)
    3493      215885 :       : Val(std::move(Default)), Seen(false) {}
    3494             : };
    3495             : 
    3496             : /// Structure to represent an optional metadata field that
    3497             : /// can be of either type (A or B) and encapsulates the
    3498             : /// MD<typeofA>Field and MD<typeofB>Field structs, so not
    3499             : /// to reimplement the specifics for representing each Field.
    3500             : template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
    3501             :   typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
    3502             :   FieldTypeA A;
    3503             :   FieldTypeB B;
    3504             :   bool Seen;
    3505             : 
    3506             :   enum {
    3507             :     IsInvalid = 0,
    3508             :     IsTypeA = 1,
    3509             :     IsTypeB = 2
    3510             :   } WhatIs;
    3511             : 
    3512             :   void assign(FieldTypeA A) {
    3513         180 :     Seen = true;
    3514         180 :     this->A = std::move(A);
    3515         180 :     WhatIs = IsTypeA;
    3516             :   }
    3517             : 
    3518             :   void assign(FieldTypeB B) {
    3519        6147 :     Seen = true;
    3520        6147 :     this->B = std::move(B);
    3521        6147 :     WhatIs = IsTypeB;
    3522             :   }
    3523             : 
    3524        6332 :   explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
    3525             :       : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
    3526        6332 :         WhatIs(IsInvalid) {}
    3527             : };
    3528             : 
    3529             : struct MDUnsignedField : public MDFieldImpl<uint64_t> {
    3530             :   uint64_t Max;
    3531             : 
    3532             :   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
    3533      115426 :       : ImplTy(Default), Max(Max) {}
    3534             : };
    3535             : 
    3536             : struct LineField : public MDUnsignedField {
    3537             :   LineField() : MDUnsignedField(0, UINT32_MAX) {}
    3538             : };
    3539             : 
    3540             : struct ColumnField : public MDUnsignedField {
    3541             :   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
    3542             : };
    3543             : 
    3544             : struct DwarfTagField : public MDUnsignedField {
    3545             :   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
    3546             :   DwarfTagField(dwarf::Tag DefaultTag)
    3547             :       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
    3548             : };
    3549             : 
    3550             : struct DwarfMacinfoTypeField : public MDUnsignedField {
    3551             :   DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
    3552             :   DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
    3553             :     : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
    3554             : };
    3555             : 
    3556             : struct DwarfAttEncodingField : public MDUnsignedField {
    3557             :   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
    3558             : };
    3559             : 
    3560             : struct DwarfVirtualityField : public MDUnsignedField {
    3561             :   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
    3562             : };
    3563             : 
    3564             : struct DwarfLangField : public MDUnsignedField {
    3565             :   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
    3566             : };
    3567             : 
    3568             : struct DwarfCCField : public MDUnsignedField {
    3569             :   DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
    3570             : };
    3571             : 
    3572             : struct EmissionKindField : public MDUnsignedField {
    3573             :   EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
    3574             : };
    3575             : 
    3576             : struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
    3577             :   DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
    3578             : };
    3579             : 
    3580             : struct MDSignedField : public MDFieldImpl<int64_t> {
    3581             :   int64_t Min;
    3582             :   int64_t Max;
    3583             : 
    3584             :   MDSignedField(int64_t Default = 0)
    3585         352 :       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
    3586             :   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
    3587        5358 :       : ImplTy(Default), Min(Min), Max(Max) {}
    3588             : };
    3589             : 
    3590             : struct MDBoolField : public MDFieldImpl<bool> {
    3591             :   MDBoolField(bool Default = false) : ImplTy(Default) {}
    3592             : };
    3593             : 
    3594             : struct MDField : public MDFieldImpl<Metadata *> {
    3595             :   bool AllowNull;
    3596             : 
    3597      127267 :   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
    3598             : };
    3599             : 
    3600             : struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
    3601             :   MDConstant() : ImplTy(nullptr) {}
    3602             : };
    3603             : 
    3604             : struct MDStringField : public MDFieldImpl<MDString *> {
    3605             :   bool AllowEmpty;
    3606             :   MDStringField(bool AllowEmpty = true)
    3607       59790 :       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
    3608             : };
    3609             : 
    3610             : struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
    3611             :   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
    3612             : };
    3613             : 
    3614             : struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
    3615             :   ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
    3616             : };
    3617             : 
    3618             : struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
    3619             :   MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
    3620             :       : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
    3621             : 
    3622             :   MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
    3623             :                     bool AllowNull = true)
    3624             :       : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
    3625             : 
    3626             :   bool isMDSignedField() const { return WhatIs == IsTypeA; }
    3627             :   bool isMDField() const { return WhatIs == IsTypeB; }
    3628             :   int64_t getMDSignedValue() const {
    3629             :     assert(isMDSignedField() && "Wrong field type");
    3630             :     return A.Val;
    3631             :   }
    3632             :   Metadata *getMDFieldValue() const {
    3633             :     assert(isMDField() && "Wrong field type");
    3634             :     return B.Val;
    3635             :   }
    3636             : };
    3637             : 
    3638             : struct MDSignedOrUnsignedField
    3639             :     : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
    3640             :   MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
    3641             : 
    3642             :   bool isMDSignedField() const { return WhatIs == IsTypeA; }
    3643             :   bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
    3644             :   int64_t getMDSignedValue() const {
    3645             :     assert(isMDSignedField() && "Wrong field type");
    3646             :     return A.Val;
    3647             :   }
    3648             :   uint64_t getMDUnsignedValue() const {
    3649             :     assert(isMDUnsignedField() && "Wrong field type");
    3650             :     return B.Val;
    3651             :   }
    3652             : };
    3653             : 
    3654             : } // end anonymous namespace
    3655             : 
    3656             : namespace llvm {
    3657             : 
    3658             : template <>
    3659       40679 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3660             :                             MDUnsignedField &Result) {
    3661       40679 :   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
    3662           1 :     return TokError("expected unsigned integer");
    3663             : 
    3664             :   auto &U = Lex.getAPSIntVal();
    3665       40678 :   if (U.ugt(Result.Max))
    3666           6 :     return TokError("value for '" + Name + "' too large, limit is " +
    3667          12 :                     Twine(Result.Max));
    3668             :   Result.assign(U.getZExtValue());
    3669             :   assert(Result.Val <= Result.Max && "Expected value in range");
    3670       40672 :   Lex.Lex();
    3671             :   return false;
    3672             : }
    3673             : 
    3674             : template <>
    3675             : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
    3676       17689 :   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3677             : }
    3678             : template <>
    3679             : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
    3680        7074 :   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3681             : }
    3682             : 
    3683             : template <>
    3684        3600 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
    3685        3600 :   if (Lex.getKind() == lltok::APSInt)
    3686          22 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3687             : 
    3688        3578 :   if (Lex.getKind() != lltok::DwarfTag)
    3689           1 :     return TokError("expected DWARF tag");
    3690             : 
    3691        3577 :   unsigned Tag = dwarf::getTag(Lex.getStrVal());
    3692        3577 :   if (Tag == dwarf::DW_TAG_invalid)
    3693           1 :     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
    3694             :   assert(Tag <= Result.Max && "Expected valid DWARF tag");
    3695             : 
    3696        3576 :   Result.assign(Tag);
    3697        3576 :   Lex.Lex();
    3698             :   return false;
    3699             : }
    3700             : 
    3701             : template <>
    3702          23 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3703             :                             DwarfMacinfoTypeField &Result) {
    3704          23 :   if (Lex.getKind() == lltok::APSInt)
    3705           0 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3706             : 
    3707          23 :   if (Lex.getKind() != lltok::DwarfMacinfo)
    3708           0 :     return TokError("expected DWARF macinfo type");
    3709             : 
    3710          23 :   unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
    3711          23 :   if (Macinfo == dwarf::DW_MACINFO_invalid)
    3712             :     return TokError(
    3713           0 :         "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
    3714             :   assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
    3715             : 
    3716          23 :   Result.assign(Macinfo);
    3717          23 :   Lex.Lex();
    3718             :   return false;
    3719             : }
    3720             : 
    3721             : template <>
    3722          57 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3723             :                             DwarfVirtualityField &Result) {
    3724          57 :   if (Lex.getKind() == lltok::APSInt)
    3725           0 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3726             : 
    3727          57 :   if (Lex.getKind() != lltok::DwarfVirtuality)
    3728           0 :     return TokError("expected DWARF virtuality code");
    3729             : 
    3730          57 :   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
    3731          57 :   if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
    3732           0 :     return TokError("invalid DWARF virtuality code" + Twine(" '") +
    3733           0 :                     Lex.getStrVal() + "'");
    3734             :   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
    3735          57 :   Result.assign(Virtuality);
    3736          57 :   Lex.Lex();
    3737             :   return false;
    3738             : }
    3739             : 
    3740             : template <>
    3741        1586 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
    3742        1586 :   if (Lex.getKind() == lltok::APSInt)
    3743          14 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3744             : 
    3745        1572 :   if (Lex.getKind() != lltok::DwarfLang)
    3746           0 :     return TokError("expected DWARF language");
    3747             : 
    3748        1572 :   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
    3749        1572 :   if (!Lang)
    3750           1 :     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
    3751           1 :                     "'");
    3752             :   assert(Lang <= Result.Max && "Expected valid DWARF language");
    3753        1571 :   Result.assign(Lang);
    3754        1571 :   Lex.Lex();
    3755             :   return false;
    3756             : }
    3757             : 
    3758             : template <>
    3759          60 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
    3760          60 :   if (Lex.getKind() == lltok::APSInt)
    3761           0 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3762             : 
    3763          60 :   if (Lex.getKind() != lltok::DwarfCC)
    3764           0 :     return TokError("expected DWARF calling convention");
    3765             : 
    3766          60 :   unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
    3767          60 :   if (!CC)
    3768           0 :     return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
    3769           0 :                     "'");
    3770             :   assert(CC <= Result.Max && "Expected valid DWARF calling convention");
    3771          60 :   Result.assign(CC);
    3772          60 :   Lex.Lex();
    3773             :   return false;
    3774             : }
    3775             : 
    3776             : template <>
    3777        1483 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
    3778        1483 :   if (Lex.getKind() == lltok::APSInt)
    3779          78 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3780             : 
    3781        1405 :   if (Lex.getKind() != lltok::EmissionKind)
    3782           0 :     return TokError("expected emission kind");
    3783             : 
    3784        1405 :   auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
    3785        1405 :   if (!Kind)
    3786           0 :     return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
    3787           0 :                     "'");
    3788             :   assert(*Kind <= Result.Max && "Expected valid emission kind");
    3789        1405 :   Result.assign(*Kind);
    3790        1405 :   Lex.Lex();
    3791             :   return false;
    3792             : }
    3793             :   
    3794             : template <>
    3795        1305 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3796             :                             DwarfAttEncodingField &Result) {
    3797        1305 :   if (Lex.getKind() == lltok::APSInt)
    3798           3 :     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
    3799             : 
    3800        1302 :   if (Lex.getKind() != lltok::DwarfAttEncoding)
    3801           0 :     return TokError("expected DWARF type attribute encoding");
    3802             : 
    3803        1302 :   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
    3804        1302 :   if (!Encoding)
    3805           0 :     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
    3806           0 :                     Lex.getStrVal() + "'");
    3807             :   assert(Encoding <= Result.Max && "Expected valid DWARF language");
    3808        1302 :   Result.assign(Encoding);
    3809        1302 :   Lex.Lex();
    3810             :   return false;
    3811             : }
    3812             : 
    3813             : /// DIFlagField
    3814             : ///  ::= uint32
    3815             : ///  ::= DIFlagVector
    3816             : ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
    3817             : template <>
    3818        2682 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
    3819             : 
    3820             :   // Parser for a single flag.
    3821        3165 :   auto parseFlag = [&](DINode::DIFlags &Val) {
    3822        6328 :     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
    3823           2 :       uint32_t TempVal = static_cast<uint32_t>(Val);
    3824           2 :       bool Res = ParseUInt32(TempVal);
    3825           2 :       Val = static_cast<DINode::DIFlags>(TempVal);
    3826             :       return Res;
    3827             :     }
    3828             : 
    3829        3163 :     if (Lex.getKind() != lltok::DIFlag)
    3830           0 :       return TokError("expected debug info flag");
    3831             : 
    3832        3163 :     Val = DINode::getFlag(Lex.getStrVal());
    3833        3163 :     if (!Val)
    3834           0 :       return TokError(Twine("invalid debug info flag flag '") +
    3835           0 :                       Lex.getStrVal() + "'");
    3836        3163 :     Lex.Lex();
    3837        3163 :     return false;
    3838        2682 :   };
    3839             : 
    3840             :   // Parse the flags and combine them together.
    3841             :   DINode::DIFlags Combined = DINode::FlagZero;
    3842             :   do {
    3843             :     DINode::DIFlags Val;
    3844        3165 :     if (parseFlag(Val))
    3845           0 :       return true;
    3846        3165 :     Combined |= Val;
    3847             :   } while (EatIfPresent(lltok::bar));
    3848             : 
    3849             :   Result.assign(Combined);
    3850             :   return false;
    3851             : }
    3852             : 
    3853             : template <>
    3854         232 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3855             :                             MDSignedField &Result) {
    3856         232 :   if (Lex.getKind() != lltok::APSInt)
    3857           0 :     return TokError("expected signed integer");
    3858             : 
    3859             :   auto &S = Lex.getAPSIntVal();
    3860         232 :   if (S < Result.Min)
    3861           2 :     return TokError("value for '" + Name + "' too small, limit is " +
    3862           4 :                     Twine(Result.Min));
    3863         230 :   if (S > Result.Max)
    3864           2 :     return TokError("value for '" + Name + "' too large, limit is " +
    3865           4 :                     Twine(Result.Max));
    3866             :   Result.assign(S.getExtValue());
    3867             :   assert(Result.Val >= Result.Min && "Expected value in range");
    3868             :   assert(Result.Val <= Result.Max && "Expected value in range");
    3869         228 :   Lex.Lex();
    3870             :   return false;
    3871             : }
    3872             : 
    3873             : template <>
    3874       10414 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
    3875       10414 :   switch (Lex.getKind()) {
    3876             :   default:
    3877           0 :     return TokError("expected 'true' or 'false'");
    3878        4821 :   case lltok::kw_true:
    3879             :     Result.assign(true);
    3880             :     break;
    3881        5593 :   case lltok::kw_false:
    3882             :     Result.assign(false);
    3883             :     break;
    3884             :   }
    3885       10414 :   Lex.Lex();
    3886             :   return false;
    3887             : }
    3888             : 
    3889             : template <>
    3890       45347 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
    3891       45347 :   if (Lex.getKind() == lltok::kw_null) {
    3892         643 :     if (!Result.AllowNull)
    3893           6 :       return TokError("'" + Name + "' cannot be null");
    3894         637 :     Lex.Lex();
    3895             :     Result.assign(nullptr);
    3896             :     return false;
    3897             :   }
    3898             : 
    3899             :   Metadata *MD;
    3900       44704 :   if (ParseMetadata(MD, nullptr))
    3901             :     return true;
    3902             : 
    3903       44704 :   Result.assign(MD);
    3904             :   return false;
    3905             : }
    3906             : 
    3907             : template <>
    3908         175 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3909             :                             MDSignedOrMDField &Result) {
    3910             :   // Try to parse a signed int.
    3911         175 :   if (Lex.getKind() == lltok::APSInt) {
    3912         156 :     MDSignedField Res = Result.A;
    3913         156 :     if (!ParseMDField(Loc, Name, Res)) {
    3914             :       Result.assign(Res);
    3915             :       return false;
    3916             :     }
    3917             :     return true;
    3918             :   }
    3919             : 
    3920             :   // Otherwise, try to parse as an MDField.
    3921          19 :   MDField Res = Result.B;
    3922          19 :   if (!ParseMDField(Loc, Name, Res)) {
    3923             :     Result.assign(Res);
    3924             :     return false;
    3925             :   }
    3926             : 
    3927             :   return true;
    3928             : }
    3929             : 
    3930             : template <>
    3931        6155 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3932             :                             MDSignedOrUnsignedField &Result) {
    3933        6155 :   if (Lex.getKind() != lltok::APSInt)
    3934             :     return false;
    3935             : 
    3936        6155 :   if (Lex.getAPSIntVal().isSigned()) {
    3937          26 :     MDSignedField Res = Result.A;
    3938          26 :     if (ParseMDField(Loc, Name, Res))
    3939             :       return true;
    3940             :     Result.assign(Res);
    3941             :     return false;
    3942             :   }
    3943             : 
    3944        6129 :   MDUnsignedField Res = Result.B;
    3945        6129 :   if (ParseMDField(Loc, Name, Res))
    3946             :     return true;
    3947             :   Result.assign(Res);
    3948             :   return false;
    3949             : }
    3950             : 
    3951             : template <>
    3952       22740 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
    3953       22740 :   LocTy ValueLoc = Lex.getLoc();
    3954             :   std::string S;
    3955       22740 :   if (ParseStringConstant(S))
    3956             :     return true;
    3957             : 
    3958       23388 :   if (!Result.AllowEmpty && S.empty())
    3959           1 :     return Error(ValueLoc, "'" + Name + "' cannot be empty");
    3960             : 
    3961       67871 :   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
    3962             :   return false;
    3963             : }
    3964             : 
    3965             : template <>
    3966          12 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
    3967             :   SmallVector<Metadata *, 4> MDs;
    3968          12 :   if (ParseMDNodeVector(MDs))
    3969             :     return true;
    3970             : 
    3971          12 :   Result.assign(std::move(MDs));
    3972             :   return false;
    3973             : }
    3974             : 
    3975             : template <>
    3976         112 : bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
    3977             :                             ChecksumKindField &Result) {
    3978             :   Optional<DIFile::ChecksumKind> CSKind =
    3979         112 :       DIFile::getChecksumKind(Lex.getStrVal());
    3980             : 
    3981         112 :   if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
    3982             :     return TokError(
    3983           0 :         "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
    3984             : 
    3985         112 :   Result.assign(*CSKind);
    3986         112 :   Lex.Lex();
    3987             :   return false;
    3988             : }
    3989             : 
    3990             : } // end namespace llvm
    3991             : 
    3992             : template <class ParserTy>
    3993       32091 : bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
    3994             :   do {
    3995      130217 :     if (Lex.getKind() != lltok::LabelStr)
    3996           0 :       return TokError("expected field label here");
    3997             : 
    3998      130217 :     if (parseField())
    3999             :       return true;
    4000             :   } while (EatIfPresent(lltok::comma));
    4001             : 
    4002             :   return false;
    4003             : }
    4004             : 
    4005             : template <class ParserTy>
    4006       32118 : bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
    4007             :   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
    4008       32118 :   Lex.Lex();
    4009             : 
    4010       32118 :   if (ParseToken(lltok::lparen, "expected '(' here"))
    4011             :     return true;
    4012       32118 :   if (Lex.getKind() != lltok::rparen)
    4013       32091 :     if (ParseMDFieldsImplBody(parseField))
    4014             :       return true;
    4015             : 
    4016       32095 :   ClosingLoc = Lex.getLoc();
    4017       32095 :   return ParseToken(lltok::rparen, "expected ')' here");
    4018             : }
    4019             : 
    4020             : template <class FieldTy>
    4021      130216 : bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
    4022      130216 :   if (Result.Seen)
    4023           1 :     return TokError("field '" + Name + "' cannot be specified more than once");
    4024             : 
    4025             :   LocTy Loc = Lex.getLoc();
    4026      130215 :   Lex.Lex();
    4027      130215 :   return ParseMDField(Loc, Name, Result);
    4028             : }
    4029             : 
    4030       34289 : bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
    4031             :   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
    4032             : 
    4033             : #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
    4034             :   if (Lex.getStrVal() == #CLASS)                                               \
    4035             :     return Parse##CLASS(N, IsDistinct);
    4036             : #include "llvm/IR/Metadata.def"
    4037             : 
    4038           1 :   return TokError("expected metadata type");
    4039             : }
    4040             : 
    4041             : #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
    4042             : #define NOP_FIELD(NAME, TYPE, INIT)
    4043             : #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
    4044             :   if (!NAME.Seen)                                                              \
    4045             :     return Error(ClosingLoc, "missing required field '" #NAME "'");
    4046             : #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
    4047             :   if (Lex.getStrVal() == #NAME)                                                \
    4048             :     return ParseMDField(#NAME, NAME);
    4049             : #define PARSE_MD_FIELDS()                                                      \
    4050             :   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
    4051             :   do {                                                                         \
    4052             :     LocTy ClosingLoc;                                                          \
    4053             :     if (ParseMDFieldsImpl([&]() -> bool {                                      \
    4054             :       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
    4055             :       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
    4056             :     }, ClosingLoc))                                                            \
    4057             :       return true;                                                             \
    4058             :     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
    4059             :   } while (false)
    4060             : #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
    4061             :   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
    4062             : 
    4063             : /// ParseDILocationFields:
    4064             : ///   ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
    4065        7995 : bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
    4066             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4067             :   OPTIONAL(line, LineField, );                                                 \
    4068             :   OPTIONAL(column, ColumnField, );                                             \
    4069             :   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
    4070             :   OPTIONAL(inlinedAt, MDField, );
    4071       98844 :   PARSE_MD_FIELDS();
    4072             : #undef VISIT_MD_FIELDS
    4073             : 
    4074       23964 :   Result = GET_OR_DISTINCT(
    4075             :       DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
    4076        7988 :   return false;
    4077             : }
    4078             : 
    4079             : /// ParseGenericDINode:
    4080             : ///   ::= !GenericDINode(tag: 15, header: "...", operands: {...})
    4081          39 : bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
    4082             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4083             :   REQUIRED(tag, DwarfTagField, );                                              \
    4084             :   OPTIONAL(header, MDStringField, );                                           \
    4085             :   OPTIONAL(operands, MDFieldList, );
    4086         270 :   PARSE_MD_FIELDS();
    4087             : #undef VISIT_MD_FIELDS
    4088             : 
    4089         105 :   Result = GET_OR_DISTINCT(GenericDINode,
    4090             :                            (Context, tag.Val, header.Val, operands.Val));
    4091          35 :   return false;
    4092             : }
    4093             : 
    4094             : /// ParseDISubrange:
    4095             : ///   ::= !DISubrange(count: 30, lowerBound: 2)
    4096             : ///   ::= !DISubrange(count: !node, lowerBound: 2)
    4097         176 : bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
    4098             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4099             :   REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false));              \
    4100             :   OPTIONAL(lowerBound, MDSignedField, );
    4101         864 :   PARSE_MD_FIELDS();
    4102             : #undef VISIT_MD_FIELDS
    4103             : 
    4104         170 :   if (count.isMDSignedField())
    4105         456 :     Result = GET_OR_DISTINCT(
    4106             :         DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
    4107          18 :   else if (count.isMDField())
    4108          54 :     Result = GET_OR_DISTINCT(
    4109             :         DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
    4110             :   else
    4111             :     return true;
    4112             : 
    4113             :   return false;
    4114             : }
    4115             : 
    4116             : /// ParseDIEnumerator:
    4117             : ///   ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
    4118        6156 : bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
    4119             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4120             :   REQUIRED(name, MDStringField, );                                             \
    4121             :   REQUIRED(value, MDSignedOrUnsignedField, );                                  \
    4122             :   OPTIONAL(isUnsigned, MDBoolField, (false));
    4123       49295 :   PARSE_MD_FIELDS();
    4124             : #undef VISIT_MD_FIELDS
    4125             : 
    4126        6164 :   if (isUnsigned.Val && value.isMDSignedField())
    4127           0 :     return TokError("unsigned enumerator with negative value");
    4128             : 
    4129        6154 :   int64_t Value = value.isMDSignedField()
    4130       12282 :                       ? value.getMDSignedValue()
    4131        6128 :                       : static_cast<int64_t>(value.getMDUnsignedValue());
    4132       12308 :   Result =
    4133        6154 :       GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
    4134             : 
    4135        6154 :   return false;
    4136             : }
    4137             : 
    4138             : /// ParseDIBasicType:
    4139             : ///   ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
    4140        1325 : bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
    4141             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4142             :   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
    4143             :   OPTIONAL(name, MDStringField, );                                             \
    4144             :   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
    4145             :   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
    4146             :   OPTIONAL(encoding, DwarfAttEncodingField, );
    4147       28974 :   PARSE_MD_FIELDS();
    4148             : #undef VISIT_MD_FIELDS
    4149             : 
    4150        3975 :   Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
    4151             :                                          align.Val, encoding.Val));
    4152        1325 :   return false;
    4153             : }
    4154             : 
    4155             : /// ParseDIDerivedType:
    4156             : ///   ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
    4157             : ///                      line: 7, scope: !1, baseType: !2, size: 32,
    4158             : ///                      align: 32, offset: 0, flags: 0, extraData: !3,
    4159             : ///                      dwarfAddressSpace: 3)
    4160        1925 : bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
    4161             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4162             :   REQUIRED(tag, DwarfTagField, );                                              \
    4163             :   OPTIONAL(name, MDStringField, );                                             \
    4164             :   OPTIONAL(file, MDField, );                                                   \
    4165             :   OPTIONAL(line, LineField, );                                                 \
    4166             :   OPTIONAL(scope, MDField, );                                                  \
    4167             :   REQUIRED(baseType, MDField, );                                               \
    4168             :   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
    4169             :   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
    4170             :   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
    4171             :   OPTIONAL(flags, DIFlagField, );                                              \
    4172             :   OPTIONAL(extraData, MDField, );                                              \
    4173             :   OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
    4174       74666 :   PARSE_MD_FIELDS();
    4175             : #undef VISIT_MD_FIELDS
    4176             : 
    4177             :   Optional<unsigned> DWARFAddressSpace;
    4178        1923 :   if (dwarfAddressSpace.Val != UINT32_MAX)
    4179          21 :     DWARFAddressSpace = dwarfAddressSpace.Val;
    4180             : 
    4181        7692 :   Result = GET_OR_DISTINCT(DIDerivedType,
    4182             :                            (Context, tag.Val, name.Val, file.Val, line.Val,
    4183             :                             scope.Val, baseType.Val, size.Val, align.Val,
    4184             :                             offset.Val, DWARFAddressSpace, flags.Val,
    4185             :                             extraData.Val));
    4186             :   return false;
    4187             : }
    4188             : 
    4189         916 : bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
    4190             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4191             :   REQUIRED(tag, DwarfTagField, );                                              \
    4192             :   OPTIONAL(name, MDStringField, );                                             \
    4193             :   OPTIONAL(file, MDField, );                                                   \
    4194             :   OPTIONAL(line, LineField, );                                                 \
    4195             :   OPTIONAL(scope, MDField, );                                                  \
    4196             :   OPTIONAL(baseType, MDField, );                                               \
    4197             :   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
    4198             :   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));                           \
    4199             :   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
    4200             :   OPTIONAL(flags, DIFlagField, );                                              \
    4201             :   OPTIONAL(elements, MDField, );                                               \
    4202             :   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
    4203             :   OPTIONAL(vtableHolder, MDField, );                                           \
    4204             :   OPTIONAL(templateParams, MDField, );                                         \
    4205             :   OPTIONAL(identifier, MDStringField, );                                       \
    4206             :   OPTIONAL(discriminator, MDField, );
    4207       48731 :   PARSE_MD_FIELDS();
    4208             : #undef VISIT_MD_FIELDS
    4209             : 
    4210             :   // If this has an identifier try to build an ODR type.
    4211         915 :   if (identifier.Val)
    4212        2520 :     if (auto *CT = DICompositeType::buildODRType(
    4213         840 :             Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
    4214         420 :             scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
    4215         420 :             elements.Val, runtimeLang.Val, vtableHolder.Val,
    4216         420 :             templateParams.Val, discriminator.Val)) {
    4217          80 :       Result = CT;
    4218          80 :       return false;
    4219             :     }
    4220             : 
    4221             :   // Create a new node, and save it in the context if it belongs in the type
    4222             :   // map.
    4223        2285 :   Result = GET_OR_DISTINCT(
    4224             :       DICompositeType,
    4225             :       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
    4226             :        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
    4227             :        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
    4228             :        discriminator.Val));
    4229         835 :   return false;
    4230             : }
    4231             : 
    4232        1751 : bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
    4233             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4234             :   OPTIONAL(flags, DIFlagField, );                                              \
    4235             :   OPTIONAL(cc, DwarfCCField, );                                                \
    4236             :   REQUIRED(types, MDField, );
    4237       10806 :   PARSE_MD_FIELDS();
    4238             : #undef VISIT_MD_FIELDS
    4239             : 
    4240        5250 :   Result = GET_OR_DISTINCT(DISubroutineType,
    4241             :                            (Context, flags.Val, cc.Val, types.Val));
    4242        1750 :   return false;
    4243             : }
    4244             : 
    4245             : /// ParseDIFileType:
    4246             : ///   ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir"
    4247             : ///                   checksumkind: CSK_MD5,
    4248             : ///                   checksum: "000102030405060708090a0b0c0d0e0f")
    4249        2368 : bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
    4250             :   // The default constructed value for checksumkind is required, but will never
    4251             :   // be used, as the parser checks if the field was actually Seen before using
    4252             :   // the Val.
    4253             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4254             :   REQUIRED(filename, MDStringField, );                                         \
    4255             :   REQUIRED(directory, MDStringField, );                                        \
    4256             :   OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5));                \
    4257             :   OPTIONAL(checksum, MDStringField, );
    4258       20173 :   PARSE_MD_FIELDS();
    4259             : #undef VISIT_MD_FIELDS
    4260             : 
    4261             :   Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
    4262        2478 :   if (checksumkind.Seen && checksum.Seen)
    4263             :     OptChecksum.emplace(checksumkind.Val, checksum.Val);
    4264        2254 :   else if (checksumkind.Seen || checksum.Seen)
    4265           0 :     return Lex.Error("'checksumkind' and 'checksum' must be provided together");
    4266             : 
    4267        4732 :   Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
    4268             :                                     OptChecksum));
    4269        2366 :   return false;
    4270             : }
    4271             : 
    4272             : /// ParseDICompileUnit:
    4273             : ///   ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
    4274             : ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
    4275             : ///                      splitDebugFilename: "abc.debug",
    4276             : ///                      emissionKind: FullDebug, enums: !1, retainedTypes: !2,
    4277             : ///                      globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
    4278        1548 : bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
    4279        1548 :   if (!IsDistinct)
    4280           2 :     return Lex.Error("missing 'distinct', required for !DICompileUnit");
    4281             : 
    4282             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4283             :   REQUIRED(language, DwarfLangField, );                                        \
    4284             :   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
    4285             :   OPTIONAL(producer, MDStringField, );                                         \
    4286             :   OPTIONAL(isOptimized, MDBoolField, );                                        \
    4287             :   OPTIONAL(flags, MDStringField, );                                            \
    4288             :   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
    4289             :   OPTIONAL(splitDebugFilename, MDStringField, );                               \
    4290             :   OPTIONAL(emissionKind, EmissionKindField, );                                 \
    4291             :   OPTIONAL(enums, MDField, );                                                  \
    4292             :   OPTIONAL(retainedTypes, MDField, );                                          \
    4293             :   OPTIONAL(globals, MDField, );                                                \
    4294             :   OPTIONAL(imports, MDField, );                                                \
    4295             :   OPTIONAL(macros, MDField, );                                                 \
    4296             :   OPTIONAL(dwoId, MDUnsignedField, );                                          \
    4297             :   OPTIONAL(splitDebugInlining, MDBoolField, = true);                           \
    4298             :   OPTIONAL(debugInfoForProfiling, MDBoolField, = false);                       \
    4299             :   OPTIONAL(gnuPubnames, MDBoolField, = false);
    4300       92388 :   PARSE_MD_FIELDS();
    4301             : #undef VISIT_MD_FIELDS
    4302             : 
    4303       12336 :   Result = DICompileUnit::getDistinct(
    4304        3084 :       Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
    4305        3084 :       runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
    4306             :       retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
    4307        4626 :       splitDebugInlining.Val, debugInfoForProfiling.Val, gnuPubnames.Val);
    4308        1542 :   return false;
    4309             : }
    4310             : 
    4311             : /// ParseDISubprogram:
    4312             : ///   ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
    4313             : ///                     file: !1, line: 7, type: !2, isLocal: false,
    4314             : ///                     isDefinition: true, scopeLine: 8, containingType: !3,
    4315             : ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
    4316             : ///                     virtualIndex: 10, thisAdjustment: 4, flags: 11,
    4317             : ///                     isOptimized: false, templateParams: !4, declaration: !5,
    4318             : ///                     variables: !6, thrownTypes: !7)
    4319        2679 : bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
    4320        2679 :   auto Loc = Lex.getLoc();
    4321             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4322             :   OPTIONAL(scope, MDField, );                                                  \
    4323             :   OPTIONAL(name, MDStringField, );                                             \
    4324             :   OPTIONAL(linkageName, MDStringField, );                                      \
    4325             :   OPTIONAL(file, MDField, );                                                   \
    4326             :   OPTIONAL(line, LineField, );                                                 \
    4327             :   OPTIONAL(type, MDField, );                                                   \
    4328             :   OPTIONAL(isLocal, MDBoolField, );                                            \
    4329             :   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
    4330             :   OPTIONAL(scopeLine, LineField, );                                            \
    4331             :   OPTIONAL(containingType, MDField, );                                         \
    4332             :   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
    4333             :   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
    4334             :   OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX));          \
    4335             :   OPTIONAL(flags, DIFlagField, );                                              \
    4336             :   OPTIONAL(isOptimized, MDBoolField, );                                        \
    4337             :   OPTIONAL(unit, MDField, );                                                   \
    4338             :   OPTIONAL(templateParams, MDField, );                                         \
    4339             :   OPTIONAL(declaration, MDField, );                                            \
    4340             :   OPTIONAL(variables, MDField, );                                              \
    4341             :   OPTIONAL(thrownTypes, MDField, );
    4342      317048 :   PARSE_MD_FIELDS();
    4343             : #undef VISIT_MD_FIELDS
    4344             : 
    4345        2679 :   if (isDefinition.Val && !IsDistinct)
    4346           2 :     return Lex.Error(
    4347             :         Loc,
    4348           1 :         "missing 'distinct', required for !DISubprogram when 'isDefinition'");
    4349             : 
    4350        5969 :   Result = GET_OR_DISTINCT(
    4351             :       DISubprogram,
    4352             :       (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
    4353             :        type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
    4354             :        containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
    4355             :        flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
    4356             :        declaration.Val, variables.Val, thrownTypes.Val));
    4357        2678 :   return false;
    4358             : }
    4359             : 
    4360             : /// ParseDILexicalBlock:
    4361             : ///   ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
    4362        1032 : bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
    4363             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4364             :   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
    4365             :   OPTIONAL(file, MDField, );                                                   \
    4366             :   OPTIONAL(line, LineField, );                                                 \
    4367             :   OPTIONAL(column, ColumnField, );
    4368       19166 :   PARSE_MD_FIELDS();
    4369             : #undef VISIT_MD_FIELDS
    4370             : 
    4371        3090 :   Result = GET_OR_DISTINCT(
    4372             :       DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
    4373        1030 :   return false;
    4374             : }
    4375             : 
    4376             : /// ParseDILexicalBlockFile:
    4377             : ///   ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
    4378         233 : bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
    4379             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4380             :   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
    4381             :   OPTIONAL(file, MDField, );                                                   \
    4382             :   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
    4383        2981 :   PARSE_MD_FIELDS();
    4384             : #undef VISIT_MD_FIELDS
    4385             : 
    4386         690 :   Result = GET_OR_DISTINCT(DILexicalBlockFile,
    4387             :                            (Context, scope.Val, file.Val, discriminator.Val));
    4388         230 :   return false;
    4389             : }
    4390             : 
    4391             : /// ParseDINamespace:
    4392             : ///   ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
    4393          94 : bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
    4394             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4395             :   REQUIRED(scope, MDField, );                                                  \
    4396             :   OPTIONAL(name, MDStringField, );                                             \
    4397             :   OPTIONAL(exportSymbols, MDBoolField, );
    4398         721 :   PARSE_MD_FIELDS();
    4399             : #undef VISIT_MD_FIELDS
    4400             : 
    4401         279 :   Result = GET_OR_DISTINCT(DINamespace,
    4402             :                            (Context, scope.Val, name.Val, exportSymbols.Val));
    4403          93 :   return false;
    4404             : }
    4405             : 
    4406             : /// ParseDIMacro:
    4407             : ///   ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
    4408          21 : bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
    4409             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4410             :   REQUIRED(type, DwarfMacinfoTypeField, );                                     \
    4411             :   OPTIONAL(line, LineField, );                                                 \
    4412             :   REQUIRED(name, MDStringField, );                                             \
    4413             :   OPTIONAL(value, MDStringField, );
    4414         367 :   PARSE_MD_FIELDS();
    4415             : #undef VISIT_MD_FIELDS
    4416             : 
    4417          63 :   Result = GET_OR_DISTINCT(DIMacro,
    4418             :                            (Context, type.Val, line.Val, name.Val, value.Val));
    4419          21 :   return false;
    4420             : }
    4421             : 
    4422             : /// ParseDIMacroFile:
    4423             : ///   ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
    4424          27 : bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
    4425             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4426             :   OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file));       \
    4427             :   OPTIONAL(line, LineField, );                                                 \
    4428             :   REQUIRED(file, MDField, );                                                   \
    4429             :   OPTIONAL(nodes, MDField, );
    4430         372 :   PARSE_MD_FIELDS();
    4431             : #undef VISIT_MD_FIELDS
    4432             : 
    4433          81 :   Result = GET_OR_DISTINCT(DIMacroFile,
    4434             :                            (Context, type.Val, line.Val, file.Val, nodes.Val));
    4435          27 :   return false;
    4436             : }
    4437             : 
    4438             : /// ParseDIModule:
    4439             : ///   ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
    4440             : ///                 includePath: "/usr/include", isysroot: "/")
    4441          21 : bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
    4442             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4443             :   REQUIRED(scope, MDField, );                                                  \
    4444             :   REQUIRED(name, MDStringField, );                                             \
    4445             :   OPTIONAL(configMacros, MDStringField, );                                     \
    4446             :   OPTIONAL(includePath, MDStringField, );                                      \
    4447             :   OPTIONAL(isysroot, MDStringField, );
    4448         367 :   PARSE_MD_FIELDS();
    4449             : #undef VISIT_MD_FIELDS
    4450             : 
    4451          63 :   Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
    4452             :                            configMacros.Val, includePath.Val, isysroot.Val));
    4453          21 :   return false;
    4454             : }
    4455             : 
    4456             : /// ParseDITemplateTypeParameter:
    4457             : ///   ::= !DITemplateTypeParameter(name: "Ty", type: !1)
    4458          54 : bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
    4459             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4460             :   OPTIONAL(name, MDStringField, );                                             \
    4461             :   REQUIRED(type, MDField, );
    4462         364 :   PARSE_MD_FIELDS();
    4463             : #undef VISIT_MD_FIELDS
    4464             : 
    4465         106 :   Result =
    4466          53 :       GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
    4467          53 :   return false;
    4468             : }
    4469             : 
    4470             : /// ParseDITemplateValueParameter:
    4471             : ///   ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
    4472             : ///                                 name: "V", type: !1, value: i32 7)
    4473          56 : bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
    4474             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4475             :   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
    4476             :   OPTIONAL(name, MDStringField, );                                             \
    4477             :   OPTIONAL(type, MDField, );                                                   \
    4478             :   REQUIRED(value, MDField, );
    4479         859 :   PARSE_MD_FIELDS();
    4480             : #undef VISIT_MD_FIELDS
    4481             : 
    4482         165 :   Result = GET_OR_DISTINCT(DITemplateValueParameter,
    4483             :                            (Context, tag.Val, name.Val, type.Val, value.Val));
    4484          55 :   return false;
    4485             : }
    4486             : 
    4487             : /// ParseDIGlobalVariable:
    4488             : ///   ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
    4489             : ///                         file: !1, line: 7, type: !2, isLocal: false,
    4490             : ///                         isDefinition: true, declaration: !3, align: 8)
    4491         649 : bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
    4492             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4493             :   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
    4494             :   OPTIONAL(scope, MDField, );                                                  \
    4495             :   OPTIONAL(linkageName, MDStringField, );                                      \
    4496             :   OPTIONAL(file, MDField, );                                                   \
    4497             :   OPTIONAL(line, LineField, );                                                 \
    4498             :   OPTIONAL(type, MDField, );                                                   \
    4499             :   OPTIONAL(isLocal, MDBoolField, );                                            \
    4500             :   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
    4501             :   OPTIONAL(declaration, MDField, );                                            \
    4502             :   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
    4503       31876 :   PARSE_MD_FIELDS();
    4504             : #undef VISIT_MD_FIELDS
    4505             : 
    4506        1941 :   Result = GET_OR_DISTINCT(DIGlobalVariable,
    4507             :                            (Context, scope.Val, name.Val, linkageName.Val,
    4508             :                             file.Val, line.Val, type.Val, isLocal.Val,
    4509             :                             isDefinition.Val, declaration.Val, align.Val));
    4510         647 :   return false;
    4511             : }
    4512             : 
    4513             : /// ParseDILocalVariable:
    4514             : ///   ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
    4515             : ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
    4516             : ///                        align: 8)
    4517             : ///   ::= !DILocalVariable(scope: !0, name: "foo",
    4518             : ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7,
    4519             : ///                        align: 8)
    4520        2137 : bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
    4521             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4522             :   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
    4523             :   OPTIONAL(name, MDStringField, );                                             \
    4524             :   OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX));                             \
    4525             :   OPTIONAL(file, MDField, );                                                   \
    4526             :   OPTIONAL(line, LineField, );                                                 \
    4527             :   OPTIONAL(type, MDField, );                                                   \
    4528             :   OPTIONAL(flags, DIFlagField, );                                              \
    4529             :   OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
    4530       65835 :   PARSE_MD_FIELDS();
    4531             : #undef VISIT_MD_FIELDS
    4532             : 
    4533        6399 :   Result = GET_OR_DISTINCT(DILocalVariable,
    4534             :                            (Context, scope.Val, name.Val, file.Val, line.Val,
    4535             :                             type.Val, arg.Val, flags.Val, align.Val));
    4536        2133 :   return false;
    4537             : }
    4538             : 
    4539             : /// ParseDIExpression:
    4540             : ///   ::= !DIExpression(0, 7, -1)
    4541        2209 : bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
    4542             :   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
    4543        2209 :   Lex.Lex();
    4544             : 
    4545        2209 :   if (ParseToken(lltok::lparen, "expected '(' here"))
    4546             :     return true;
    4547             : 
    4548             :   SmallVector<uint64_t, 8> Elements;
    4549        2209 :   if (Lex.getKind() != lltok::rparen)
    4550             :     do {
    4551         625 :       if (Lex.getKind() == lltok::DwarfOp) {
    4552         720 :         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
    4553             :           Lex.Lex();
    4554         360 :           Elements.push_back(Op);
    4555         360 :           continue;
    4556             :         }
    4557           0 :         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
    4558             :       }
    4559             : 
    4560         265 :       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
    4561           0 :         return TokError("expected unsigned integer");
    4562             : 
    4563             :       auto &U = Lex.getAPSIntVal();
    4564         265 :       if (U.ugt(UINT64_MAX))
    4565           2 :         return TokError("element too large, limit is " + Twine(UINT64_MAX));
    4566         264 :       Elements.push_back(U.getZExtValue());
    4567             :       Lex.Lex();
    4568             :     } while (EatIfPresent(lltok::comma));
    4569             : 
    4570        2208 :   if (ParseToken(lltok::rparen, "expected ')' here"))
    4571             :     return true;
    4572             : 
    4573        6624 :   Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
    4574        2208 :   return false;
    4575             : }
    4576             : 
    4577             : /// ParseDIGlobalVariableExpression:
    4578             : ///   ::= !DIGlobalVariableExpression(var: !0, expr: !1)
    4579         633 : bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
    4580             :                                                bool IsDistinct) {
    4581             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4582             :   REQUIRED(var, MDField, );                                                    \
    4583             :   REQUIRED(expr, MDField, );
    4584        5064 :   PARSE_MD_FIELDS();
    4585             : #undef VISIT_MD_FIELDS
    4586             : 
    4587        1266 :   Result =
    4588         633 :       GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
    4589         633 :   return false;
    4590             : }
    4591             : 
    4592             : /// ParseDIObjCProperty:
    4593             : ///   ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
    4594             : ///                       getter: "getFoo", attributes: 7, type: !2)
    4595          21 : bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
    4596             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4597             :   OPTIONAL(name, MDStringField, );                                             \
    4598             :   OPTIONAL(file, MDField, );                                                   \
    4599             :   OPTIONAL(line, LineField, );                                                 \
    4600             :   OPTIONAL(setter, MDStringField, );                                           \
    4601             :   OPTIONAL(getter, MDStringField, );                                           \
    4602             :   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
    4603             :   OPTIONAL(type, MDField, );
    4604         467 :   PARSE_MD_FIELDS();
    4605             : #undef VISIT_MD_FIELDS
    4606             : 
    4607          63 :   Result = GET_OR_DISTINCT(DIObjCProperty,
    4608             :                            (Context, name.Val, file.Val, line.Val, setter.Val,
    4609             :                             getter.Val, attributes.Val, type.Val));
    4610          21 :   return false;
    4611             : }
    4612             : 
    4613             : /// ParseDIImportedEntity:
    4614             : ///   ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
    4615             : ///                         line: 7, name: "foo")
    4616         263 : bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
    4617             : #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
    4618             :   REQUIRED(tag, DwarfTagField, );                                              \
    4619             :   REQUIRED(scope, MDField, );                                                  \
    4620             :   OPTIONAL(entity, MDField, );                                                 \
    4621             :   OPTIONAL(file, MDField, );                                                   \
    4622             :   OPTIONAL(line, LineField, );                                                 \
    4623             :   OPTIONAL(name, MDStringField, );
    4624        6666 :   PARSE_MD_FIELDS();
    4625             : #undef VISIT_MD_FIELDS
    4626             : 
    4627         783 :   Result = GET_OR_DISTINCT(
    4628             :       DIImportedEntity,
    4629             :       (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
    4630         261 :   return false;
    4631             : }
    4632             : 
    4633             : #undef PARSE_MD_FIELD
    4634             : #undef NOP_FIELD
    4635             : #undef REQUIRE_FIELD
    4636             : #undef DECLARE_FIELD
    4637             : 
    4638             : /// ParseMetadataAsValue
    4639             : ///  ::= metadata i32 %local
    4640             : ///  ::= metadata i32 @global
    4641             : ///  ::= metadata i32 7
    4642             : ///  ::= metadata !0
    4643             : ///  ::= metadata !{...}
    4644             : ///  ::= metadata !"string"
    4645        7244 : bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
    4646             :   // Note: the type 'metadata' has already been parsed.
    4647             :   Metadata *MD;
    4648        7244 :   if (ParseMetadata(MD, &PFS))
    4649             :     return true;
    4650             : 
    4651        7241 :   V = MetadataAsValue::get(Context, MD);
    4652        7241 :   return false;
    4653             : }
    4654             : 
    4655             : /// ParseValueAsMetadata
    4656             : ///  ::= i32 %local
    4657             : ///  ::= i32 @global
    4658             : ///  ::= i32 7
    4659       19848 : bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
    4660             :                                     PerFunctionState *PFS) {
    4661             :   Type *Ty;
    4662             :   LocTy Loc;
    4663       19848 :   if (ParseType(Ty, TypeMsg, Loc))
    4664             :     return true;
    4665       39694 :   if (Ty->isMetadataTy())
    4666           1 :     return Error(Loc, "invalid metadata-value-metadata roundtrip");
    4667             : 
    4668             :   Value *V;
    4669       19846 :   if (ParseValue(Ty, V, PFS))
    4670             :     return true;
    4671             : 
    4672       19841 :   MD = ValueAsMetadata::get(V);
    4673       19841 :   return false;
    4674             : }
    4675             : 
    4676             : /// ParseMetadata
    4677             : ///  ::= i32 %local
    4678             : ///  ::= i32 @global
    4679             : ///  ::= i32 7
    4680             : ///  ::= !42
    4681             : ///  ::= !{...}
    4682             : ///  ::= !"string"
    4683             : ///  ::= !DILocation(...)
    4684       99823 : bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
    4685       99823 :   if (Lex.getKind() == lltok::MetadataVar) {
    4686             :     MDNode *N;
    4687        1783 :     if (ParseSpecializedMDNode(N))
    4688             :       return true;
    4689        1783 :     MD = N;
    4690        1783 :     return false;
    4691             :   }
    4692             : 
    4693             :   // ValueAsMetadata:
    4694             :   // <type> <value>
    4695       98040 :   if (Lex.getKind() != lltok::exclaim)
    4696       19848 :     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
    4697             : 
    4698             :   // '!'.
    4699             :   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
    4700       78192 :   Lex.Lex();
    4701             : 
    4702             :   // MDString:
    4703             :   //   ::= '!' STRINGCONSTANT
    4704       78192 :   if (Lex.getKind() == lltok::StringConstant) {
    4705             :     MDString *S;
    4706       10919 :     if (ParseMDString(S))
    4707             :       return true;
    4708       10919 :     MD = S;
    4709       10919 :     return false;
    4710             :   }
    4711             : 
    4712             :   // MDNode:
    4713             :   // !{ ... }
    4714             :   // !7
    4715             :   MDNode *N;
    4716       67273 :   if (ParseMDNodeTail(N))
    4717             :     return true;
    4718       67270 :   MD = N;
    4719       67270 :   return false;
    4720             : }
    4721             : 
    4722             : //===----------------------------------------------------------------------===//
    4723             : // Function Parsing.
    4724             : //===----------------------------------------------------------------------===//
    4725             : 
    4726     3099680 : bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
    4727             :                                    PerFunctionState *PFS) {
    4728     3099680 :   if (Ty->isFunctionTy())
    4729           0 :     return Error(ID.Loc, "functions are not values, refer to them as pointers");
    4730             : 
    4731     3099680 :   switch (ID.Kind) {
    4732      236607 :   case ValID::t_LocalID:
    4733      236607 :     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
    4734      236607 :     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
    4735      236607 :     return V == nullptr;
    4736     1280151 :   case ValID::t_LocalName:
    4737     1280155 :     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
    4738     1280147 :     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
    4739     1280147 :     return V == nullptr;
    4740       11820 :   case ValID::t_InlineAsm: {
    4741       35456 :     if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
    4742           3 :       return Error(ID.Loc, "invalid type for inline asm constraint string");
    4743       23634 :     V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
    4744             :                        (ID.UIntVal >> 1) & 1,
    4745       11817 :                        (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
    4746       11817 :     return false;
    4747             :   }
    4748      186150 :   case ValID::t_GlobalName:
    4749      186150 :     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
    4750      186150 :     return V == nullptr;
    4751         643 :   case ValID::t_GlobalID:
    4752         643 :     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
    4753         643 :     return V == nullptr;
    4754             :   case ValID::t_APSInt:
    4755     1046029 :     if (!Ty->isIntegerTy())
    4756           1 :       return Error(ID.Loc, "integer constant must have integer type");
    4757     2092056 :     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
    4758     1046028 :     V = ConstantInt::get(Context, ID.APSIntVal);
    4759     1046028 :     return false;
    4760             :   case ValID::t_APFloat:
    4761       42071 :     if (!Ty->isFloatingPointTy() ||
    4762       42071 :         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
    4763           2 :       return Error(ID.Loc, "floating point constant invalid for type");
    4764             : 
    4765             :     // The lexer has no type info, so builds all half, float, and double FP
    4766             :     // constants as double.  Fix this here.  Long double does not need this.
    4767       42071 :     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
    4768             :       bool Ignored;
    4769       41236 :       if (Ty->isHalfTy())
    4770        1593 :         ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
    4771             :                               &Ignored);
    4772       39643 :       else if (Ty->isFloatTy())
    4773       28454 :         ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
    4774             :                               &Ignored);
    4775             :     }
    4776       42071 :     V = ConstantFP::get(Context, ID.APFloatVal);
    4777             : 
    4778       42071 :     if (V->getType() != Ty)
    4779           3 :       return Error(ID.Loc, "floating point constant does not have type '" +
    4780           4 :                    getTypeString(Ty) + "'");
    4781             : 
    4782             :     return false;
    4783             :   case ValID::t_Null:
    4784        6807 :     if (!Ty->isPointerTy())
    4785           0 :       return Error(ID.Loc, "null must be a pointer type");
    4786        6807 :     V = ConstantPointerNull::get(cast<PointerType>(Ty));
    4787        6807 :     return false;
    4788             :   case ValID::t_Undef:
    4789             :     // FIXME: LabelTy should not be a first-class type.
    4790      133247 :     if (!Ty->isFirstClassType() || Ty->isLabelTy())
    4791           0 :       return Error(ID.Loc, "invalid type for undef constant");
    4792      133247 :     V = UndefValue::get(Ty);
    4793      133247 :     return false;
    4794             :   case ValID::t_EmptyArray:
    4795          16 :     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
    4796           0 :       return Error(ID.Loc, "invalid empty array initializer");
    4797          16 :     V = UndefValue::get(Ty);
    4798          16 :     return false;
    4799             :   case ValID::t_Zero:
    4800             :     // FIXME: LabelTy should not be a first-class type.
    4801       24787 :     if (!Ty->isFirstClassType() || Ty->isLabelTy())
    4802           0 :       return Error(ID.Loc, "invalid type for null constant");
    4803       24787 :     V = Constant::getNullValue(Ty);
    4804       24787 :     return false;
    4805             :   case ValID::t_None:
    4806         443 :     if (!Ty->isTokenTy())
    4807           0 :       return Error(ID.Loc, "invalid type for none constant");
    4808         443 :     V = Constant::getNullValue(Ty);
    4809         443 :     return false;
    4810      129264 :   case ValID::t_Constant:
    4811      129264 :     if (ID.ConstantVal->getType() != Ty)
    4812           0 :       return Error(ID.Loc, "constant expression type mismatch");
    4813             : 
    4814      129264 :     V = ID.ConstantVal;
    4815      129264 :     return false;
    4816             :   case ValID::t_ConstantStruct:
    4817             :   case ValID::t_PackedConstantStruct:
    4818             :     if (StructType *ST = dyn_cast<StructType>(Ty)) {
    4819        1643 :       if (ST->getNumElements() != ID.UIntVal)
    4820           1 :         return Error(ID.Loc,
    4821             :                      "initializer with struct type has wrong # elements");
    4822        1642 :       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
    4823           0 :         return Error(ID.Loc, "packed'ness of initializer and type don't match");
    4824             : 
    4825             :       // Verify that the elements are compatible with the structtype.
    4826       10984 :       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
    4827       14016 :         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
    4828           1 :           return Error(ID.Loc, "element " + Twine(i) +
    4829           1 :                     " of struct initializer doesn't match struct element type");
    4830             : 
    4831        3282 :       V = ConstantStruct::get(
    4832             :           ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
    4833             :     } else
    4834           0 :       return Error(ID.Loc, "constant expression type mismatch");
    4835        1641 :     return false;
    4836             :   }
    4837           0 :   llvm_unreachable("Invalid ValID");
    4838             : }
    4839             : 
    4840         507 : bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
    4841         507 :   C = nullptr;
    4842        1014 :   ValID ID;
    4843         507 :   auto Loc = Lex.getLoc();
    4844         507 :   if (ParseValID(ID, /*PFS=*/nullptr))
    4845             :     return true;
    4846         507 :   switch (ID.Kind) {
    4847         506 :   case ValID::t_APSInt:
    4848             :   case ValID::t_APFloat:
    4849             :   case ValID::t_Undef:
    4850             :   case ValID::t_Constant:
    4851             :   case ValID::t_ConstantStruct:
    4852             :   case ValID::t_PackedConstantStruct: {
    4853             :     Value *V;
    4854         506 :     if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
    4855             :       return true;
    4856             :     assert(isa<Constant>(V) && "Expected a constant value");
    4857         504 :     C = cast<Constant>(V);
    4858         504 :     return false;
    4859             :   }
    4860           0 :   case ValID::t_Null:
    4861           0 :     C = Constant::getNullValue(Ty);
    4862           0 :     return false;
    4863             :   default:
    4864           1 :     return Error(Loc, "expected a constant value");
    4865             :   }
    4866             : }
    4867             : 
    4868     2077196 : bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
    4869     2077196 :   V = nullptr;
    4870     4154392 :   ValID ID;
    4871     4154392 :   return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
    4872             : }
    4873             : 
    4874     1381943 : bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
    4875     1381943 :   Type *Ty = nullptr;
    4876     2763886 :   return ParseType(Ty) ||
    4877     2763886 :          ParseValue(Ty, V, PFS);
    4878             : }
    4879             : 
    4880       79934 : bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
    4881             :                                       PerFunctionState &PFS) {
    4882             :   Value *V;
    4883       79934 :   Loc = Lex.getLoc();
    4884       79934 :   if (ParseTypeAndValue(V, PFS)) return true;
    4885      159868 :   if (!isa<BasicBlock>(V))
    4886           0 :     return Error(Loc, "expected a basic block");
    4887       79934 :   BB = cast<BasicBlock>(V);
    4888       79934 :   return false;
    4889             : }
    4890             : 
    4891             : /// FunctionHeader
    4892             : ///   ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
    4893             : ///       OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
    4894             : ///       '(' ArgList ')' OptFuncAttrs OptSection OptionalAlign OptGC
    4895             : ///       OptionalPrefix OptionalPrologue OptPersonalityFn
    4896      265127 : bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
    4897             :   // Parse the linkage.
    4898      265127 :   LocTy LinkageLoc = Lex.getLoc();
    4899             :   unsigned Linkage;
    4900             :   unsigned Visibility;
    4901             :   unsigned DLLStorageClass;
    4902             :   bool DSOLocal;
    4903             :   AttrBuilder RetAttrs;
    4904             :   unsigned CC;
    4905             :   bool HasLinkage;
    4906      265127 :   Type *RetType = nullptr;
    4907             :   LocTy RetTypeLoc = Lex.getLoc();
    4908      265127 :   if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
    4909      265126 :                            DSOLocal) ||
    4910      795377 :       ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
    4911             :       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
    4912             :     return true;
    4913             : 
    4914             :   // Verify that the linkage is ok.
    4915      265124 :   switch ((GlobalValue::LinkageTypes)Linkage) {
    4916             :   case GlobalValue::ExternalLinkage:
    4917             :     break; // always ok.
    4918          48 :   case GlobalValue::ExternalWeakLinkage:
    4919          48 :     if (isDefine)
    4920           0 :       return Error(LinkageLoc, "invalid linkage for function definition");
    4921             :     break;
    4922        2376 :   case GlobalValue::PrivateLinkage:
    4923             :   case GlobalValue::InternalLinkage:
    4924             :   case GlobalValue::AvailableExternallyLinkage:
    4925             :   case GlobalValue::LinkOnceAnyLinkage:
    4926             :   case GlobalValue::LinkOnceODRLinkage:
    4927             :   case GlobalValue::WeakAnyLinkage:
    4928             :   case GlobalValue::WeakODRLinkage:
    4929        2376 :     if (!isDefine)
    4930           0 :       return Error(LinkageLoc, "invalid linkage for function declaration");
    4931             :     break;
    4932             :   case GlobalValue::AppendingLinkage:
    4933             :   case GlobalValue::CommonLinkage:
    4934           0 :     return Error(LinkageLoc, "invalid function linkage type");
    4935             :   }
    4936             : 
    4937      265124 :   if (!isValidVisibilityForLinkage(Visibility, Linkage))
    4938           4 :     return Error(LinkageLoc,
    4939             :                  "symbol with local linkage must have default visibility");
    4940             : 
    4941      265120 :   if (!FunctionType::isValidReturnType(RetType))
    4942           0 :     return Error(RetTypeLoc, "invalid function return type");
    4943             : 
    4944      265120 :   LocTy NameLoc = Lex.getLoc();
    4945             : 
    4946             :   std::string FunctionName;
    4947      265120 :   if (Lex.getKind() == lltok::GlobalVar) {
    4948             :     FunctionName = Lex.getStrVal();
    4949          36 :   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
    4950          36 :     unsigned NameID = Lex.getUIntVal();
    4951             : 
    4952          72 :     if (NameID != NumberedVals.size())
    4953           0 :       return TokError("function expected to be numbered '%" +
    4954           0 :                       Twine(NumberedVals.size()) + "'");
    4955             :   } else {
    4956           0 :     return TokError("expected function name");
    4957             :   }
    4958             : 
    4959      265120 :   Lex.Lex();
    4960             : 
    4961      265120 :   if (Lex.getKind() != lltok::lparen)
    4962           0 :     return TokError("expected '(' in function argument list");
    4963             : 
    4964      265120 :   SmallVector<ArgInfo, 8> ArgList;
    4965             :   bool isVarArg;
    4966             :   AttrBuilder FuncAttrs;
    4967             :   std::vector<unsigned> FwdRefAttrGrps;
    4968      265120 :   LocTy BuiltinLoc;
    4969             :   std::string Section;
    4970             :   unsigned Alignment;
    4971             :   std::string GC;
    4972      265120 :   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
    4973      265120 :   Constant *Prefix = nullptr;
    4974      265120 :   Constant *Prologue = nullptr;
    4975      265120 :   Constant *PersonalityFn = nullptr;
    4976             :   Comdat *C;
    4977             : 
    4978      530238 :   if (ParseArgumentList(ArgList, isVarArg) ||
    4979      530236 :       ParseOptionalUnnamedAddr(UnnamedAddr) ||
    4980      265118 :       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
    4981             :                                  BuiltinLoc) ||
    4982         150 :       (EatIfPresent(lltok::kw_section) &&
    4983      265267 :        ParseStringConstant(Section)) ||
    4984      530237 :       parseOptionalComdat(FunctionName, C) ||
    4985      265116 :       ParseOptionalAlignment(Alignment) ||
    4986         483 :       (EatIfPresent(lltok::kw_gc) &&
    4987         483 :        ParseStringConstant(GC)) ||
    4988          25 :       (EatIfPresent(lltok::kw_prefix) &&
    4989          25 :        ParseGlobalTypeAndValue(Prefix)) ||
    4990          46 :       (EatIfPresent(lltok::kw_prologue) &&
    4991      265166 :        ParseGlobalTypeAndValue(Prologue)) ||
    4992         992 :       (EatIfPresent(lltok::kw_personality) &&
    4993         992 :        ParseGlobalTypeAndValue(PersonalityFn)))
    4994             :     return true;
    4995             : 
    4996      265116 :   if (FuncAttrs.contains(Attribute::Builtin))
    4997           0 :     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
    4998             : 
    4999             :   // If the alignment was parsed as an attribute, move to the alignment field.
    5000      265116 :   if (FuncAttrs.hasAlignmentAttr()) {
    5001         608 :     Alignment = FuncAttrs.getAlignment();
    5002         608 :     FuncAttrs.removeAttribute(Attribute::Alignment);
    5003             :   }
    5004             : 
    5005             :   // Okay, if we got here, the function is syntactically valid.  Convert types
    5006             :   // and do semantic checks.
    5007             :   std::vector<Type*> ParamTypeList;
    5008             :   SmallVector<AttributeSet, 8> Attrs;
    5009             : 
    5010      720331 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
    5011      910430 :     ParamTypeList.push_back(ArgList[i].Ty);
    5012      455215 :     Attrs.push_back(ArgList[i].Attrs);
    5013             :   }
    5014             : 
    5015             :   AttributeList PAL =
    5016             :       AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
    5017      265116 :                          AttributeSet::get(Context, RetAttrs), Attrs);
    5018             : 
    5019      265794 :   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
    5020           0 :     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
    5021             : 
    5022             :   FunctionType *FT =
    5023      530232 :     FunctionType::get(RetType, ParamTypeList, isVarArg);
    5024             :   PointerType *PFT = PointerType::getUnqual(FT);
    5025             : 
    5026      265116 :   Fn = nullptr;
    5027      265116 :   if (!FunctionName.empty()) {
    5028             :     // If this was a definition of a forward reference, remove the definition
    5029             :     // from the forward reference table and fill in the forward ref.
    5030             :     auto FRVI = ForwardRefVals.find(FunctionName);
    5031      265075 :     if (FRVI != ForwardRefVals.end()) {
    5032       66718 :       Fn = M->getFunction(FunctionName);
    5033       33359 :       if (!Fn)
    5034           1 :         return Error(FRVI->second.second, "invalid forward reference to "
    5035             :                      "function as global value!");
    5036       33358 :       if (Fn->getType() != PFT)
    5037           1 :         return Error(FRVI->second.second, "invalid forward reference to "
    5038           3 :                      "function '" + FunctionName + "' with wrong type!");
    5039             : 
    5040             :       ForwardRefVals.erase(FRVI);
    5041      463432 :     } else if ((Fn = M->getFunction(FunctionName))) {
    5042             :       // Reject redefinitions.
    5043           3 :       return Error(NameLoc, "invalid redefinition of function '" +
    5044           2 :                    FunctionName + "'");
    5045      463430 :     } else if (M->getNamedValue(FunctionName)) {
    5046           0 :       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
    5047             :     }
    5048             : 
    5049             :   } else {
    5050             :     // If this is a definition of a forward referenced function, make sure the
    5051             :     // types agree.
    5052          82 :     auto I = ForwardRefValIDs.find(NumberedVals.size());
    5053          41 :     if (I != ForwardRefValIDs.end()) {
    5054          18 :       Fn = cast<Function>(I->second.first);
    5055          18 :       if (Fn->getType() != PFT)
    5056           0 :         return Error(NameLoc, "type of definition and forward reference of '@" +
    5057           0 :                      Twine(NumberedVals.size()) + "' disagree");
    5058             :       ForwardRefValIDs.erase(I);
    5059             :     }
    5060             :   }
    5061             : 
    5062      265113 :   if (!Fn)
    5063      463476 :     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
    5064             :   else // Move the forward-reference to the correct spot in the module.
    5065       66750 :     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
    5066             : 
    5067      265113 :   if (FunctionName.empty())
    5068          82 :     NumberedVals.push_back(Fn);
    5069             : 
    5070      265113 :   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
    5071      265113 :   maybeSetDSOLocal(DSOLocal, *Fn);
    5072      265113 :   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
    5073      265113 :   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
    5074      265113 :   Fn->setCallingConv(CC);
    5075             :   Fn->setAttributes(PAL);
    5076      265113 :   Fn->setUnnamedAddr(UnnamedAddr);
    5077      265113 :   Fn->setAlignment(Alignment);
    5078      530226 :   Fn->setSection(Section);
    5079      265113 :   Fn->setComdat(C);
    5080      265113 :   Fn->setPersonalityFn(PersonalityFn);
    5081      266079 :   if (!GC.empty()) Fn->setGC(GC);
    5082      265113 :   Fn->setPrefixData(Prefix);
    5083      265113 :   Fn->setPrologueData(Prologue);
    5084      265113 :   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
    5085             : 
    5086             :   // Add all of the arguments we parsed to the function.
    5087      265113 :   Function::arg_iterator ArgIt = Fn->arg_begin();
    5088      720323 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
    5089             :     // If the argument has a name, insert it into the argument symbol table.
    5090      910420 :     if (ArgList[i].Name.empty()) continue;
    5091             : 
    5092             :     // Set the name, if it conflicted, it will be auto-renamed.
    5093      713416 :     ArgIt->setName(ArgList[i].Name);
    5094             : 
    5095      356708 :     if (ArgIt->getName() != ArgList[i].Name)
    5096           0 :       return Error(ArgList[i].Loc, "redefinition of argument '%" +
    5097           0 :                    ArgList[i].Name + "'");
    5098             :   }
    5099             : 
    5100      265113 :   if (isDefine)
    5101             :     return false;
    5102             : 
    5103             :   // Check the declaration has no block address forward references.
    5104      107286 :   ValID ID;
    5105       53643 :   if (FunctionName.empty()) {
    5106           0 :     ID.Kind = ValID::t_GlobalID;
    5107           0 :     ID.UIntVal = NumberedVals.size() - 1;
    5108             :   } else {
    5109       53643 :     ID.Kind = ValID::t_GlobalName;
    5110             :     ID.StrVal = FunctionName;
    5111             :   }
    5112             :   auto Blocks = ForwardRefBlockAddresses.find(ID);
    5113       53643 :   if (Blocks != ForwardRefBlockAddresses.end())
    5114           0 :     return Error(Blocks->first.Loc,
    5115             :                  "cannot take blockaddress inside a declaration");
    5116             :   return false;
    5117             : }
    5118             : 
    5119      211470 : bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
    5120      422940 :   ValID ID;
    5121      211470 :   if (FunctionNumber == -1) {
    5122      211429 :     ID.Kind = ValID::t_GlobalName;
    5123      634287 :     ID.StrVal = F.getName();
    5124             :   } else {
    5125          41 :     ID.Kind = ValID::t_GlobalID;
    5126          41 :     ID.UIntVal = FunctionNumber;
    5127             :   }
    5128             : 
    5129      211470 :   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
    5130      422940 :   if (Blocks == P.ForwardRefBlockAddresses.end())
    5131             :     return false;
    5132             : 
    5133         384 :   for (const auto &I : Blocks->second) {
    5134         269 :     const ValID &BBID = I.first;
    5135         269 :     GlobalValue *GV = I.second;
    5136             : 
    5137             :     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
    5138             :            "Expected local id or name");
    5139             :     BasicBlock *BB;
    5140         269 :     if (BBID.Kind == ValID::t_LocalName)
    5141         260 :       BB = GetBB(BBID.StrVal, BBID.Loc);
    5142             :     else
    5143           9 :       BB = GetBB(BBID.UIntVal, BBID.Loc);
    5144         269 :     if (!BB)
    5145           0 :       return P.Error(BBID.Loc, "referenced value is not a basic block");
    5146             : 
    5147         269 :     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
    5148         269 :     GV->eraseFromParent();
    5149             :   }
    5150             : 
    5151         115 :   P.ForwardRefBlockAddresses.erase(Blocks);
    5152         115 :   return false;
    5153             : }
    5154             : 
    5155             : /// ParseFunctionBody
    5156             : ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
    5157      211470 : bool LLParser::ParseFunctionBody(Function &Fn) {
    5158      211470 :   if (Lex.getKind() != lltok::lbrace)
    5159           0 :     return TokError("expected '{' in function body");
    5160      211470 :   Lex.Lex();  // eat the {.
    5161             : 
    5162             :   int FunctionNumber = -1;
    5163      211511 :   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
    5164             : 
    5165      422940 :   PerFunctionState PFS(*this, Fn, FunctionNumber);
    5166             : 
    5167             :   // Resolve block addresses and allow basic blocks to be forward-declared
    5168             :   // within this function.
    5169      211470 :   if (PFS.resolveForwardRefBlockAddresses())
    5170             :     return true;
    5171      211470 :   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
    5172             : 
    5173             :   // We need at least one basic block.
    5174      211470 :   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
    5175           0 :     return TokError("function body requires at least one basic block");
    5176             : 
    5177      506612 :   while (Lex.getKind() != lltok::rbrace &&
    5178             :          Lex.getKind() != lltok::kw_uselistorder)
    5179      295206 :     if (ParseBasicBlock(PFS)) return true;
    5180             : 
    5181      212143 :   while (Lex.getKind() != lltok::rbrace)
    5182         740 :     if (ParseUseListOrder(&PFS))
    5183             :       return true;
    5184             : 
    5185             :   // Eat the }.
    5186             :   Lex.Lex();
    5187             : 
    5188             :   // Verify function is ok.
    5189      211403 :   return PFS.FinishFunction();
    5190             : }
    5191             : 
    5192             : /// ParseBasicBlock
    5193             : ///   ::= LabelStr? Instruction*
    5194      295206 : bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
    5195             :   // If this basic block starts out with a name, remember it.
    5196             :   std::string Name;
    5197      295206 :   LocTy NameLoc = Lex.getLoc();
    5198      295206 :   if (Lex.getKind() == lltok::LabelStr) {
    5199             :     Name = Lex.getStrVal();
    5200      156258 :     Lex.Lex();
    5201             :   }
    5202             : 
    5203      295206 :   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
    5204      295206 :   if (!BB)
    5205           1 :     return Error(NameLoc,
    5206           3 :                  "unable to create block named '" + Name + "'");
    5207             : 
    5208             :   std::string NameStr;
    5209             : 
    5210             :   // Parse the instructions in this block until we get a terminator.
    5211             :   Instruction *Inst;
    5212             :   do {
    5213             :     // This instruction may have three possibilities for a name: a) none
    5214             :     // specified, b) name specified "%foo =", c) number specified: "%4 =".
    5215     1274757 :     LocTy NameLoc = Lex.getLoc();
    5216             :     int NameID = -1;
    5217             :     NameStr = "";
    5218             : 
    5219     1274757 :     if (Lex.getKind() == lltok::LocalVarID) {
    5220      209507 :       NameID = Lex.getUIntVal();
    5221      209507 :       Lex.Lex();
    5222      209507 :       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
    5223          63 :         return true;
    5224     1065250 :     } else if (Lex.getKind() == lltok::LocalVar) {
    5225             :       NameStr = Lex.getStrVal();
    5226      608129 :       Lex.Lex();
    5227      608129 :       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
    5228             :         return true;
    5229             :     }
    5230             : 
    5231     1274757 :     switch (ParseInstruction(Inst, BB, PFS)) {
    5232           0 :     default: llvm_unreachable("Unknown ParseInstruction result!");
    5233             :     case InstError: return true;
    5234             :     case InstNormal:
    5235     1265751 :       BB->getInstList().push_back(Inst);
    5236             : 
    5237             :       // With a normal result, we check to see if the instruction is followed by
    5238             :       // a comma and metadata.
    5239             :       if (EatIfPresent(lltok::comma))
    5240       13526 :         if (ParseInstructionMetadata(*Inst))
    5241             :           return true;
    5242             :       break;
    5243             :     case InstExtraComma:
    5244        8948 :       BB->getInstList().push_back(Inst);
    5245             : 
    5246             :       // If the instruction parser ate an extra comma at the end of it, it
    5247             :       // *must* be followed by metadata.
    5248        8948 :       if (ParseInstructionMetadata(*Inst))
    5249             :         return true;
    5250             :       break;
    5251             :     }
    5252             : 
    5253             :     // Set the name on the instruction.
    5254     1274695 :     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
    5255     2549388 :   } while (!isa<TerminatorInst>(Inst));
    5256             : 
    5257             :   return false;
    5258             : }
    5259             : 
    5260             : //===----------------------------------------------------------------------===//
    5261             : // Instruction Parsing.
    5262             : //===----------------------------------------------------------------------===//
    5263             : 
    5264             : /// ParseInstruction - Parse one of the many different instructions.
    5265             : ///
    5266     1274757 : int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
    5267             :                                PerFunctionState &PFS) {
    5268     1274757 :   lltok::Kind Token = Lex.getKind();
    5269     1274757 :   if (Token == lltok::Eof)
    5270           1 :     return TokError("found end of file when expecting more instructions");
    5271     1274756 :   LocTy Loc = Lex.getLoc();
    5272     1274756 :   unsigned KeywordVal = Lex.getUIntVal();
    5273     1274756 :   Lex.Lex();  // Eat the keyword.
    5274             : 
    5275     1274756 :   switch (Token) {
    5276           2 :   default:                    return Error(Loc, "expected instruction opcode");
    5277             :   // Terminator Instructions.
    5278        3509 :   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
    5279      214547 :   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
    5280       72793 :   case lltok::kw_br:          return ParseBr(Inst, PFS);
    5281        1348 :   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
    5282         315 :   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
    5283        1808 :   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
    5284         239 :   case lltok::kw_resume:      return ParseResume(Inst, PFS);
    5285         164 :   case lltok::kw_cleanupret:  return ParseCleanupRet(Inst, PFS);
    5286         185 :   case lltok::kw_catchret:    return ParseCatchRet(Inst, PFS);
    5287         245 :   case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
    5288         267 :   case lltok::kw_catchpad:    return ParseCatchPad(Inst, PFS);
    5289         249 :   case lltok::kw_cleanuppad:  return ParseCleanupPad(Inst, PFS);
    5290             :   // Binary Operators.
    5291             :   case lltok::kw_add:
    5292             :   case lltok::kw_sub:
    5293             :   case lltok::kw_mul:
    5294             :   case lltok::kw_shl: {
    5295             :     bool NUW = EatIfPresent(lltok::kw_nuw);
    5296             :     bool NSW = EatIfPresent(lltok::kw_nsw);
    5297       69385 :     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
    5298             : 
    5299       69385 :     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
    5300             : 
    5301       69384 :     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
    5302       69384 :     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
    5303             :     return false;
    5304             :   }
    5305       33475 :   case lltok::kw_fadd:
    5306             :   case lltok::kw_fsub:
    5307             :   case lltok::kw_fmul:
    5308             :   case lltok::kw_fdiv:
    5309             :   case lltok::kw_frem: {
    5310       33475 :     FastMathFlags FMF = EatFastMathFlagsIfPresent();
    5311       33475 :     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
    5312       33475 :     if (Res != 0)
    5313             :       return Res;
    5314       33475 :     if (FMF.any())
    5315        3393 :       Inst->setFastMathFlags(FMF);
    5316             :     return 0;
    5317             :   }
    5318             : 
    5319             :   case lltok::kw_sdiv:
    5320             :   case lltok::kw_udiv:
    5321             :   case lltok::kw_lshr:
    5322             :   case lltok::kw_ashr: {
    5323             :     bool Exact = EatIfPresent(lltok::kw_exact);
    5324             : 
    5325       15921 :     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
    5326       15921 :     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
    5327             :     return false;
    5328             :   }
    5329             : 
    5330        2262 :   case lltok::kw_urem:
    5331        2262 :   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
    5332       29023 :   case lltok::kw_and:
    5333             :   case lltok::kw_or:
    5334       29023 :   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
    5335       50899 :   case lltok::kw_icmp:   return ParseCompare(Inst, PFS, KeywordVal);
    5336        9231 :   case lltok::kw_fcmp: {
    5337        9231 :     FastMathFlags FMF = EatFastMathFlagsIfPresent();
    5338        9231 :     int Res = ParseCompare(Inst, PFS, KeywordVal);
    5339        9231 :     if (Res != 0)
    5340             :       return Res;
    5341        9231 :     if (FMF.any())
    5342         400 :       Inst->setFastMathFlags(FMF);
    5343             :     return 0;
    5344             :   }
    5345             : 
    5346             :   // Casts.
    5347      108809 :   case lltok::kw_trunc:
    5348             :   case lltok::kw_zext:
    5349             :   case lltok::kw_sext:
    5350             :   case lltok::kw_fptrunc:
    5351             :   case lltok::kw_fpext:
    5352             :   case lltok::kw_bitcast:
    5353             :   case lltok::kw_addrspacecast:
    5354             :   case lltok::kw_uitofp:
    5355             :   case lltok::kw_sitofp:
    5356             :   case lltok::kw_fptoui:
    5357             :   case lltok::kw_fptosi:
    5358             :   case lltok::kw_inttoptr:
    5359      108809 :   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
    5360             :   // Other.
    5361       22324 :   case lltok::kw_select:         return ParseSelect(Inst, PFS);
    5362         210 :   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
    5363       20108 :   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
    5364       28024 :   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
    5365       36671 :   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
    5366       22026 :   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
    5367        1053 :   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
    5368             :   // Call.
    5369       89901 :   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
    5370       30759 :   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
    5371         136 :   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
    5372          66 :   case lltok::kw_notail:   return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
    5373             :   // Memory.
    5374       46029 :   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
    5375      147741 :   case lltok::kw_load:           return ParseLoad(Inst, PFS);
    5376      116931 :   case lltok::kw_store:          return ParseStore(Inst, PFS);
    5377        1060 :   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
    5378        5801 :   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
    5379         663 :   case lltok::kw_fence:          return ParseFence(Inst, PFS);
    5380       84727 :   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
    5381        4493 :   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
    5382        1357 :   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
    5383             :   }
    5384             : }
    5385             : 
    5386             : /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
    5387       60397 : bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
    5388       60397 :   if (Opc == Instruction::FCmp) {
    5389        9237 :     switch (Lex.getKind()) {
    5390           0 :     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
    5391        2492 :     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
    5392         295 :     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
    5393        1189 :     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
    5394        1733 :     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
    5395         392 :     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
    5396         476 :     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
    5397         253 :     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
    5398         291 :     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
    5399         237 :     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
    5400         511 :     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
    5401         346 :     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
    5402         302 :     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
    5403         243 :     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
    5404         331 :     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
    5405          72 :     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
    5406          74 :     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
    5407             :     }
    5408             :   } else {
    5409       51160 :     switch (Lex.getKind()) {
    5410           0 :     default: return TokError("expected icmp predicate (e.g. 'eq')");
    5411       17942 :     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
    5412        6785 :     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
    5413        7448 :     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
    5414        7063 :     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
    5415        1491 :     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
    5416        1608 :     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
    5417        3958 :     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
    5418        2502 :     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
    5419        1116 :     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
    5420        1247 :     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
    5421             :     }
    5422             :   }
    5423       60397 :   Lex.Lex();
    5424       60397 :   return false;
    5425             : }
    5426             : 
    5427             : //===----------------------------------------------------------------------===//
    5428             : // Terminator Instructions.
    5429             : //===----------------------------------------------------------------------===//
    5430             : 
    5431             : /// ParseRet - Parse a return instruction.
    5432             : ///   ::= 'ret' void (',' !dbg, !1)*
    5433             : ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
    5434      214547 : bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
    5435             :                         PerFunctionState &PFS) {
    5436      214547 :   SMLoc TypeLoc = Lex.getLoc();
    5437      214547 :   Type *Ty = nullptr;
    5438      214547 :   if (ParseType(Ty, true /*void allowed*/)) return true;
    5439             : 
    5440      214547 :   Type *ResType = PFS.getFunction().getReturnType();
    5441             : 
    5442      429094 :   if (Ty->isVoidTy()) {
    5443       70220 :     if (!ResType->isVoidTy())
    5444           0 :       return Error(TypeLoc, "value doesn't match function result type '" +
    5445           0 :                    getTypeString(ResType) + "'");
    5446             : 
    5447      140440 :     Inst = ReturnInst::Create(Context);
    5448       70220 :     return false;
    5449             :   }
    5450             : 
    5451             :   Value *RV;
    5452      144327 :   if (ParseValue(Ty, RV, PFS)) return true;
    5453             : 
    5454      144320 :   if (ResType != RV->getType())
    5455           6 :     return Error(TypeLoc, "value doesn't match function result type '" +
    5456           8 :                  getTypeString(ResType) + "'");
    5457             : 
    5458      144318 :   Inst = ReturnInst::Create(Context, RV);
    5459      144318 :   return false;
    5460             : }
    5461             : 
    5462             : /// ParseBr
    5463             : ///   ::= 'br' TypeAndValue
    5464             : ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
    5465       72793 : bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
    5466       72793 :   LocTy Loc, Loc2;
    5467             :   Value *Op0;
    5468             :   BasicBlock *Op1, *Op2;
    5469       72793 :   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
    5470             : 
    5471       72793 :   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
    5472       39401 :     Inst = BranchInst::Create(BB);
    5473       39401 :     return false;
    5474             :   }
    5475             : 
    5476       33392 :   if (Op0->getType() != Type::getInt1Ty(Context))
    5477           0 :     return Error(Loc, "branch condition must have 'i1' type");
    5478             : 
    5479       66784 :   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
    5480       66784 :       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
    5481      100176 :       ParseToken(lltok::comma, "expected ',' after true destination") ||
    5482       33392 :       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
    5483             :     return true;
    5484             : 
    5485       66784 :   Inst = BranchInst::Create(Op1, Op2, Op0);
    5486       33392 :   return false;
    5487             : }
    5488             : 
    5489             : /// ParseSwitch
    5490             : ///  Instruction
    5491             : ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
    5492             : ///  JumpTable
    5493             : ///    ::= (TypeAndValue ',' TypeAndValue)*
    5494        1348 : bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
    5495        1348 :   LocTy CondLoc, BBLoc;
    5496             :   Value *Cond;
    5497             :   BasicBlock *DefaultBB;
    5498        1348 :   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
    5499        2696 :       ParseToken(lltok::comma, "expected ',' after switch condition") ||
    5500        4044 :       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
    5501        1348 :       ParseToken(lltok::lsquare, "expected '[' with switch table"))
    5502             :     return true;
    5503             : 
    5504        2696 :   if (!Cond->getType()->isIntegerTy())
    5505           0 :     return Error(CondLoc, "switch condition must have integer type");
    5506             : 
    5507             :   // Parse the jump table pairs.
    5508             :   SmallPtrSet<Value*, 32> SeenCases;
    5509             :   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
    5510       14774 :   while (Lex.getKind() != lltok::rsquare) {
    5511             :     Value *Constant;
    5512             :     BasicBlock *DestBB;
    5513             : 
    5514        6713 :     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
    5515       13426 :         ParseToken(lltok::comma, "expected ',' after case value") ||
    5516             :         ParseTypeAndBasicBlock(DestBB, PFS))
    5517           0 :       return true;
    5518             : 
    5519        6713 :     if (!SeenCases.insert(Constant).second)
    5520           0 :       return Error(CondLoc, "duplicate case value in switch");
    5521       13426 :     if (!isa<ConstantInt>(Constant))
    5522           0 :       return Error(CondLoc, "case value is not a constant integer");
    5523             : 
    5524        6713 :     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
    5525             :   }
    5526             : 
    5527        1348 :   Lex.Lex();  // Eat the ']'.
    5528             : 
    5529        1348 :   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
    5530        8061 :   for (unsigned i = 0, e = Table.size(); i != e; ++i)
    5531       13426 :     SI->addCase(Table[i].first, Table[i].second);
    5532        1348 :   Inst = SI;
    5533        1348 :   return false;
    5534             : }
    5535             : 
    5536             : /// ParseIndirectBr
    5537             : ///  Instruction
    5538             : ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
    5539         315 : bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
    5540             :   LocTy AddrLoc;
    5541             :   Value *Address;
    5542         315 :   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
    5543         630 :       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
    5544         315 :       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
    5545             :     return true;
    5546             : 
    5547         630 :   if (!Address->getType()->isPointerTy())
    5548           0 :     return Error(AddrLoc, "indirectbr address must have pointer type");
    5549             : 
    5550             :   // Parse the destination list.
    5551             :   SmallVector<BasicBlock*, 16> DestList;
    5552             : 
    5553         315 :   if (Lex.getKind() != lltok::rsquare) {
    5554             :     BasicBlock *DestBB;
    5555         311 :     if (ParseTypeAndBasicBlock(DestBB, PFS))
    5556           0 :       return true;
    5557         311 :     DestList.push_back(DestBB);
    5558             : 
    5559         595 :     while (EatIfPresent(lltok::comma)) {
    5560         595 :       if (ParseTypeAndBasicBlock(DestBB, PFS))
    5561             :         return true;
    5562         595 :       DestList.push_back(DestBB);
    5563             :     }
    5564             :   }
    5565             : 
    5566         315 :   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
    5567             :     return true;
    5568             : 
    5569         315 :   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
    5570        1221 :   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
    5571        1812 :     IBI->addDestination(DestList[i]);
    5572         315 :   Inst = IBI;
    5573         315 :   return false;
    5574             : }
    5575             : 
    5576             : /// ParseInvoke
    5577             : ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
    5578             : ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
    5579        1808 : bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
    5580        1808 :   LocTy CallLoc = Lex.getLoc();
    5581             :   AttrBuilder RetAttrs, FnAttrs;
    5582             :   std::vector<unsigned> FwdRefAttrGrps;
    5583        1808 :   LocTy NoBuiltinLoc;
    5584             :   unsigned CC;
    5585        1808 :   Type *RetType = nullptr;
    5586             :   LocTy RetTypeLoc;
    5587        3616 :   ValID CalleeID;
    5588             :   SmallVector<ParamInfo, 16> ArgList;
    5589        1808 :   SmallVector<OperandBundleDef, 2> BundleList;
    5590             : 
    5591             :   BasicBlock *NormalBB, *UnwindBB;
    5592        5424 :   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
    5593        1808 :       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
    5594        5424 :       ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
    5595        1808 :       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
    5596        1808 :                                  NoBuiltinLoc) ||
    5597        3616 :       ParseOptionalOperandBundles(BundleList, PFS) ||
    5598        3616 :       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
    5599        1808 :       ParseTypeAndBasicBlock(NormalBB, PFS) ||
    5600        5424 :       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
    5601             :       ParseTypeAndBasicBlock(UnwindBB, PFS))
    5602             :     return true;
    5603             : 
    5604             :   // If RetType is a non-function pointer type, then this is the short syntax
    5605             :   // for the call, which means that RetType is just the return type.  Infer the
    5606             :   // rest of the function argument types from the arguments that are present.
    5607        1808 :   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
    5608             :   if (!Ty) {
    5609             :     // Pull out the types of all of the arguments...
    5610             :     std::vector<Type*> ParamTypes;
    5611        3526 :     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
    5612        5373 :       ParamTypes.push_back(ArgList[i].V->getType());
    5613             : 
    5614        1735 :     if (!FunctionType::isValidReturnType(RetType))
    5615           0 :       return Error(RetTypeLoc, "Invalid result type for LLVM function");
    5616             : 
    5617        1735 :     Ty = FunctionType::get(RetType, ParamTypes, false);
    5618             :   }
    5619             : 
    5620        1808 :   CalleeID.FTy = Ty;
    5621             : 
    5622             :   // Look up the callee.
    5623             :   Value *Callee;
    5624        1808 :   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
    5625             :     return true;
    5626             : 
    5627             :   // Set up the Attribute for the function.
    5628             :   SmallVector<Value *, 8> Args;
    5629             :   SmallVector<AttributeSet, 8> ArgAttrs;
    5630             : 
    5631             :   // Loop through FunctionType's arguments and ensure they are specified
    5632             :   // correctly.  Also, gather any parameter attributes.
    5633        1808 :   FunctionType::param_iterator I = Ty->param_begin();
    5634        1808 :   FunctionType::param_iterator E = Ty->param_end();
    5635        3897 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
    5636             :     Type *ExpectedTy = nullptr;
    5637        2089 :     if (I != E) {
    5638        1905 :       ExpectedTy = *I++;
    5639         184 :     } else if (!Ty->isVarArg()) {
    5640           0 :       return Error(ArgList[i].Loc, "too many arguments specified");
    5641             :     }
    5642             : 
    5643        5715 :     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
    5644           0 :       return Error(ArgList[i].Loc, "argument is not of expected type '" +
    5645           0 :                    getTypeString(ExpectedTy) + "'");
    5646        4178 :     Args.push_back(ArgList[i].V);
    5647        2089 :     ArgAttrs.push_back(ArgList[i].Attrs);
    5648             :   }
    5649             : 
    5650        1808 :   if (I != E)
    5651           0 :     return Error(CallLoc, "not enough parameters specified for call");
    5652             : 
    5653        1808 :   if (FnAttrs.hasAlignmentAttr())
    5654           0 :     return Error(CallLoc, "invoke instructions may not have an alignment");
    5655             : 
    5656             :   // Finish off the Attribute and check them
    5657             :   AttributeList PAL =
    5658             :       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
    5659        1808 :                          AttributeSet::get(Context, RetAttrs), ArgAttrs);
    5660             : 
    5661             :   InvokeInst *II =
    5662        1808 :       InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
    5663        1808 :   II->setCallingConv(CC);
    5664             :   II->setAttributes(PAL);
    5665        1808 :   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
    5666        1808 :   Inst = II;
    5667        1808 :   return false;
    5668             : }
    5669             : 
    5670             : /// ParseResume
    5671             : ///   ::= 'resume' TypeAndValue
    5672         239 : bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
    5673             :   Value *Exn; LocTy ExnLoc;
    5674         239 :   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
    5675             :     return true;
    5676             : 
    5677         239 :   ResumeInst *RI = ResumeInst::Create(Exn);
    5678         239 :   Inst = RI;
    5679         239 :   return false;
    5680             : }
    5681             : 
    5682         516 : bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
    5683             :                                   PerFunctionState &PFS) {
    5684         516 :   if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
    5685             :     return true;
    5686             : 
    5687        1446 :   while (Lex.getKind() != lltok::rsquare) {
    5688             :     // If this isn't the first argument, we need a comma.
    5689         713 :     if (!Args.empty() &&
    5690         248 :         ParseToken(lltok::comma, "expected ',' in argument list"))
    5691           0 :       return true;
    5692             : 
    5693             :     // Parse the argument.
    5694             :     LocTy ArgLoc;
    5695         465 :     Type *ArgTy = nullptr;
    5696         465 :     if (ParseType(ArgTy, ArgLoc))
    5697             :       return true;
    5698             : 
    5699             :     Value *V;
    5700         930 :     if (ArgTy->isMetadataTy()) {
    5701           0 :       if (ParseMetadataAsValue(V, PFS))
    5702             :         return true;
    5703             :     } else {
    5704         465 :       if (ParseValue(ArgTy, V, PFS))
    5705             :         return true;
    5706             :     }
    5707         465 :     Args.push_back(V);
    5708             :   }
    5709             : 
    5710         516 :   Lex.Lex();  // Lex the ']'.
    5711         516 :   return false;
    5712             : }
    5713             : 
    5714             : /// ParseCleanupRet
    5715             : ///   ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
    5716         164 : bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
    5717         164 :   Value *CleanupPad = nullptr;
    5718             : 
    5719         164 :   if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
    5720             :     return true;
    5721             : 
    5722         328 :   if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
    5723             :     return true;
    5724             : 
    5725         164 :   if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
    5726             :     return true;
    5727             : 
    5728         164 :   BasicBlock *UnwindBB = nullptr;
    5729         164 :   if (Lex.getKind() == lltok::kw_to) {
    5730         111 :     Lex.Lex();
    5731         111 :     if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
    5732             :       return true;
    5733             :   } else {
    5734          53 :     if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
    5735             :       return true;
    5736             :     }
    5737             :   }
    5738             : 
    5739         164 :   Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
    5740         164 :   return false;
    5741             : }
    5742             : 
    5743             : /// ParseCatchRet
    5744             : ///   ::= 'catchret' from Parent Value 'to' TypeAndValue
    5745         185 : bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
    5746         185 :   Value *CatchPad = nullptr;
    5747             : 
    5748         185 :   if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
    5749             :     return true;
    5750             : 
    5751         370 :   if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
    5752             :     return true;
    5753             : 
    5754             :   BasicBlock *BB;
    5755         370 :   if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
    5756             :       ParseTypeAndBasicBlock(BB, PFS))
    5757             :       return true;
    5758             : 
    5759         370 :   Inst = CatchReturnInst::Create(CatchPad, BB);
    5760         185 :   return false;
    5761             : }
    5762             : 
    5763             : /// ParseCatchSwitch
    5764             : ///   ::= 'catchswitch' within Parent
    5765         245 : bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
    5766             :   Value *ParentPad;
    5767             : 
    5768         245 :   if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
    5769             :     return true;
    5770             : 
    5771         245 :   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
    5772             :       Lex.getKind() != lltok::LocalVarID)
    5773           0 :     return TokError("expected scope value for catchswitch");
    5774             : 
    5775         490 :   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
    5776             :     return true;
    5777             : 
    5778         245 :   if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
    5779             :     return true;
    5780             : 
    5781             :   SmallVector<BasicBlock *, 32> Table;
    5782             :   do {
    5783             :     BasicBlock *DestBB;
    5784         267 :     if (ParseTypeAndBasicBlock(DestBB, PFS))
    5785           0 :       return true;
    5786         267 :     Table.push_back(DestBB);
    5787             :   } while (EatIfPresent(lltok::comma));
    5788             : 
    5789         245 :   if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
    5790             :     return true;
    5791             : 
    5792         245 :   if (ParseToken(lltok::kw_unwind,
    5793             :                  "expected 'unwind' after catchswitch scope"))
    5794             :     return true;
    5795             : 
    5796         245 :   BasicBlock *UnwindBB = nullptr;
    5797             :   if (EatIfPresent(lltok::kw_to)) {
    5798         183 :     if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
    5799             :       return true;
    5800             :   } else {
    5801          62 :     if (ParseTypeAndBasicBlock(UnwindBB, PFS))
    5802             :       return true;
    5803             :   }
    5804             : 
    5805             :   auto *CatchSwitch =
    5806         490 :       CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
    5807         779 :   for (BasicBlock *DestBB : Table)
    5808         267 :     CatchSwitch->addHandler(DestBB);
    5809         245 :   Inst = CatchSwitch;
    5810         245 :   return false;
    5811             : }
    5812             : 
    5813             : /// ParseCatchPad
    5814             : ///   ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
    5815         267 : bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
    5816         267 :   Value *CatchSwitch = nullptr;
    5817             : 
    5818         267 :   if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
    5819             :     return true;
    5820             : 
    5821         267 :   if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
    5822           0 :     return TokError("expected scope value for catchpad");
    5823             : 
    5824         534 :   if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
    5825             :     return true;
    5826             : 
    5827             :   SmallVector<Value *, 8> Args;
    5828         267 :   if (ParseExceptionArgs(Args, PFS))
    5829             :     return true;
    5830             : 
    5831         267 :   Inst = CatchPadInst::Create(CatchSwitch, Args);
    5832         267 :   return false;
    5833             : }
    5834             : 
    5835             : /// ParseCleanupPad
    5836             : ///   ::= 'cleanuppad' within Parent ParamList
    5837         249 : bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
    5838         249 :   Value *ParentPad = nullptr;
    5839             : 
    5840         249 :   if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
    5841             :     return true;
    5842             : 
    5843         249 :   if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
    5844             :       Lex.getKind() != lltok::LocalVarID)
    5845           0 :     return TokError("expected scope value for cleanuppad");
    5846             : 
    5847         498 :   if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
    5848             :     return true;
    5849             : 
    5850             :   SmallVector<Value *, 8> Args;
    5851         249 :   if (ParseExceptionArgs(Args, PFS))
    5852             :     return true;
    5853             : 
    5854         249 :   Inst = CleanupPadInst::Create(ParentPad, Args);
    5855         249 :   return false;
    5856             : }
    5857             : 
    5858             : //===----------------------------------------------------------------------===//
    5859             : // Binary Operators.
    5860             : //===----------------------------------------------------------------------===//
    5861             : 
    5862             : /// ParseArithmetic
    5863             : ///  ::= ArithmeticOps TypeAndValue ',' Value
    5864             : ///
    5865             : /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
    5866             : /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
    5867      121043 : bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
    5868             :                                unsigned Opc, unsigned OperandType) {
    5869             :   LocTy Loc; Value *LHS, *RHS;
    5870      121043 :   if (ParseTypeAndValue(LHS, Loc, PFS) ||
    5871      242086 :       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
    5872      121043 :       ParseValue(LHS->getType(), RHS, PFS))
    5873             :     return true;
    5874             : 
    5875             :   bool Valid;
    5876      121042 :   switch (OperandType) {
    5877           0 :   default: llvm_unreachable("Unknown operand type!");
    5878           0 :   case 0: // int or FP.
    5879           0 :     Valid = LHS->getType()->isIntOrIntVectorTy() ||
    5880             :             LHS->getType()->isFPOrFPVectorTy();
    5881             :     break;
    5882      175134 :   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
    5883       33475 :   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
    5884             :   }
    5885             : 
    5886      121042 :   if (!Valid)
    5887           0 :     return Error(Loc, "invalid operand type for instruction");
    5888             : 
    5889      121042 :   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
    5890      121042 :   return false;
    5891             : }
    5892             : 
    5893             : /// ParseLogical
    5894             : ///  ::= ArithmeticOps TypeAndValue ',' Value {
    5895       29023 : bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
    5896             :                             unsigned Opc) {
    5897             :   LocTy Loc; Value *LHS, *RHS;
    5898       29023 :   if (ParseTypeAndValue(LHS, Loc, PFS) ||
    5899       58046 :       ParseToken(lltok::comma, "expected ',' in logical operation") ||
    5900       29023 :       ParseValue(LHS->getType(), RHS, PFS))
    5901             :     return true;
    5902             : 
    5903       58046 :   if (!LHS->getType()->isIntOrIntVectorTy())
    5904           0 :     return Error(Loc,"instruction requires integer or integer vector operands");
    5905             : 
    5906       29023 :   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
    5907       29023 :   return false;
    5908             : }
    5909             : 
    5910             : /// ParseCompare
    5911             : ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
    5912             : ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
    5913       60130 : bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
    5914             :                             unsigned Opc) {
    5915             :   // Parse the integer/fp comparison predicate.
    5916             :   LocTy Loc;
    5917             :   unsigned Pred;
    5918             :   Value *LHS, *RHS;
    5919      120260 :   if (ParseCmpPredicate(Pred, Opc) ||
    5920       60130 :       ParseTypeAndValue(LHS, Loc, PFS) ||
    5921      180390 :       ParseToken(lltok::comma, "expected ',' after compare value") ||
    5922       60130 :       ParseValue(LHS->getType(), RHS, PFS))
    5923             :     return true;
    5924             : 
    5925       60130 :   if (Opc == Instruction::FCmp) {
    5926        9231 :     if (!LHS->getType()->isFPOrFPVectorTy())
    5927           0 :       return Error(Loc, "fcmp requires floating point operands");
    5928        9231 :     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
    5929             :   } else {
    5930             :     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
    5931      101798 :     if (!LHS->getType()->isIntOrIntVectorTy() &&
    5932             :         !LHS->getType()->isPtrOrPtrVectorTy())
    5933           0 :       return Error(Loc, "icmp requires integer operands");
    5934       50899 :     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
    5935             :   }
    5936             :   return false;
    5937             : }
    5938             : 
    5939             : //===----------------------------------------------------------------------===//
    5940             : // Other Instructions.
    5941             : //===----------------------------------------------------------------------===//
    5942             : 
    5943             : 
    5944             : /// ParseCast
    5945             : ///   ::= CastOpc TypeAndValue 'to' Type
    5946      108809 : bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
    5947             :                          unsigned Opc) {
    5948             :   LocTy Loc;
    5949             :   Value *Op;
    5950      108809 :   Type *DestTy = nullptr;
    5951      108809 :   if (ParseTypeAndValue(Op, Loc, PFS) ||
    5952      217618 :       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
    5953             :       ParseType(DestTy))
    5954             :     return true;
    5955             : 
    5956      108808 :   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
    5957           7 :     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
    5958          21 :     return Error(Loc, "invalid cast opcode for cast from '" +
    5959          35 :                  getTypeString(Op->getType()) + "' to '" +
    5960          28 :                  getTypeString(DestTy) + "'");
    5961             :   }
    5962      108801 :   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
    5963      108801 :   return false;
    5964             : }
    5965             : 
    5966             : /// ParseSelect
    5967             : ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
    5968       22324 : bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
    5969             :   LocTy Loc;
    5970             :   Value *Op0, *Op1, *Op2;
    5971       22324 :   if (ParseTypeAndValue(Op0, Loc, PFS) ||
    5972       44648 :       ParseToken(lltok::comma, "expected ',' after select condition") ||
    5973       22324 :       ParseTypeAndValue(Op1, PFS) ||
    5974       66972 :       ParseToken(lltok::comma, "expected ',' after select value") ||
    5975             :       ParseTypeAndValue(Op2, PFS))
    5976             :     return true;
    5977             : 
    5978       22324 :   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
    5979           1 :     return Error(Loc, Reason);
    5980             : 
    5981       44646 :   Inst = SelectInst::Create(Op0, Op1, Op2);
    5982       22323 :   return false;
    5983             : }
    5984             : 
    5985             : /// ParseVA_Arg
    5986             : ///   ::= 'va_arg' TypeAndValue ',' Type
    5987         210 : bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
    5988             :   Value *Op;
    5989         210 :   Type *EltTy = nullptr;
    5990             :   LocTy TypeLoc;
    5991         210 :   if (ParseTypeAndValue(Op, PFS) ||
    5992         420 :       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
    5993             :       ParseType(EltTy, TypeLoc))
    5994             :     return true;
    5995             : 
    5996         210 :   if (!EltTy->isFirstClassType())
    5997           0 :     return Error(TypeLoc, "va_arg requires operand with first class type");
    5998             : 
    5999         420 :   Inst = new VAArgInst(Op, EltTy);
    6000         210 :   return false;
    6001             : }
    6002             : 
    6003             : /// ParseExtractElement
    6004             : ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
    6005       20108 : bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
    6006             :   LocTy Loc;
    6007             :   Value *Op0, *Op1;
    6008       20108 :   if (ParseTypeAndValue(Op0, Loc, PFS) ||
    6009       40216 :       ParseToken(lltok::comma, "expected ',' after extract value") ||
    6010             :       ParseTypeAndValue(Op1, PFS))
    6011             :     return true;
    6012             : 
    6013       20108 :   if (!ExtractElementInst::isValidOperands(Op0, Op1))
    6014           0 :     return Error(Loc, "invalid extractelement operands");
    6015             : 
    6016       40216 :   Inst = ExtractElementInst::Create(Op0, Op1);
    6017       20108 :   return false;
    6018             : }
    6019             : 
    6020             : /// ParseInsertElement
    6021             : ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
    6022       28024 : bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
    6023             :   LocTy Loc;
    6024             :   Value *Op0, *Op1, *Op2;
    6025       28024 :   if (ParseTypeAndValue(Op0, Loc, PFS) ||
    6026       56048 :       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
    6027       28024 :       ParseTypeAndValue(Op1, PFS) ||
    6028       84072 :       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
    6029             :       ParseTypeAndValue(Op2, PFS))
    6030             :     return true;
    6031             : 
    6032       28024 :   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
    6033           0 :     return Error(Loc, "invalid insertelement operands");
    6034             : 
    6035       56048 :   Inst = InsertElementInst::Create(Op0, Op1, Op2);
    6036       28024 :   return false;
    6037             : }
    6038             : 
    6039             : /// ParseShuffleVector
    6040             : ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
    6041       36671 : bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
    6042             :   LocTy Loc;
    6043             :   Value *Op0, *Op1, *Op2;
    6044       36671 :   if (ParseTypeAndValue(Op0, Loc, PFS) ||
    6045       73342 :       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
    6046       36671 :       ParseTypeAndValue(Op1, PFS) ||
    6047      110013 :       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
    6048             :       ParseTypeAndValue(Op2, PFS))
    6049             :     return true;
    6050             : 
    6051       36671 :   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
    6052           0 :     return Error(Loc, "invalid shufflevector operands");
    6053             : 
    6054       36671 :   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
    6055       36671 :   return false;
    6056             : }
    6057             : 
    6058             : /// ParsePHI
    6059             : ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
    6060       22026 : int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
    6061       22026 :   Type *Ty = nullptr;  LocTy TypeLoc;
    6062             :   Value *Op0, *Op1;
    6063             : 
    6064       22026 :   if (ParseType(Ty, TypeLoc) ||
    6065       44052 :       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
    6066       44052 :       ParseValue(Ty, Op0, PFS) ||
    6067       44052 :       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
    6068       66078 :       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
    6069       22026 :       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
    6070             :     return true;
    6071             : 
    6072             :   bool AteExtraComma = false;
    6073             :   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
    6074             : 
    6075             :   while (true) {
    6076       45933 :     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
    6077             : 
    6078             :     if (!EatIfPresent(lltok::comma))
    6079             :       break;
    6080             : 
    6081       23959 :     if (Lex.getKind() == lltok::MetadataVar) {
    6082             :       AteExtraComma = true;
    6083             :       break;
    6084             :     }
    6085             : 
    6086       47814 :     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
    6087       47814 :         ParseValue(Ty, Op0, PFS) ||
    6088       47814 :         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
    6089       71721 :         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
    6090       23907 :         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
    6091             :       return true;
    6092             :   }
    6093             : 
    6094       22026 :   if (!Ty->isFirstClassType())
    6095           0 :     return Error(TypeLoc, "phi node must have first class type");
    6096             : 
    6097       44052 :   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
    6098      135918 :   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
    6099       91866 :     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
    6100       22026 :   Inst = PN;
    6101       22026 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6102             : }
    6103             : 
    6104             : /// ParseLandingPad
    6105             : ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
    6106             : /// Clause
    6107             : ///   ::= 'catch' TypeAndValue
    6108             : ///   ::= 'filter'
    6109             : ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
    6110        1053 : bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
    6111        1053 :   Type *Ty = nullptr; LocTy TyLoc;
    6112             : 
    6113        1053 :   if (ParseType(Ty, TyLoc))
    6114             :     return true;
    6115             : 
    6116        3159 :   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
    6117             :   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
    6118             : 
    6119        1997 :   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
    6120             :     LandingPadInst::ClauseType CT;
    6121             :     if (EatIfPresent(lltok::kw_catch))
    6122             :       CT = LandingPadInst::Catch;
    6123             :     else if (EatIfPresent(lltok::kw_filter))
    6124             :       CT = LandingPadInst::Filter;
    6125             :     else
    6126           0 :       return TokError("expected 'catch' or 'filter' clause type");
    6127             : 
    6128             :     Value *V;
    6129             :     LocTy VLoc;
    6130         473 :     if (ParseTypeAndValue(V, VLoc, PFS))
    6131             :       return true;
    6132             : 
    6133             :     // A 'catch' type expects a non-array constant. A filter clause expects an
    6134             :     // array constant.
    6135         473 :     if (CT == LandingPadInst::Catch) {
    6136         848 :       if (isa<ArrayType>(V->getType()))
    6137           0 :         Error(VLoc, "'catch' clause has an invalid type");
    6138             :     } else {
    6139          98 :       if (!isa<ArrayType>(V->getType()))
    6140           1 :         Error(VLoc, "'filter' clause has an invalid type");
    6141             :     }
    6142             : 
    6143         473 :     Constant *CV = dyn_cast<Constant>(V);
    6144             :     if (!CV)
    6145           1 :       return Error(VLoc, "clause argument must be a constant");
    6146         472 :     LP->addClause(CV);
    6147             :   }
    6148             : 
    6149        1052 :   Inst = LP.release();
    6150        1052 :   return false;
    6151             : }
    6152             : 
    6153             : /// ParseCall
    6154             : ///   ::= 'call' OptionalFastMathFlags OptionalCallingConv
    6155             : ///           OptionalAttrs Type Value ParameterList OptionalAttrs
    6156             : ///   ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
    6157             : ///           OptionalAttrs Type Value ParameterList OptionalAttrs
    6158             : ///   ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
    6159             : ///           OptionalAttrs Type Value ParameterList OptionalAttrs
    6160             : ///   ::= 'notail' 'call'  OptionalFastMathFlags OptionalCallingConv
    6161             : ///           OptionalAttrs Type Value ParameterList OptionalAttrs
    6162      120862 : bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
    6163             :                          CallInst::TailCallKind TCK) {
    6164             :   AttrBuilder RetAttrs, FnAttrs;
    6165             :   std::vector<unsigned> FwdRefAttrGrps;
    6166      120862 :   LocTy BuiltinLoc;
    6167             :   unsigned CC;
    6168      120862 :   Type *RetType = nullptr;
    6169             :   LocTy RetTypeLoc;
    6170      241724 :   ValID CalleeID;
    6171             :   SmallVector<ParamInfo, 16> ArgList;
    6172      120862 :   SmallVector<OperandBundleDef, 2> BundleList;
    6173      120862 :   LocTy CallLoc = Lex.getLoc();
    6174             : 
    6175      151823 :   if (TCK != CallInst::TCK_None &&
    6176       30961 :       ParseToken(lltok::kw_call,
    6177             :                  "expected 'tail call', 'musttail call', or 'notail call'"))
    6178             :     return true;
    6179             : 
    6180      120862 :   FastMathFlags FMF = EatFastMathFlagsIfPresent();
    6181             : 
    6182      362586 :   if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
    6183      120862 :       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
    6184      241724 :       ParseValID(CalleeID) ||
    6185      120862 :       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
    6186      241716 :                          PFS.getFunction().isVarArg()) ||
    6187      362570 :       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
    6188      120854 :       ParseOptionalOperandBundles(BundleList, PFS))
    6189             :     return true;
    6190             : 
    6191      120854 :   if (FMF.any() && !RetType->isFPOrFPVectorTy())
    6192           0 :     return Error(CallLoc, "fast-math-flags specified for call without "
    6193             :                           "floating-point scalar or vector return type");
    6194             : 
    6195             :   // If RetType is a non-function pointer type, then this is the short syntax
    6196             :   // for the call, which means that RetType is just the return type.  Infer the
    6197             :   // rest of the function argument types from the arguments that are present.
    6198      120854 :   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
    6199             :   if (!Ty) {
    6200             :     // Pull out the types of all of the arguments...
    6201             :     std::vector<Type*> ParamTypes;
    6202      339542 :     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
    6203      667968 :       ParamTypes.push_back(ArgList[i].V->getType());
    6204             : 
    6205      116886 :     if (!FunctionType::isValidReturnType(RetType))
    6206           0 :       return Error(RetTypeLoc, "Invalid result type for LLVM function");
    6207             : 
    6208      116886 :     Ty = FunctionType::get(RetType, ParamTypes, false);
    6209             :   }
    6210             : 
    6211      120854 :   CalleeID.FTy = Ty;
    6212             : 
    6213             :   // Look up the callee.
    6214             :   Value *Callee;
    6215      120854 :   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
    6216             :     return true;
    6217             : 
    6218             :   // Set up the Attribute for the function.
    6219             :   SmallVector<AttributeSet, 8> Attrs;
    6220             : 
    6221             :   SmallVector<Value*, 8> Args;
    6222             : 
    6223             :   // Loop through FunctionType's arguments and ensure they are specified
    6224             :   // correctly.  Also, gather any parameter attributes.
    6225      120851 :   FunctionType::param_iterator I = Ty->param_begin();
    6226      120851 :   FunctionType::param_iterator E = Ty->param_end();
    6227      352358 :   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
    6228             :     Type *ExpectedTy = nullptr;
    6229      231507 :     if (I != E) {
    6230      226580 :       ExpectedTy = *I++;
    6231        4927 :     } else if (!Ty->isVarArg()) {
    6232           0 :       return Error(ArgList[i].Loc, "too many arguments specified");
    6233             :     }
    6234             : 
    6235      679740 :     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
    6236           0 :       return Error(ArgList[i].Loc, "argument is not of expected type '" +
    6237           0 :                    getTypeString(ExpectedTy) + "'");
    6238      463014 :     Args.push_back(ArgList[i].V);
    6239      231507 :     Attrs.push_back(ArgList[i].Attrs);
    6240             :   }
    6241             : 
    6242      120851 :   if (I != E)
    6243           0 :     return Error(CallLoc, "not enough parameters specified for call");
    6244             : 
    6245      120851 :   if (FnAttrs.hasAlignmentAttr())
    6246           1 :     return Error(CallLoc, "call instructions may not have an alignment");
    6247             : 
    6248             :   // Finish off the Attribute and check them
    6249             :   AttributeList PAL =
    6250             :       AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
    6251      120850 :                          AttributeSet::get(Context, RetAttrs), Attrs);
    6252             : 
    6253      120850 :   CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
    6254             :   CI->setTailCallKind(TCK);
    6255      120850 :   CI->setCallingConv(CC);
    6256      120850 :   if (FMF.any())
    6257         610 :     CI->setFastMathFlags(FMF);
    6258             :   CI->setAttributes(PAL);
    6259      120850 :   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
    6260      120850 :   Inst = CI;
    6261      120850 :   return false;
    6262             : }
    6263             : 
    6264             : //===----------------------------------------------------------------------===//
    6265             : // Memory Instructions.
    6266             : //===----------------------------------------------------------------------===//
    6267             : 
    6268             : /// ParseAlloc
    6269             : ///   ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
    6270             : ///       (',' 'align' i32)? (',', 'addrspace(n))?
    6271       46029 : int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
    6272       46029 :   Value *Size = nullptr;
    6273       46029 :   LocTy SizeLoc, TyLoc, ASLoc;
    6274       46029 :   unsigned Alignment = 0;
    6275       46029 :   unsigned AddrSpace = 0;
    6276       46029 :   Type *Ty = nullptr;
    6277             : 
    6278             :   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
    6279             :   bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
    6280             : 
    6281       46029 :   if (ParseType(Ty, TyLoc)) return true;
    6282             : 
    6283       92058 :   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
    6284           4 :     return Error(TyLoc, "invalid type for alloca");
    6285             : 
    6286       46025 :   bool AteExtraComma = false;
    6287             :   if (EatIfPresent(lltok::comma)) {
    6288       43055 :     if (Lex.getKind() == lltok::kw_align) {
    6289       41610 :       if (ParseOptionalAlignment(Alignment))
    6290             :         return true;
    6291       41609 :       if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
    6292             :         return true;
    6293        1445 :     } else if (Lex.getKind() == lltok::kw_addrspace) {
    6294         415 :       ASLoc = Lex.getLoc();
    6295         415 :       if (ParseOptionalAddrSpace(AddrSpace))
    6296             :         return true;
    6297        1030 :     } else if (Lex.getKind() == lltok::MetadataVar) {
    6298           0 :       AteExtraComma = true;
    6299             :     } else {
    6300        1030 :       if (ParseTypeAndValue(Size, SizeLoc, PFS))
    6301             :         return true;
    6302             :       if (EatIfPresent(lltok::comma)) {
    6303         353 :         if (Lex.getKind() == lltok::kw_align) {
    6304         342 :           if (ParseOptionalAlignment(Alignment))
    6305             :             return true;
    6306         342 :           if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
    6307             :             return true;
    6308          11 :         } else if (Lex.getKind() == lltok::kw_addrspace) {
    6309           8 :           ASLoc = Lex.getLoc();
    6310           8 :           if (ParseOptionalAddrSpace(AddrSpace))
    6311             :             return true;
    6312           3 :         } else if (Lex.getKind() == lltok::MetadataVar) {
    6313           3 :           AteExtraComma = true;
    6314             :         }
    6315             :       }
    6316             :     }
    6317             :   }
    6318             : 
    6319       47054 :   if (Size && !Size->getType()->isIntegerTy())
    6320           0 :     return Error(SizeLoc, "element count must have integer type");
    6321             : 
    6322       46024 :   AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
    6323             :   AI->setUsedWithInAlloca(IsInAlloca);
    6324             :   AI->setSwiftError(IsSwiftError);
    6325       46024 :   Inst = AI;
    6326       46024 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6327             : }
    6328             : 
    6329             : /// ParseLoad
    6330             : ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
    6331             : ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
    6332             : ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
    6333      147741 : int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
    6334             :   Value *Val; LocTy Loc;
    6335      147741 :   unsigned Alignment = 0;
    6336      147741 :   bool AteExtraComma = false;
    6337             :   bool isAtomic = false;
    6338      147741 :   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
    6339      147741 :   SyncScope::ID SSID = SyncScope::System;
    6340             : 
    6341      147741 :   if (Lex.getKind() == lltok::kw_atomic) {
    6342             :     isAtomic = true;
    6343         996 :     Lex.Lex();
    6344             :   }
    6345             : 
    6346             :   bool isVolatile = false;
    6347      147741 :   if (Lex.getKind() == lltok::kw_volatile) {
    6348             :     isVolatile = true;
    6349        9353 :     Lex.Lex();
    6350             :   }
    6351             : 
    6352             :   Type *Ty;
    6353      147741 :   LocTy ExplicitTypeLoc = Lex.getLoc();
    6354      147741 :   if (ParseType(Ty) ||
    6355      295481 :       ParseToken(lltok::comma, "expected comma after load's type") ||
    6356      147740 :       ParseTypeAndValue(Val, Loc, PFS) ||
    6357      443221 :       ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
    6358      147740 :       ParseOptionalCommaAlign(Alignment, AteExtraComma))
    6359             :     return true;
    6360             : 
    6361      295478 :   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
    6362           0 :     return Error(Loc, "load operand must be a pointer to a first class type");
    6363      148735 :   if (isAtomic && !Alignment)
    6364           0 :     return Error(Loc, "atomic load must have explicit non-zero alignment");
    6365      147739 :   if (Ordering == AtomicOrdering::Release ||
    6366             :       Ordering == AtomicOrdering::AcquireRelease)
    6367           0 :     return Error(Loc, "atomic load cannot use Release ordering");
    6368             : 
    6369      147739 :   if (Ty != cast<PointerType>(Val->getType())->getElementType())
    6370           1 :     return Error(ExplicitTypeLoc,
    6371           1 :                  "explicit pointee type doesn't match operand's pointee type");
    6372             : 
    6373      147738 :   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
    6374      147738 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6375             : }
    6376             : 
    6377             : /// ParseStore
    6378             : 
    6379             : ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
    6380             : ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
    6381             : ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
    6382      116931 : int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
    6383             :   Value *Val, *Ptr; LocTy Loc, PtrLoc;
    6384      116931 :   unsigned Alignment = 0;
    6385      116931 :   bool AteExtraComma = false;
    6386             :   bool isAtomic = false;
    6387      116931 :   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
    6388      116931 :   SyncScope::ID SSID = SyncScope::System;
    6389             : 
    6390      116931 :   if (Lex.getKind() == lltok::kw_atomic) {
    6391             :     isAtomic = true;
    6392         972 :     Lex.Lex();
    6393             :   }
    6394             : 
    6395             :   bool isVolatile = false;
    6396      116931 :   if (Lex.getKind() == lltok::kw_volatile) {
    6397             :     isVolatile = true;
    6398        9792 :     Lex.Lex();
    6399             :   }
    6400             : 
    6401      116930 :   if (ParseTypeAndValue(Val, Loc, PFS) ||
    6402      233860 :       ParseToken(lltok::comma, "expected ',' after store operand") ||
    6403      116930 :       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
    6404      350791 :       ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
    6405      116930 :       ParseOptionalCommaAlign(Alignment, AteExtraComma))
    6406             :     return true;
    6407             : 
    6408      233858 :   if (!Ptr->getType()->isPointerTy())
    6409           0 :     return Error(PtrLoc, "store operand must be a pointer");
    6410      116929 :   if (!Val->getType()->isFirstClassType())
    6411           0 :     return Error(Loc, "store operand must be a first class value");
    6412      116929 :   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
    6413           0 :     return Error(Loc, "stored value and pointer type do not match");
    6414      116929 :   if (isAtomic && !Alignment)
    6415           0 :     return Error(Loc, "atomic store must have explicit non-zero alignment");
    6416      116929 :   if (Ordering == AtomicOrdering::Acquire ||
    6417             :       Ordering == AtomicOrdering::AcquireRelease)
    6418           0 :     return Error(Loc, "atomic store cannot use Acquire ordering");
    6419             : 
    6420      116929 :   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
    6421      116929 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6422             : }
    6423             : 
    6424             : /// ParseCmpXchg
    6425             : ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
    6426             : ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
    6427        1060 : int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
    6428             :   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
    6429             :   bool AteExtraComma = false;
    6430        1060 :   AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
    6431        1060 :   AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
    6432        1060 :   SyncScope::ID SSID = SyncScope::System;
    6433             :   bool isVolatile = false;
    6434             :   bool isWeak = false;
    6435             : 
    6436             :   if (EatIfPresent(lltok::kw_weak))
    6437             :     isWeak = true;
    6438             : 
    6439             :   if (EatIfPresent(lltok::kw_volatile))
    6440             :     isVolatile = true;
    6441             : 
    6442        1060 :   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
    6443        2120 :       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
    6444        1060 :       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
    6445        2120 :       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
    6446        1060 :       ParseTypeAndValue(New, NewLoc, PFS) ||
    6447        3180 :       ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
    6448        1060 :       ParseOrdering(FailureOrdering))
    6449             :     return true;
    6450             : 
    6451        2120 :   if (SuccessOrdering == AtomicOrdering::Unordered ||
    6452        1060 :       FailureOrdering == AtomicOrdering::Unordered)
    6453           0 :     return TokError("cmpxchg cannot be unordered");
    6454        1060 :   if (isStrongerThan(FailureOrdering, SuccessOrdering))
    6455           0 :     return TokError("cmpxchg failure argument shall be no stronger than the "
    6456           0 :                     "success argument");
    6457        1060 :   if (FailureOrdering == AtomicOrdering::Release ||
    6458             :       FailureOrdering == AtomicOrdering::AcquireRelease)
    6459           0 :     return TokError(
    6460           0 :         "cmpxchg failure ordering cannot include release semantics");
    6461        2120 :   if (!Ptr->getType()->isPointerTy())
    6462           0 :     return Error(PtrLoc, "cmpxchg operand must be a pointer");
    6463        1060 :   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
    6464           0 :     return Error(CmpLoc, "compare value and pointer type do not match");
    6465        1060 :   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
    6466           0 :     return Error(NewLoc, "new value and pointer type do not match");
    6467             :   if (!New->getType()->isFirstClassType())
    6468           0 :     return Error(NewLoc, "cmpxchg operand must be a first class value");
    6469             :   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
    6470        1060 :       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
    6471             :   CXI->setVolatile(isVolatile);
    6472             :   CXI->setWeak(isWeak);
    6473        1060 :   Inst = CXI;
    6474             :   return AteExtraComma ? InstExtraComma : InstNormal;
    6475             : }
    6476             : 
    6477             : /// ParseAtomicRMW
    6478             : ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
    6479             : ///       'singlethread'? AtomicOrdering
    6480        5801 : int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
    6481             :   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
    6482             :   bool AteExtraComma = false;
    6483        5801 :   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
    6484        5801 :   SyncScope::ID SSID = SyncScope::System;
    6485             :   bool isVolatile = false;
    6486             :   AtomicRMWInst::BinOp Operation;
    6487             : 
    6488             :   if (EatIfPresent(lltok::kw_volatile))
    6489             :     isVolatile = true;
    6490             : 
    6491        5801 :   switch (Lex.getKind()) {
    6492           0 :   default: return TokError("expected binary operation in atomicrmw");
    6493             :   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
    6494         862 :   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
    6495         726 :   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
    6496         609 :   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
    6497         258 :   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
    6498         578 :   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
    6499         560 :   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
    6500         405 :   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
    6501         424 :   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
    6502         416 :   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
    6503         417 :   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
    6504             :   }
    6505        5801 :   Lex.Lex();  // Eat the operation.
    6506             : 
    6507        5801 :   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
    6508       11602 :       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
    6509       11602 :       ParseTypeAndValue(Val, ValLoc, PFS) ||
    6510        5801 :       ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
    6511             :     return true;
    6512             : 
    6513        5801 :   if (Ordering == AtomicOrdering::Unordered)
    6514           0 :     return TokError("atomicrmw cannot be unordered");
    6515       11602 :   if (!Ptr->getType()->isPointerTy())
    6516           0 :     return Error(PtrLoc, "atomicrmw operand must be a pointer");
    6517        5801 :   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
    6518           0 :     return Error(ValLoc, "atomicrmw value and pointer type do not match");
    6519        5801 :   if (!Val->getType()->isIntegerTy())
    6520           0 :     return Error(ValLoc, "atomicrmw operand must be an integer");
    6521        5801 :   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
    6522        5801 :   if (Size < 8 || (Size & (Size - 1)))
    6523           0 :     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
    6524           0 :                          " integer");
    6525             : 
    6526             :   AtomicRMWInst *RMWI =
    6527        5801 :     new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
    6528             :   RMWI->setVolatile(isVolatile);
    6529        5801 :   Inst = RMWI;
    6530             :   return AteExtraComma ? InstExtraComma : InstNormal;
    6531             : }
    6532             : 
    6533             : /// ParseFence
    6534             : ///   ::= 'fence' 'singlethread'? AtomicOrdering
    6535         663 : int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
    6536         663 :   AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
    6537         663 :   SyncScope::ID SSID = SyncScope::System;
    6538         663 :   if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
    6539             :     return true;
    6540             : 
    6541         663 :   if (Ordering == AtomicOrdering::Unordered)
    6542           0 :     return TokError("fence cannot be unordered");
    6543         663 :   if (Ordering == AtomicOrdering::Monotonic)
    6544           0 :     return TokError("fence cannot be monotonic");
    6545             : 
    6546         663 :   Inst = new FenceInst(Context, Ordering, SSID);
    6547         663 :   return InstNormal;
    6548             : }
    6549             : 
    6550             : /// ParseGetElementPtr
    6551             : ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
    6552       84727 : int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
    6553       84727 :   Value *Ptr = nullptr;
    6554       84727 :   Value *Val = nullptr;
    6555             :   LocTy Loc, EltLoc;
    6556             : 
    6557             :   bool InBounds = EatIfPresent(lltok::kw_inbounds);
    6558             : 
    6559       84727 :   Type *Ty = nullptr;
    6560       84727 :   LocTy ExplicitTypeLoc = Lex.getLoc();
    6561       84727 :   if (ParseType(Ty) ||
    6562      169453 :       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
    6563             :       ParseTypeAndValue(Ptr, Loc, PFS))
    6564             :     return true;
    6565             : 
    6566       84725 :   Type *BaseType = Ptr->getType();
    6567             :   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
    6568             :   if (!BasePointerType)
    6569           1 :     return Error(Loc, "base of getelementptr must be a pointer");
    6570             : 
    6571       84724 :   if (Ty != BasePointerType->getElementType())
    6572           1 :     return Error(ExplicitTypeLoc,
    6573           1 :                  "explicit pointee type doesn't match operand's pointee type");
    6574             : 
    6575             :   SmallVector<Value*, 16> Indices;
    6576             :   bool AteExtraComma = false;
    6577             :   // GEP returns a vector of pointers if at least one of parameters is a vector.
    6578             :   // All vector parameters should have the same vector width.
    6579       84723 :   unsigned GEPWidth = BaseType->isVectorTy() ?
    6580             :     BaseType->getVectorNumElements() : 0;
    6581             : 
    6582      109437 :   while (EatIfPresent(lltok::comma)) {
    6583      110302 :     if (Lex.getKind() == lltok::MetadataVar) {
    6584             :       AteExtraComma = true;
    6585             :       break;
    6586             :     }
    6587      109438 :     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
    6588      218876 :     if (!Val->getType()->isIntOrIntVectorTy())
    6589           0 :       return Error(EltLoc, "getelementptr index must be an integer");
    6590             : 
    6591      109438 :     if (Val->getType()->isVectorTy()) {
    6592             :       unsigned ValNumEl = Val->getType()->getVectorNumElements();
    6593         452 :       if (GEPWidth && GEPWidth != ValNumEl)
    6594           1 :         return Error(EltLoc,
    6595           1 :           "getelementptr vector index has a wrong number of elements");
    6596             :       GEPWidth = ValNumEl;
    6597             :     }
    6598      109437 :     Indices.push_back(Val);
    6599             :   }
    6600             : 
    6601             :   SmallPtrSet<Type*, 4> Visited;
    6602       84722 :   if (!Indices.empty() && !Ty->isSized(&Visited))
    6603           1 :     return Error(Loc, "base element of getelementptr must be sized");
    6604             : 
    6605       84721 :   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
    6606           3 :     return Error(Loc, "invalid getelementptr indices");
    6607       84718 :   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
    6608       84718 :   if (InBounds)
    6609       62399 :     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
    6610       84718 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6611             : }
    6612             : 
    6613             : /// ParseExtractValue
    6614             : ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
    6615        4493 : int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
    6616             :   Value *Val; LocTy Loc;
    6617             :   SmallVector<unsigned, 4> Indices;
    6618             :   bool AteExtraComma;
    6619        8986 :   if (ParseTypeAndValue(Val, Loc, PFS) ||
    6620        4493 :       ParseIndexList(Indices, AteExtraComma))
    6621             :     return true;
    6622             : 
    6623        4492 :   if (!Val->getType()->isAggregateType())
    6624           0 :     return Error(Loc, "extractvalue operand must be aggregate type");
    6625             : 
    6626        4492 :   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
    6627           1 :     return Error(Loc, "invalid indices for extractvalue");
    6628        4491 :   Inst = ExtractValueInst::Create(Val, Indices);
    6629        4491 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6630             : }
    6631             : 
    6632             : /// ParseInsertValue
    6633             : ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
    6634        1357 : int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
    6635             :   Value *Val0, *Val1; LocTy Loc0, Loc1;
    6636             :   SmallVector<unsigned, 4> Indices;
    6637             :   bool AteExtraComma;
    6638        1357 :   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
    6639        2714 :       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
    6640        2714 :       ParseTypeAndValue(Val1, Loc1, PFS) ||
    6641        1357 :       ParseIndexList(Indices, AteExtraComma))
    6642             :     return true;
    6643             : 
    6644        1357 :   if (!Val0->getType()->isAggregateType())
    6645           0 :     return Error(Loc0, "insertvalue operand must be aggregate type");
    6646             : 
    6647        1357 :   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
    6648        1357 :   if (!IndexedType)
    6649           1 :     return Error(Loc0, "invalid indices for insertvalue");
    6650        1356 :   if (IndexedType != Val1->getType())
    6651           3 :     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
    6652           5 :                            getTypeString(Val1->getType()) + "' instead of '" +
    6653           5 :                            getTypeString(IndexedType) + "'");
    6654        1355 :   Inst = InsertValueInst::Create(Val0, Val1, Indices);
    6655        1355 :   return AteExtraComma ? InstExtraComma : InstNormal;
    6656             : }
    6657             : 
    6658             : //===----------------------------------------------------------------------===//
    6659             : // Embedded metadata.
    6660             : //===----------------------------------------------------------------------===//
    6661             : 
    6662             : /// ParseMDNodeVector
    6663             : ///   ::= { Element (',' Element)* }
    6664             : /// Element
    6665             : ///   ::= 'null' | TypeAndValue
    6666       17759 : bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
    6667       17759 :   if (ParseToken(lltok::lbrace, "expected '{' here"))
    6668             :     return true;
    6669             : 
    6670             :   // Check for an empty list.
    6671             :   if (EatIfPresent(lltok::rbrace))
    6672             :     return false;
    6673             : 
    6674             :   do {
    6675             :     // Null is a special case since it is typeless.
    6676         885 :     if (EatIfPresent(lltok::kw_null)) {
    6677         885 :       Elts.push_back(nullptr);
    6678         885 :       continue;
    6679             :     }
    6680             : 
    6681             :     Metadata *MD;
    6682       47875 :     if (ParseMetadata(MD, nullptr))
    6683           7 :       return true;
    6684       47868 :     Elts.push_back(MD);
    6685             :   } while (EatIfPresent(lltok::comma));
    6686             : 
    6687       16000 :   return ParseToken(lltok::rbrace, "expected end of metadata node");
    6688             : }
    6689             : 
    6690             : //===----------------------------------------------------------------------===//
    6691             : // Use-list order directives.
    6692             : //===----------------------------------------------------------------------===//
    6693         858 : bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
    6694             :                                 SMLoc Loc) {
    6695         858 :   if (V->use_empty())
    6696           4 :     return Error(Loc, "value has no uses");
    6697             : 
    6698             :   unsigned NumUses = 0;
    6699             :   SmallDenseMap<const Use *, unsigned, 16> Order;
    6700        4024 :   for (const Use &U : V->uses()) {
    6701        3171 :     if (++NumUses > Indexes.size())
    6702             :       break;
    6703        9510 :     Order[&U] = Indexes[NumUses - 1];
    6704             :   }
    6705         854 :   if (NumUses < 2)
    6706           1 :     return Error(Loc, "value only has one use");
    6707         853 :   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
    6708           3 :     return Error(Loc, "wrong number of indexes, expected " +
    6709           6 :                           Twine(std::distance(V->use_begin(), V->use_end())));
    6710             : 
    6711        5158 :   V->sortUseList([&](const Use &L, const Use &R) {
    6712        8616 :     return Order.lookup(&L) < Order.lookup(&R);
    6713        4308 :   });
    6714         850 :   return false;
    6715             : }
    6716             : 
    6717             : /// ParseUseListOrderIndexes
    6718             : ///   ::= '{' uint32 (',' uint32)+ '}'
    6719         867 : bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
    6720         867 :   SMLoc Loc = Lex.getLoc();
    6721         867 :   if (ParseToken(lltok::lbrace, "expected '{' here"))
    6722             :     return true;
    6723         867 :   if (Lex.getKind() == lltok::rbrace)
    6724           0 :     return Lex.Error("expected non-empty list of uselistorder indexes");
    6725             : 
    6726             :   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
    6727             :   // indexes should be distinct numbers in the range [0, size-1], and should
    6728             :   // not be in order.
    6729             :   unsigned Offset = 0;
    6730         867 :   unsigned Max = 0;
    6731             :   bool IsOrdered = true;
    6732             :   assert(Indexes.empty() && "Expected empty order vector");
    6733             :   do {
    6734             :     unsigned Index;
    6735        3202 :     if (ParseUInt32(Index))
    6736           0 :       return true;
    6737             : 
    6738             :     // Update consistency checks.
    6739        6404 :     Offset += Index - Indexes.size();
    6740        3202 :     Max = std::max(Max, Index);
    6741        3202 :     IsOrdered &= Index == Indexes.size();
    6742             : 
    6743        3202 :     Indexes.push_back(Index);
    6744             :   } while (EatIfPresent(lltok::comma));
    6745             : 
    6746         867 :   if (ParseToken(lltok::rbrace, "expected '}' here"))
    6747             :     return true;
    6748             : 
    6749         867 :   if (Indexes.size() < 2)
    6750           0 :     return Error(Loc, "expected >= 2 uselistorder indexes");
    6751         867 :   if (Offset != 0 || Max >= Indexes.size())
    6752           2 :     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
    6753         865 :   if (IsOrdered)
    6754           1 :     return Error(Loc, "expected uselistorder indexes to change the order");
    6755             : 
    6756             :   return false;
    6757             : }
    6758             : 
    6759             : /// ParseUseListOrder
    6760             : ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
    6761         857 : bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
    6762         857 :   SMLoc Loc = Lex.getLoc();
    6763         857 :   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
    6764             :     return true;
    6765             : 
    6766             :   Value *V;
    6767             :   SmallVector<unsigned, 16> Indexes;
    6768        1711 :   if (ParseTypeAndValue(V, PFS) ||
    6769        1711 :       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
    6770         855 :       ParseUseListOrderIndexes(Indexes))
    6771             :     return true;
    6772             : 
    6773         852 :   return sortUseListOrder(V, Indexes, Loc);
    6774             : }
    6775             : 
    6776             : /// ParseUseListOrderBB
    6777             : ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
    6778          12 : bool LLParser::ParseUseListOrderBB() {
    6779             :   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
    6780          12 :   SMLoc Loc = Lex.getLoc();
    6781          12 :   Lex.Lex();
    6782             : 
    6783          24 :   ValID Fn, Label;
    6784             :   SmallVector<unsigned, 16> Indexes;
    6785          24 :   if (ParseValID(Fn) ||
    6786          24 :       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
    6787          24 :       ParseValID(Label) ||
    6788          36 :       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
    6789          12 :       ParseUseListOrderIndexes(Indexes))
    6790             :     return true;
    6791             : 
    6792             :   // Check the function.
    6793             :   GlobalValue *GV;
    6794          12 :   if (Fn.Kind == ValID::t_GlobalName)
    6795          24 :     GV = M->getNamedValue(Fn.StrVal);
    6796           0 :   else if (Fn.Kind == ValID::t_GlobalID)
    6797           0 :     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
    6798             :   else
    6799           0 :     return Error(Fn.Loc, "expected function name in uselistorder_bb");
    6800          12 :   if (!GV)
    6801           1 :     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
    6802             :   auto *F = dyn_cast<Function>(GV);
    6803             :   if (!F)
    6804           1 :     return Error(Fn.Loc, "expected function name in uselistorder_bb");
    6805          10 :   if (F->isDeclaration())
    6806           1 :     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
    6807             : 
    6808             :   // Check the basic block.
    6809           9 :   if (Label.Kind == ValID::t_LocalID)
    6810           1 :     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
    6811           8 :   if (Label.Kind != ValID::t_LocalName)
    6812           0 :     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
    6813             :   Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
    6814           8 :   if (!V)
    6815           1 :     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
    6816           7 :   if (!isa<BasicBlock>(V))
    6817           1 :     return Error(Label.Loc, "expected basic block in uselistorder_bb");
    6818             : 
    6819           6 :   return sortUseListOrder(V, Indexes, Loc);
    6820             : }

Generated by: LCOV version 1.13