blob: 63104129f8c2df6dd4f582c7aa9d8682ab606f61 [file] [log] [blame]
//===-- LLParser.cpp - Parser Class ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the parser class for .ll files.
//
//===----------------------------------------------------------------------===//
#include "llvm/AsmParser/LLParser.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/AsmParser/LLToken.h"
#include "llvm/AsmParser/SlotMapping.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/AutoUpgrade.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Comdat.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalIFunc.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/ModRef.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <optional>
#include <vector>
using namespace llvm;
static cl::opt<bool> AllowIncompleteIR(
"allow-incomplete-ir", cl::init(false), cl::Hidden,
cl::desc(
"Allow incomplete IR on a best effort basis (references to unknown "
"metadata will be dropped)"));
extern llvm::cl::opt<bool> UseNewDbgInfoFormat;
extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat;
extern bool WriteNewDbgInfoFormatToBitcode;
extern cl::opt<bool> WriteNewDbgInfoFormat;
static std::string getTypeString(Type *T) {
std::string Result;
raw_string_ostream Tmp(Result);
Tmp << *T;
return Tmp.str();
}
// Whatever debug info format we parsed, we should convert to the expected debug
// info format immediately afterwards.
bool LLParser::finalizeDebugInfoFormat(Module *M) {
// We should have already returned an error if we observed both intrinsics and
// records in this IR.
assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
"Mixed debug intrinsics/records seen without a parsing error?");
if (PreserveInputDbgFormat == cl::boolOrDefault::BOU_TRUE) {
UseNewDbgInfoFormat = SeenNewDbgInfoFormat;
WriteNewDbgInfoFormatToBitcode = SeenNewDbgInfoFormat;
WriteNewDbgInfoFormat = SeenNewDbgInfoFormat;
} else if (M) {
M->setIsNewDbgInfoFormat(false);
}
return false;
}
/// Run: module ::= toplevelentity*
bool LLParser::Run(bool UpgradeDebugInfo,
DataLayoutCallbackTy DataLayoutCallback) {
// Prime the lexer.
Lex.Lex();
if (Context.shouldDiscardValueNames())
return error(
Lex.getLoc(),
"Can't read textual IR with a Context that discards named Values");
if (M) {
if (parseTargetDefinitions(DataLayoutCallback))
return true;
}
return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
validateEndOfIndex() || finalizeDebugInfoFormat(M);
}
bool LLParser::parseStandaloneConstantValue(Constant *&C,
const SlotMapping *Slots) {
restoreParsingState(Slots);
Lex.Lex();
Type *Ty = nullptr;
if (parseType(Ty) || parseConstantValue(Ty, C))
return true;
if (Lex.getKind() != lltok::Eof)
return error(Lex.getLoc(), "expected end of string");
return false;
}
bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
const SlotMapping *Slots) {
restoreParsingState(Slots);
Lex.Lex();
Read = 0;
SMLoc Start = Lex.getLoc();
Ty = nullptr;
if (parseType(Ty))
return true;
SMLoc End = Lex.getLoc();
Read = End.getPointer() - Start.getPointer();
return false;
}
void LLParser::restoreParsingState(const SlotMapping *Slots) {
if (!Slots)
return;
NumberedVals = Slots->GlobalValues;
NumberedMetadata = Slots->MetadataNodes;
for (const auto &I : Slots->NamedTypes)
NamedTypes.insert(
std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
for (const auto &I : Slots->Types)
NumberedTypes.insert(
std::make_pair(I.first, std::make_pair(I.second, LocTy())));
}
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II) {
// White-list intrinsics that are safe to drop.
if (!isa<DbgInfoIntrinsic>(II) &&
II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
return;
SmallVector<MetadataAsValue *> MVs;
for (Value *V : II->args())
if (auto *MV = dyn_cast<MetadataAsValue>(V))
if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
if (MD->isTemporary())
MVs.push_back(MV);
if (!MVs.empty()) {
assert(II->use_empty() && "Cannot have uses");
II->eraseFromParent();
// Also remove no longer used MetadataAsValue wrappers.
for (MetadataAsValue *MV : MVs)
if (MV->use_empty())
delete MV;
}
}
void LLParser::dropUnknownMetadataReferences() {
auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
for (Function &F : *M) {
F.eraseMetadataIf(Pred);
for (Instruction &I : make_early_inc_range(instructions(F))) {
I.eraseMetadataIf(Pred);
if (auto *II = dyn_cast<IntrinsicInst>(&I))
dropIntrinsicWithUnknownMetadataArgument(II);
}
}
for (GlobalVariable &GV : M->globals())
GV.eraseMetadataIf(Pred);
for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
// Check whether there is only a single use left, which would be in our
// own NumberedMetadata.
if (Info.first->getNumTemporaryUses() == 1) {
NumberedMetadata.erase(ID);
ForwardRefMDNodes.erase(ID);
}
}
}
/// validateEndOfModule - Do final validity and basic correctness checks at the
/// end of the module.
bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
if (!M)
return false;
// Handle any function attribute group forward references.
for (const auto &RAG : ForwardRefAttrGroups) {
Value *V = RAG.first;
const std::vector<unsigned> &Attrs = RAG.second;
AttrBuilder B(Context);
for (const auto &Attr : Attrs) {
auto R = NumberedAttrBuilders.find(Attr);
if (R != NumberedAttrBuilders.end())
B.merge(R->second);
}
if (Function *Fn = dyn_cast<Function>(V)) {
AttributeList AS = Fn->getAttributes();
AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
AS = AS.removeFnAttributes(Context);
FnAttrs.merge(B);
// If the alignment was parsed as an attribute, move to the alignment
// field.
if (MaybeAlign A = FnAttrs.getAlignment()) {
Fn->setAlignment(*A);
FnAttrs.removeAttribute(Attribute::Alignment);
}
AS = AS.addFnAttributes(Context, FnAttrs);
Fn->setAttributes(AS);
} else if (CallInst *CI = dyn_cast<CallInst>(V)) {
AttributeList AS = CI->getAttributes();
AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
AS = AS.removeFnAttributes(Context);
FnAttrs.merge(B);
AS = AS.addFnAttributes(Context, FnAttrs);
CI->setAttributes(AS);
} else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
AttributeList AS = II->getAttributes();
AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
AS = AS.removeFnAttributes(Context);
FnAttrs.merge(B);
AS = AS.addFnAttributes(Context, FnAttrs);
II->setAttributes(AS);
} else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
AttributeList AS = CBI->getAttributes();
AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
AS = AS.removeFnAttributes(Context);
FnAttrs.merge(B);
AS = AS.addFnAttributes(Context, FnAttrs);
CBI->setAttributes(AS);
} else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
AttrBuilder Attrs(M->getContext(), GV->getAttributes());
Attrs.merge(B);
GV->setAttributes(AttributeSet::get(Context,Attrs));
} else {
llvm_unreachable("invalid object with forward attribute group reference");
}
}
// If there are entries in ForwardRefBlockAddresses at this point, the
// function was never defined.
if (!ForwardRefBlockAddresses.empty())
return error(ForwardRefBlockAddresses.begin()->first.Loc,
"expected function name in blockaddress");
auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
GlobalValue *FwdRef) {
GlobalValue *GV = nullptr;
if (GVRef.Kind == ValID::t_GlobalName) {
GV = M->getNamedValue(GVRef.StrVal);
} else {
GV = NumberedVals.get(GVRef.UIntVal);
}
if (!GV)
return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
"' referenced by dso_local_equivalent");
if (!GV->getValueType()->isFunctionTy())
return error(GVRef.Loc,
"expected a function, alias to function, or ifunc "
"in dso_local_equivalent");
auto *Equiv = DSOLocalEquivalent::get(GV);
FwdRef->replaceAllUsesWith(Equiv);
FwdRef->eraseFromParent();
return false;
};
// If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
// point, they are references after the function was defined. Resolve those
// now.
for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
return true;
}
for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
return true;
}
ForwardRefDSOLocalEquivalentIDs.clear();
ForwardRefDSOLocalEquivalentNames.clear();
for (const auto &NT : NumberedTypes)
if (NT.second.second.isValid())
return error(NT.second.second,
"use of undefined type '%" + Twine(NT.first) + "'");
for (StringMap<std::pair<Type*, LocTy> >::iterator I =
NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
if (I->second.second.isValid())
return error(I->second.second,
"use of undefined type named '" + I->getKey() + "'");
if (!ForwardRefComdats.empty())
return error(ForwardRefComdats.begin()->second,
"use of undefined comdat '$" +
ForwardRefComdats.begin()->first + "'");
for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
FunctionType *FTy = nullptr;
for (Use &U : V->uses()) {
auto *CB = dyn_cast<CallBase>(U.getUser());
if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
return nullptr;
FTy = CB->getFunctionType();
}
return FTy;
};
auto GetDeclarationType = [&](StringRef Name, Value *V) -> Type * {
// Automatically create declarations for intrinsics. Intrinsics can only
// be called directly, so the call function type directly determines the
// declaration function type.
if (Name.starts_with("llvm."))
// Don't do anything if the intrinsic is called with different function
// types. This would result in a verifier error anyway.
return GetCommonFunctionType(V);
if (AllowIncompleteIR) {
// If incomplete IR is allowed, also add declarations for
// non-intrinsics. First check whether this global is only used in
// calls with the same type, in which case we'll insert a function.
if (auto *Ty = GetCommonFunctionType(V))
return Ty;
// Otherwise, fall back to using a dummy i8 type.
return Type::getInt8Ty(Context);
}
return nullptr;
};
if (Type *Ty = GetDeclarationType(Name, Info.first)) {
GlobalValue *GV;
if (auto *FTy = dyn_cast<FunctionType>(Ty))
GV = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
else
GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
GlobalValue::ExternalLinkage,
/*Initializer*/ nullptr, Name);
Info.first->replaceAllUsesWith(GV);
Info.first->eraseFromParent();
ForwardRefVals.erase(Name);
}
}
if (!ForwardRefVals.empty())
return error(ForwardRefVals.begin()->second.second,
"use of undefined value '@" + ForwardRefVals.begin()->first +
"'");
if (!ForwardRefValIDs.empty())
return error(ForwardRefValIDs.begin()->second.second,
"use of undefined value '@" +
Twine(ForwardRefValIDs.begin()->first) + "'");
if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
dropUnknownMetadataReferences();
if (!ForwardRefMDNodes.empty())
return error(ForwardRefMDNodes.begin()->second.second,
"use of undefined metadata '!" +
Twine(ForwardRefMDNodes.begin()->first) + "'");
// Resolve metadata cycles.
for (auto &N : NumberedMetadata) {
if (N.second && !N.second->isResolved())
N.second->resolveCycles();
}
for (auto *Inst : InstsWithTBAATag) {
MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
// With incomplete IR, the tbaa metadata may have been dropped.
if (!AllowIncompleteIR)
assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
if (MD) {
auto *UpgradedMD = UpgradeTBAANode(*MD);
if (MD != UpgradedMD)
Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
}
}
// Look for intrinsic functions and CallInst that need to be upgraded. We use
// make_early_inc_range here because we may remove some functions.
for (Function &F : llvm::make_early_inc_range(*M))
UpgradeCallsToIntrinsic(&F);
if (UpgradeDebugInfo)
llvm::UpgradeDebugInfo(*M);
UpgradeModuleFlags(*M);
UpgradeSectionAttributes(*M);
if (!Slots)
return false;
// Initialize the slot mapping.
// Because by this point we've parsed and validated everything, we can "steal"
// the mapping from LLParser as it doesn't need it anymore.
Slots->GlobalValues = std::move(NumberedVals);
Slots->MetadataNodes = std::move(NumberedMetadata);
for (const auto &I : NamedTypes)
Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
for (const auto &I : NumberedTypes)
Slots->Types.insert(std::make_pair(I.first, I.second.first));
return false;
}
/// Do final validity and basic correctness checks at the end of the index.
bool LLParser::validateEndOfIndex() {
if (!Index)
return false;
if (!ForwardRefValueInfos.empty())
return error(ForwardRefValueInfos.begin()->second.front().second,
"use of undefined summary '^" +
Twine(ForwardRefValueInfos.begin()->first) + "'");
if (!ForwardRefAliasees.empty())
return error(ForwardRefAliasees.begin()->second.front().second,
"use of undefined summary '^" +
Twine(ForwardRefAliasees.begin()->first) + "'");
if (!ForwardRefTypeIds.empty())
return error(ForwardRefTypeIds.begin()->second.front().second,
"use of undefined type id summary '^" +
Twine(ForwardRefTypeIds.begin()->first) + "'");
return false;
}
//===----------------------------------------------------------------------===//
// Top-Level Entities
//===----------------------------------------------------------------------===//
bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
// Delay parsing of the data layout string until the target triple is known.
// Then, pass both the the target triple and the tentative data layout string
// to DataLayoutCallback, allowing to override the DL string.
// This enables importing modules with invalid DL strings.
std::string TentativeDLStr = M->getDataLayoutStr();
LocTy DLStrLoc;
bool Done = false;
while (!Done) {
switch (Lex.getKind()) {
case lltok::kw_target:
if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
return true;
break;
case lltok::kw_source_filename:
if (parseSourceFileName())
return true;
break;
default:
Done = true;
}
}
// Run the override callback to potentially change the data layout string, and
// parse the data layout string.
if (auto LayoutOverride =
DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
TentativeDLStr = *LayoutOverride;
DLStrLoc = {};
}
Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
if (!MaybeDL)
return error(DLStrLoc, toString(MaybeDL.takeError()));
M->setDataLayout(MaybeDL.get());
return false;
}
bool LLParser::parseTopLevelEntities() {
// If there is no Module, then parse just the summary index entries.
if (!M) {
while (true) {
switch (Lex.getKind()) {
case lltok::Eof:
return false;
case lltok::SummaryID:
if (parseSummaryEntry())
return true;
break;
case lltok::kw_source_filename:
if (parseSourceFileName())
return true;
break;
default:
// Skip everything else
Lex.Lex();
}
}
}
while (true) {
switch (Lex.getKind()) {
default:
return tokError("expected top-level entity");
case lltok::Eof: return false;
case lltok::kw_declare:
if (parseDeclare())
return true;
break;
case lltok::kw_define:
if (parseDefine())
return true;
break;
case lltok::kw_module:
if (parseModuleAsm())
return true;
break;
case lltok::LocalVarID:
if (parseUnnamedType())
return true;
break;
case lltok::LocalVar:
if (parseNamedType())
return true;
break;
case lltok::GlobalID:
if (parseUnnamedGlobal())
return true;
break;
case lltok::GlobalVar:
if (parseNamedGlobal())
return true;
break;
case lltok::ComdatVar: if (parseComdat()) return true; break;
case lltok::exclaim:
if (parseStandaloneMetadata())
return true;
break;
case lltok::SummaryID:
if (parseSummaryEntry())
return true;
break;
case lltok::MetadataVar:
if (parseNamedMetadata())
return true;
break;
case lltok::kw_attributes:
if (parseUnnamedAttrGrp())
return true;
break;
case lltok::kw_uselistorder:
if (parseUseListOrder())
return true;
break;
case lltok::kw_uselistorder_bb:
if (parseUseListOrderBB())
return true;
break;
}
}
}
/// toplevelentity
/// ::= 'module' 'asm' STRINGCONSTANT
bool LLParser::parseModuleAsm() {
assert(Lex.getKind() == lltok::kw_module);
Lex.Lex();
std::string AsmStr;
if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
parseStringConstant(AsmStr))
return true;
M->appendModuleInlineAsm(AsmStr);
return false;
}
/// toplevelentity
/// ::= 'target' 'triple' '=' STRINGCONSTANT
/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
LocTy &DLStrLoc) {
assert(Lex.getKind() == lltok::kw_target);
std::string Str;
switch (Lex.Lex()) {
default:
return tokError("unknown target property");
case lltok::kw_triple:
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' after target triple") ||
parseStringConstant(Str))
return true;
M->setTargetTriple(Str);
return false;
case lltok::kw_datalayout:
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' after target datalayout"))
return true;
DLStrLoc = Lex.getLoc();
if (parseStringConstant(TentativeDLStr))
return true;
return false;
}
}
/// toplevelentity
/// ::= 'source_filename' '=' STRINGCONSTANT
bool LLParser::parseSourceFileName() {
assert(Lex.getKind() == lltok::kw_source_filename);
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' after source_filename") ||
parseStringConstant(SourceFileName))
return true;
if (M)
M->setSourceFileName(SourceFileName);
return false;
}
/// parseUnnamedType:
/// ::= LocalVarID '=' 'type' type
bool LLParser::parseUnnamedType() {
LocTy TypeLoc = Lex.getLoc();
unsigned TypeID = Lex.getUIntVal();
Lex.Lex(); // eat LocalVarID;
if (parseToken(lltok::equal, "expected '=' after name") ||
parseToken(lltok::kw_type, "expected 'type' after '='"))
return true;
Type *Result = nullptr;
if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
if (Entry.first)
return error(TypeLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= LocalVar '=' 'type' type
bool LLParser::parseNamedType() {
std::string Name = Lex.getStrVal();
LocTy NameLoc = Lex.getLoc();
Lex.Lex(); // eat LocalVar.
if (parseToken(lltok::equal, "expected '=' after name") ||
parseToken(lltok::kw_type, "expected 'type' after name"))
return true;
Type *Result = nullptr;
if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
if (Entry.first)
return error(NameLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= 'declare' FunctionHeader
bool LLParser::parseDeclare() {
assert(Lex.getKind() == lltok::kw_declare);
Lex.Lex();
std::vector<std::pair<unsigned, MDNode *>> MDs;
while (Lex.getKind() == lltok::MetadataVar) {
unsigned MDK;
MDNode *N;
if (parseMetadataAttachment(MDK, N))
return true;
MDs.push_back({MDK, N});
}
Function *F;
unsigned FunctionNumber = -1;
SmallVector<unsigned> UnnamedArgNums;
if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
return true;
for (auto &MD : MDs)
F->addMetadata(MD.first, *MD.second);
return false;
}
/// toplevelentity
/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
bool LLParser::parseDefine() {
assert(Lex.getKind() == lltok::kw_define);
Lex.Lex();
Function *F;
unsigned FunctionNumber = -1;
SmallVector<unsigned> UnnamedArgNums;
return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
parseOptionalFunctionMetadata(*F) ||
parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
}
/// parseGlobalType
/// ::= 'constant'
/// ::= 'global'
bool LLParser::parseGlobalType(bool &IsConstant) {
if (Lex.getKind() == lltok::kw_constant)
IsConstant = true;
else if (Lex.getKind() == lltok::kw_global)
IsConstant = false;
else {
IsConstant = false;
return tokError("expected 'global' or 'constant'");
}
Lex.Lex();
return false;
}
bool LLParser::parseOptionalUnnamedAddr(
GlobalVariable::UnnamedAddr &UnnamedAddr) {
if (EatIfPresent(lltok::kw_unnamed_addr))
UnnamedAddr = GlobalValue::UnnamedAddr::Global;
else if (EatIfPresent(lltok::kw_local_unnamed_addr))
UnnamedAddr = GlobalValue::UnnamedAddr::Local;
else
UnnamedAddr = GlobalValue::UnnamedAddr::None;
return false;
}
/// parseUnnamedGlobal:
/// OptionalVisibility (ALIAS | IFUNC) ...
/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
/// OptionalDLLStorageClass
/// ... -> global variable
/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
/// OptionalVisibility
/// OptionalDLLStorageClass
/// ... -> global variable
bool LLParser::parseUnnamedGlobal() {
unsigned VarID;
std::string Name;
LocTy NameLoc = Lex.getLoc();
// Handle the GlobalID form.
if (Lex.getKind() == lltok::GlobalID) {
VarID = Lex.getUIntVal();
if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
return true;
Lex.Lex(); // eat GlobalID;
if (parseToken(lltok::equal, "expected '=' after name"))
return true;
} else {
VarID = NumberedVals.getNext();
}
bool HasLinkage;
unsigned Linkage, Visibility, DLLStorageClass;
bool DSOLocal;
GlobalVariable::ThreadLocalMode TLM;
GlobalVariable::UnnamedAddr UnnamedAddr;
if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
DSOLocal) ||
parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
return true;
switch (Lex.getKind()) {
default:
return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
case lltok::kw_alias:
case lltok::kw_ifunc:
return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
}
}
/// parseNamedGlobal:
/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
/// OptionalVisibility OptionalDLLStorageClass
/// ... -> global variable
bool LLParser::parseNamedGlobal() {
assert(Lex.getKind() == lltok::GlobalVar);
LocTy NameLoc = Lex.getLoc();
std::string Name = Lex.getStrVal();
Lex.Lex();
bool HasLinkage;
unsigned Linkage, Visibility, DLLStorageClass;
bool DSOLocal;
GlobalVariable::ThreadLocalMode TLM;
GlobalVariable::UnnamedAddr UnnamedAddr;
if (parseToken(lltok::equal, "expected '=' in global variable") ||
parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
DSOLocal) ||
parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
return true;
switch (Lex.getKind()) {
default:
return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
case lltok::kw_alias:
case lltok::kw_ifunc:
return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
}
}
bool LLParser::parseComdat() {
assert(Lex.getKind() == lltok::ComdatVar);
std::string Name = Lex.getStrVal();
LocTy NameLoc = Lex.getLoc();
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here"))
return true;
if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
return tokError("expected comdat type");
Comdat::SelectionKind SK;
switch (Lex.getKind()) {
default:
return tokError("unknown selection kind");
case lltok::kw_any:
SK = Comdat::Any;
break;
case lltok::kw_exactmatch:
SK = Comdat::ExactMatch;
break;
case lltok::kw_largest:
SK = Comdat::Largest;
break;
case lltok::kw_nodeduplicate:
SK = Comdat::NoDeduplicate;
break;
case lltok::kw_samesize:
SK = Comdat::SameSize;
break;
}
Lex.Lex();
// See if the comdat was forward referenced, if so, use the comdat.
Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
return error(NameLoc, "redefinition of comdat '$" + Name + "'");
Comdat *C;
if (I != ComdatSymTab.end())
C = &I->second;
else
C = M->getOrInsertComdat(Name);
C->setSelectionKind(SK);
return false;
}
// MDString:
// ::= '!' STRINGCONSTANT
bool LLParser::parseMDString(MDString *&Result) {
std::string Str;
if (parseStringConstant(Str))
return true;
Result = MDString::get(Context, Str);
return false;
}
// MDNode:
// ::= '!' MDNodeNumber
bool LLParser::parseMDNodeID(MDNode *&Result) {
// !{ ..., !42, ... }
LocTy IDLoc = Lex.getLoc();
unsigned MID = 0;
if (parseUInt32(MID))
return true;
// If not a forward reference, just return it now.
if (NumberedMetadata.count(MID)) {
Result = NumberedMetadata[MID];
return false;
}
// Otherwise, create MDNode forward reference.
auto &FwdRef = ForwardRefMDNodes[MID];
FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
Result = FwdRef.first.get();
NumberedMetadata[MID].reset(Result);
return false;
}
/// parseNamedMetadata:
/// !foo = !{ !1, !2 }
bool LLParser::parseNamedMetadata() {
assert(Lex.getKind() == lltok::MetadataVar);
std::string Name = Lex.getStrVal();
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here") ||
parseToken(lltok::exclaim, "Expected '!' here") ||
parseToken(lltok::lbrace, "Expected '{' here"))
return true;
NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
if (Lex.getKind() != lltok::rbrace)
do {
MDNode *N = nullptr;
// parse DIExpressions inline as a special case. They are still MDNodes,
// so they can still appear in named metadata. Remove this logic if they
// become plain Metadata.
if (Lex.getKind() == lltok::MetadataVar &&
Lex.getStrVal() == "DIExpression") {
if (parseDIExpression(N, /*IsDistinct=*/false))
return true;
// DIArgLists should only appear inline in a function, as they may
// contain LocalAsMetadata arguments which require a function context.
} else if (Lex.getKind() == lltok::MetadataVar &&
Lex.getStrVal() == "DIArgList") {
return tokError("found DIArgList outside of function");
} else if (parseToken(lltok::exclaim, "Expected '!' here") ||
parseMDNodeID(N)) {
return true;
}
NMD->addOperand(N);
} while (EatIfPresent(lltok::comma));
return parseToken(lltok::rbrace, "expected end of metadata node");
}
/// parseStandaloneMetadata:
/// !42 = !{...}
bool LLParser::parseStandaloneMetadata() {
assert(Lex.getKind() == lltok::exclaim);
Lex.Lex();
unsigned MetadataID = 0;
MDNode *Init;
if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
return true;
// Detect common error, from old metadata syntax.
if (Lex.getKind() == lltok::Type)
return tokError("unexpected type in metadata definition");
bool IsDistinct = EatIfPresent(lltok::kw_distinct);
if (Lex.getKind() == lltok::MetadataVar) {
if (parseSpecializedMDNode(Init, IsDistinct))
return true;
} else if (parseToken(lltok::exclaim, "Expected '!' here") ||
parseMDTuple(Init, IsDistinct))
return true;
// See if this was forward referenced, if so, handle it.
auto FI = ForwardRefMDNodes.find(MetadataID);
if (FI != ForwardRefMDNodes.end()) {
auto *ToReplace = FI->second.first.get();
// DIAssignID has its own special forward-reference "replacement" for
// attachments (the temporary attachments are never actually attached).
if (isa<DIAssignID>(Init)) {
for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
"Inst unexpectedly already has DIAssignID attachment");
Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
}
}
ToReplace->replaceAllUsesWith(Init);
ForwardRefMDNodes.erase(FI);
assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
} else {
if (NumberedMetadata.count(MetadataID))
return tokError("Metadata id is already used");
NumberedMetadata[MetadataID].reset(Init);
}
return false;
}
// Skips a single module summary entry.
bool LLParser::skipModuleSummaryEntry() {
// Each module summary entry consists of a tag for the entry
// type, followed by a colon, then the fields which may be surrounded by
// nested sets of parentheses. The "tag:" looks like a Label. Once parsing
// support is in place we will look for the tokens corresponding to the
// expected tags.
if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
Lex.getKind() != lltok::kw_blockcount)
return tokError(
"Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
"start of summary entry");
if (Lex.getKind() == lltok::kw_flags)
return parseSummaryIndexFlags();
if (Lex.getKind() == lltok::kw_blockcount)
return parseBlockCount();
Lex.Lex();
if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
parseToken(lltok::lparen, "expected '(' at start of summary entry"))
return true;
// Now walk through the parenthesized entry, until the number of open
// parentheses goes back down to 0 (the first '(' was parsed above).
unsigned NumOpenParen = 1;
do {
switch (Lex.getKind()) {
case lltok::lparen:
NumOpenParen++;
break;
case lltok::rparen:
NumOpenParen--;
break;
case lltok::Eof:
return tokError("found end of file while parsing summary entry");
default:
// Skip everything in between parentheses.
break;
}
Lex.Lex();
} while (NumOpenParen > 0);
return false;
}
/// SummaryEntry
/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
bool LLParser::parseSummaryEntry() {
assert(Lex.getKind() == lltok::SummaryID);
unsigned SummaryID = Lex.getUIntVal();
// For summary entries, colons should be treated as distinct tokens,
// not an indication of the end of a label token.
Lex.setIgnoreColonInIdentifiers(true);
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here"))
return true;
// If we don't have an index object, skip the summary entry.
if (!Index)
return skipModuleSummaryEntry();
bool result = false;
switch (Lex.getKind()) {
case lltok::kw_gv:
result = parseGVEntry(SummaryID);
break;
case lltok::kw_module:
result = parseModuleEntry(SummaryID);
break;
case lltok::kw_typeid:
result = parseTypeIdEntry(SummaryID);
break;
case lltok::kw_typeidCompatibleVTable:
result = parseTypeIdCompatibleVtableEntry(SummaryID);
break;
case lltok::kw_flags:
result = parseSummaryIndexFlags();
break;
case lltok::kw_blockcount:
result = parseBlockCount();
break;
default:
result = error(Lex.getLoc(), "unexpected summary kind");
break;
}
Lex.setIgnoreColonInIdentifiers(false);
return result;
}
static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
(GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
}
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
(GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;
}
// If there was an explicit dso_local, update GV. In the absence of an explicit
// dso_local we keep the default value.
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
if (DSOLocal)
GV.setDSOLocal(true);
}
/// parseAliasOrIFunc:
/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
/// OptionalVisibility OptionalDLLStorageClass
/// OptionalThreadLocal OptionalUnnamedAddr
/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
///
/// AliaseeOrResolver
/// ::= TypeAndValue
///
/// SymbolAttrs
/// ::= ',' 'partition' StringConstant
///
/// Everything through OptionalUnnamedAddr has already been parsed.
///
bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
LocTy NameLoc, unsigned L, unsigned Visibility,
unsigned DLLStorageClass, bool DSOLocal,
GlobalVariable::ThreadLocalMode TLM,
GlobalVariable::UnnamedAddr UnnamedAddr) {
bool IsAlias;
if (Lex.getKind() == lltok::kw_alias)
IsAlias = true;
else if (Lex.getKind() == lltok::kw_ifunc)
IsAlias = false;
else
llvm_unreachable("Not an alias or ifunc!");
Lex.Lex();
GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
return error(NameLoc, "invalid linkage type for alias");
if (!isValidVisibilityForLinkage(Visibility, L))
return error(NameLoc,
"symbol with local linkage must have default visibility");
if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
return error(NameLoc,
"symbol with local linkage cannot have a DLL storage class");
Type *Ty;
LocTy ExplicitTypeLoc = Lex.getLoc();
if (parseType(Ty) ||
parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
return true;
Constant *Aliasee;
LocTy AliaseeLoc = Lex.getLoc();
if (Lex.getKind() != lltok::kw_bitcast &&
Lex.getKind() != lltok::kw_getelementptr &&
Lex.getKind() != lltok::kw_addrspacecast &&
Lex.getKind() != lltok::kw_inttoptr) {
if (parseGlobalTypeAndValue(Aliasee))
return true;
} else {
// The bitcast dest type is not present, it is implied by the dest type.
ValID ID;
if (parseValID(ID, /*PFS=*/nullptr))
return true;
if (ID.Kind != ValID::t_Constant)
return error(AliaseeLoc, "invalid aliasee");
Aliasee = ID.ConstantVal;
}
Type *AliaseeType = Aliasee->getType();
auto *PTy = dyn_cast<PointerType>(AliaseeType);
if (!PTy)
return error(AliaseeLoc, "An alias or ifunc must have pointer type");
unsigned AddrSpace = PTy->getAddressSpace();
GlobalValue *GVal = nullptr;
// See if the alias was forward referenced, if so, prepare to replace the
// forward reference.
if (!Name.empty()) {
auto I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end()) {
GVal = I->second.first;
ForwardRefVals.erase(Name);
} else if (M->getNamedValue(Name)) {
return error(NameLoc, "redefinition of global '@" + Name + "'");
}
} else {
auto I = ForwardRefValIDs.find(NameID);
if (I != ForwardRefValIDs.end()) {
GVal = I->second.first;
ForwardRefValIDs.erase(I);
}
}
// Okay, create the alias/ifunc but do not insert it into the module yet.
std::unique_ptr<GlobalAlias> GA;
std::unique_ptr<GlobalIFunc> GI;
GlobalValue *GV;
if (IsAlias) {
GA.reset(GlobalAlias::create(Ty, AddrSpace,
(GlobalValue::LinkageTypes)Linkage, Name,
Aliasee, /*Parent*/ nullptr));
GV = GA.get();
} else {
GI.reset(GlobalIFunc::create(Ty, AddrSpace,
(GlobalValue::LinkageTypes)Linkage, Name,
Aliasee, /*Parent*/ nullptr));
GV = GI.get();
}
GV->setThreadLocalMode(TLM);
GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
GV->setUnnamedAddr(UnnamedAddr);
maybeSetDSOLocal(DSOLocal, *GV);
// At this point we've parsed everything except for the IndirectSymbolAttrs.
// Now parse them if there are any.
while (Lex.getKind() == lltok::comma) {
Lex.Lex();
if (Lex.getKind() == lltok::kw_partition) {
Lex.Lex();
GV->setPartition(Lex.getStrVal());
if (parseToken(lltok::StringConstant, "expected partition string"))
return true;
} else {
return tokError("unknown alias or ifunc property!");
}
}
if (Name.empty())
NumberedVals.add(NameID, GV);
if (GVal) {
// Verify that types agree.
if (GVal->getType() != GV->getType())
return error(
ExplicitTypeLoc,
"forward reference and definition of alias have different types");
// If they agree, just RAUW the old value with the alias and remove the
// forward ref info.
GVal->replaceAllUsesWith(GV);
GVal->eraseFromParent();
}
// Insert into the module, we know its name won't collide now.
if (IsAlias)
M->insertAlias(GA.release());
else
M->insertIFunc(GI.release());
assert(GV->getName() == Name && "Should not be a name conflict!");
return false;
}
static bool isSanitizer(lltok::Kind Kind) {
switch (Kind) {
case lltok::kw_no_sanitize_address:
case lltok::kw_no_sanitize_hwaddress:
case lltok::kw_sanitize_memtag:
case lltok::kw_sanitize_address_dyninit:
return true;
default:
return false;
}
}
bool LLParser::parseSanitizer(GlobalVariable *GV) {
using SanitizerMetadata = GlobalValue::SanitizerMetadata;
SanitizerMetadata Meta;
if (GV->hasSanitizerMetadata())
Meta = GV->getSanitizerMetadata();
switch (Lex.getKind()) {
case lltok::kw_no_sanitize_address:
Meta.NoAddress = true;
break;
case lltok::kw_no_sanitize_hwaddress:
Meta.NoHWAddress = true;
break;
case lltok::kw_sanitize_memtag:
Meta.Memtag = true;
break;
case lltok::kw_sanitize_address_dyninit:
Meta.IsDynInit = true;
break;
default:
return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
}
GV->setSanitizerMetadata(Meta);
Lex.Lex();
return false;
}
/// parseGlobal
/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
/// OptionalVisibility OptionalDLLStorageClass
/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
/// Const OptionalAttrs
///
/// Everything up to and including OptionalUnnamedAddr has been parsed
/// already.
///
bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
LocTy NameLoc, unsigned Linkage, bool HasLinkage,
unsigned Visibility, unsigned DLLStorageClass,
bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
GlobalVariable::UnnamedAddr UnnamedAddr) {
if (!isValidVisibilityForLinkage(Visibility, Linkage))
return error(NameLoc,
"symbol with local linkage must have default visibility");
if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
return error(NameLoc,
"symbol with local linkage cannot have a DLL storage class");
unsigned AddrSpace;
bool IsConstant, IsExternallyInitialized;
LocTy IsExternallyInitializedLoc;
LocTy TyLoc;
Type *Ty = nullptr;
if (parseOptionalAddrSpace(AddrSpace) ||
parseOptionalToken(lltok::kw_externally_initialized,
IsExternallyInitialized,
&IsExternallyInitializedLoc) ||
parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
return true;
// If the linkage is specified and is external, then no initializer is
// present.
Constant *Init = nullptr;
if (!HasLinkage ||
!GlobalValue::isValidDeclarationLinkage(
(GlobalValue::LinkageTypes)Linkage)) {
if (parseGlobalValue(Ty, Init))
return true;
}
if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
return error(TyLoc, "invalid type for global variable");
GlobalValue *GVal = nullptr;
// See if the global was forward referenced, if so, use the global.
if (!Name.empty()) {
auto I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end()) {
GVal = I->second.first;
ForwardRefVals.erase(I);
} else if (M->getNamedValue(Name)) {
return error(NameLoc, "redefinition of global '@" + Name + "'");
}
} else {
// Handle @"", where a name is syntactically specified, but semantically
// missing.
if (NameID == (unsigned)-1)
NameID = NumberedVals.getNext();
auto I = ForwardRefValIDs.find(NameID);
if (I != ForwardRefValIDs.end()) {
GVal = I->second.first;
ForwardRefValIDs.erase(I);
}
}
GlobalVariable *GV = new GlobalVariable(
*M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
GlobalVariable::NotThreadLocal, AddrSpace);
if (Name.empty())
NumberedVals.add(NameID, GV);
// Set the parsed properties on the global.
if (Init)
GV->setInitializer(Init);
GV->setConstant(IsConstant);
GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
maybeSetDSOLocal(DSOLocal, *GV);
GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
GV->setExternallyInitialized(IsExternallyInitialized);
GV->setThreadLocalMode(TLM);
GV->setUnnamedAddr(UnnamedAddr);
if (GVal) {
if (GVal->getAddressSpace() != AddrSpace)
return error(
TyLoc,
"forward reference and definition of global have different types");
GVal->replaceAllUsesWith(GV);
GVal->eraseFromParent();
}
// parse attributes on the global.
while (Lex.getKind() == lltok::comma) {
Lex.Lex();
if (Lex.getKind() == lltok::kw_section) {
Lex.Lex();
GV->setSection(Lex.getStrVal());
if (parseToken(lltok::StringConstant, "expected global section string"))
return true;
} else if (Lex.getKind() == lltok::kw_partition) {
Lex.Lex();
GV->setPartition(Lex.getStrVal());
if (parseToken(lltok::StringConstant, "expected partition string"))
return true;
} else if (Lex.getKind() == lltok::kw_align) {
MaybeAlign Alignment;
if (parseOptionalAlignment(Alignment))
return true;
if (Alignment)
GV->setAlignment(*Alignment);
} else if (Lex.getKind() == lltok::kw_code_model) {
CodeModel::Model CodeModel;
if (parseOptionalCodeModel(CodeModel))
return true;
GV->setCodeModel(CodeModel);
} else if (Lex.getKind() == lltok::MetadataVar) {
if (parseGlobalObjectMetadataAttachment(*GV))
return true;
} else if (isSanitizer(Lex.getKind())) {
if (parseSanitizer(GV))
return true;
} else {
Comdat *C;
if (parseOptionalComdat(Name, C))
return true;
if (C)
GV->setComdat(C);
else
return tokError("unknown global variable property!");
}
}
AttrBuilder Attrs(M->getContext());
LocTy BuiltinLoc;
std::vector<unsigned> FwdRefAttrGrps;
if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
return true;
if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
GV->setAttributes(AttributeSet::get(Context, Attrs));
ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
}
return false;
}
/// parseUnnamedAttrGrp
/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
bool LLParser::parseUnnamedAttrGrp() {
assert(Lex.getKind() == lltok::kw_attributes);
LocTy AttrGrpLoc = Lex.getLoc();
Lex.Lex();
if (Lex.getKind() != lltok::AttrGrpID)
return tokError("expected attribute group id");
unsigned VarID = Lex.getUIntVal();
std::vector<unsigned> unused;
LocTy BuiltinLoc;
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here") ||
parseToken(lltok::lbrace, "expected '{' here"))
return true;
auto R = NumberedAttrBuilders.find(VarID);
if (R == NumberedAttrBuilders.end())
R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
parseToken(lltok::rbrace, "expected end of attribute group"))
return true;
if (!R->second.hasAttributes())
return error(AttrGrpLoc, "attribute group has no attributes");
return false;
}
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
switch (Kind) {
#define GET_ATTR_NAMES
#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
case lltok::kw_##DISPLAY_NAME: \
return Attribute::ENUM_NAME;
#include "llvm/IR/Attributes.inc"
default:
return Attribute::None;
}
}
bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
bool InAttrGroup) {
if (Attribute::isTypeAttrKind(Attr))
return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
switch (Attr) {
case Attribute::Alignment: {
MaybeAlign Alignment;
if (InAttrGroup) {
uint32_t Value = 0;
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
return true;
Alignment = Align(Value);
} else {
if (parseOptionalAlignment(Alignment, true))
return true;
}
B.addAlignmentAttr(Alignment);
return false;
}
case Attribute::StackAlignment: {
unsigned Alignment;
if (InAttrGroup) {
Lex.Lex();
if (parseToken(lltok::equal, "expected '=' here") ||
parseUInt32(Alignment))
return true;
} else {
if (parseOptionalStackAlignment(Alignment))
return true;
}
B.addStackAlignmentAttr(Alignment);
return false;
}
case Attribute::AllocSize: {
unsigned ElemSizeArg;
std::optional<unsigned> NumElemsArg;
if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
return true;
B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
return false;
}
case Attribute::VScaleRange: {
unsigned MinValue, MaxValue;
if (parseVScaleRangeArguments(MinValue, MaxValue))
return true;
B.addVScaleRangeAttr(MinValue,
MaxValue > 0 ? MaxValue : std::optional<unsigned>());
return false;
}
case Attribute::Dereferenceable: {
uint64_t Bytes;
if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
return true;
B.addDereferenceableAttr(Bytes);
return false;
}
case Attribute::DereferenceableOrNull: {
uint64_t Bytes;
if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
return true;
B.addDereferenceableOrNullAttr(Bytes);
return false;
}
case Attribute::UWTable: {
UWTableKind Kind;
if (parseOptionalUWTableKind(Kind))
return true;
B.addUWTableAttr(Kind);
return false;
}
case Attribute::AllocKind: {
AllocFnKind Kind = AllocFnKind::Unknown;
if (parseAllocKind(Kind))
return true;
B.addAllocKindAttr(Kind);
return false;
}
case Attribute::Memory: {
std::optional<MemoryEffects> ME = parseMemoryAttr();
if (!ME)
return true;
B.addMemoryAttr(*ME);
return false;
}
case Attribute::NoFPClass: {
if (FPClassTest NoFPClass =
static_cast<FPClassTest>(parseNoFPClassAttr())) {
B.addNoFPClassAttr(NoFPClass);
return false;
}
return true;
}
case Attribute::Range:
return parseRangeAttr(B);
default:
B.addAttribute(Attr);
Lex.Lex();
return false;
}
}
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {
switch (Kind) {
case lltok::kw_readnone:
ME &= MemoryEffects::none();
return true;
case lltok::kw_readonly:
ME &= MemoryEffects::readOnly();
return true;
case lltok::kw_writeonly:
ME &= MemoryEffects::writeOnly();
return true;
case lltok::kw_argmemonly:
ME &= MemoryEffects::argMemOnly();
return true;
case lltok::kw_inaccessiblememonly:
ME &= MemoryEffects::inaccessibleMemOnly();
return true;
case lltok::kw_inaccessiblemem_or_argmemonly:
ME &= MemoryEffects::inaccessibleOrArgMemOnly();
return true;
default:
return false;
}
}
/// parseFnAttributeValuePairs
/// ::= <attr> | <attr> '=' <value>
bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
std::vector<unsigned> &FwdRefAttrGrps,
bool InAttrGrp, LocTy &BuiltinLoc) {
bool HaveError = false;
B.clear();
MemoryEffects ME = MemoryEffects::unknown();
while (true) {
lltok::Kind Token = Lex.getKind();
if (Token == lltok::rbrace)
break; // Finished.
if (Token == lltok::StringConstant) {
if (parseStringAttribute(B))
return true;
continue;
}
if (Token == lltok::AttrGrpID) {
// Allow a function to reference an attribute group:
//
// define void @foo() #1 { ... }
if (InAttrGrp) {
HaveError |= error(
Lex.getLoc(),
"cannot have an attribute group reference in an attribute group");
} else {
// Save the reference to the attribute group. We'll fill it in later.
FwdRefAttrGrps.push_back(Lex.getUIntVal());
}
Lex.Lex();
continue;
}
SMLoc Loc = Lex.getLoc();
if (Token == lltok::kw_builtin)
BuiltinLoc = Loc;
if (upgradeMemoryAttr(ME, Token)) {
Lex.Lex();
continue;
}
Attribute::AttrKind Attr = tokenToAttribute(Token);
if (Attr == Attribute::None) {
if (!InAttrGrp)
break;
return error(Lex.getLoc(), "unterminated attribute group");
}
if (parseEnumAttribute(Attr, B, InAttrGrp))
return true;
// As a hack, we allow function alignment to be initially parsed as an
// attribute on a function declaration/definition or added to an attribute
// group and later moved to the alignment field.
if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
HaveError |= error(Loc, "this attribute does not apply to functions");
}
if (ME != MemoryEffects::unknown())
B.addMemoryAttr(ME);
return HaveError;
}
//===----------------------------------------------------------------------===//
// GlobalValue Reference/Resolution Routines.
//===----------------------------------------------------------------------===//
static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
// The used global type does not matter. We will later RAUW it with a
// global/function of the correct type.
return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
GlobalValue::ExternalWeakLinkage, nullptr, "",
nullptr, GlobalVariable::NotThreadLocal,
PTy->getAddressSpace());
}
Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
Value *Val) {
Type *ValTy = Val->getType();
if (ValTy == Ty)
return Val;
if (Ty->isLabelTy())
error(Loc, "'" + Name + "' is not a basic block");
else
error(Loc, "'" + Name + "' defined with type '" +
getTypeString(Val->getType()) + "' but expected '" +
getTypeString(Ty) + "'");
return nullptr;
}
/// getGlobalVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (!PTy) {
error(Loc, "global variable reference must have pointer type");
return nullptr;
}
// Look this name up in the normal function symbol table.
GlobalValue *Val =
cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
auto I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val)
return cast_or_null<GlobalValue>(
checkValidVariableType(Loc, "@" + Name, Ty, Val));
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (!PTy) {
error(Loc, "global variable reference must have pointer type");
return nullptr;
}
GlobalValue *Val = NumberedVals.get(ID);
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (!Val) {
auto I = ForwardRefValIDs.find(ID);
if (I != ForwardRefValIDs.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val)
return cast_or_null<GlobalValue>(
checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
//===----------------------------------------------------------------------===//
// Comdat Reference/Resolution Routines.
//===----------------------------------------------------------------------===//
Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
// Look this name up in the comdat symbol table.
Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
if (I != ComdatSymTab.end())
return &I->second;
// Otherwise, create a new forward reference for this value and remember it.
Comdat *C = M->getOrInsertComdat(Name);
ForwardRefComdats[Name] = Loc;
return C;
}
//===----------------------------------------------------------------------===//
// Helper Routines.
//===----------------------------------------------------------------------===//
/// parseToken - If the current token has the specified kind, eat it and return
/// success. Otherwise, emit the specified error and return failure.
bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
if (Lex.getKind() != T)
return tokError(ErrMsg);
Lex.Lex();
return false;
}
/// parseStringConstant
/// ::= StringConstant
bool LLParser::parseStringConstant(std::string &Result) {
if (Lex.getKind() != lltok::StringConstant)
return tokError("expected string constant");
Result = Lex.getStrVal();
Lex.Lex();
return false;
}
/// parseUInt32
/// ::= uint32
bool LLParser::parseUInt32(uint32_t &Val) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return tokError("expected integer");
uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
if (Val64 != unsigned(Val64))
return tokError("expected 32-bit integer (too large)");
Val = Val64;
Lex.Lex();
return false;
}
/// parseUInt64
/// ::= uint64
bool LLParser::parseUInt64(uint64_t &Val) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return tokError("expected integer");
Val = Lex.getAPSIntVal().getLimitedValue();
Lex.Lex();
return false;
}
/// parseTLSModel
/// := 'localdynamic'
/// := 'initialexec'
/// := 'localexec'
bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
switch (Lex.getKind()) {
default:
return tokError("expected localdynamic, initialexec or localexec");
case lltok::kw_localdynamic:
TLM = GlobalVariable::LocalDynamicTLSModel;
break;
case lltok::kw_initialexec:
TLM = GlobalVariable::InitialExecTLSModel;
break;
case lltok::kw_localexec:
TLM = GlobalVariable::LocalExecTLSModel;
break;
}
Lex.Lex();
return false;
}
/// parseOptionalThreadLocal
/// := /*empty*/
/// := 'thread_local'
/// := 'thread_local' '(' tlsmodel ')'
bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
TLM = GlobalVariable::NotThreadLocal;
if (!EatIfPresent(lltok::kw_thread_local))
return false;
TLM = GlobalVariable::GeneralDynamicTLSModel;
if (Lex.getKind() == lltok::lparen) {
Lex.Lex();
return parseTLSModel(TLM) ||
parseToken(lltok::rparen, "expected ')' after thread local model");
}
return false;
}
/// parseOptionalAddrSpace
/// := /*empty*/
/// := 'addrspace' '(' uint32 ')'
bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
AddrSpace = DefaultAS;
if (!EatIfPresent(lltok::kw_addrspace))
return false;
auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
if (Lex.getKind() == lltok::StringConstant) {
auto AddrSpaceStr = Lex.getStrVal();
if (AddrSpaceStr == "A") {
AddrSpace = M->getDataLayout().getAllocaAddrSpace();
} else if (AddrSpaceStr == "G") {
AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
} else if (AddrSpaceStr == "P") {
AddrSpace = M->getDataLayout().getProgramAddressSpace();
} else {
return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
}
Lex.Lex();
return false;
}
if (Lex.getKind() != lltok::APSInt)
return tokError("expected integer or string constant");
SMLoc Loc = Lex.getLoc();
if (parseUInt32(AddrSpace))
return true;
if (!isUInt<24>(AddrSpace))
return error(Loc, "invalid address space, must be a 24-bit integer");
return false;
};
return parseToken(lltok::lparen, "expected '(' in address space") ||
ParseAddrspaceValue(AddrSpace) ||
parseToken(lltok::rparen, "expected ')' in address space");
}
/// parseStringAttribute
/// := StringConstant
/// := StringConstant '=' StringConstant
bool LLParser::parseStringAttribute(AttrBuilder &B) {
std::string Attr = Lex.getStrVal();
Lex.Lex();
std::string Val;
if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
return true;
B.addAttribute(Attr, Val);
return false;
}
/// Parse a potentially empty list of parameter or return attributes.
bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
bool HaveError = false;
B.clear();
while (true) {
lltok::Kind Token = Lex.getKind();
if (Token == lltok::StringConstant) {
if (parseStringAttribute(B))
return true;
continue;
}
SMLoc Loc = Lex.getLoc();
Attribute::AttrKind Attr = tokenToAttribute(Token);
if (Attr == Attribute::None)
return HaveError;
if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
return true;
if (IsParam && !Attribute::canUseAsParamAttr(Attr))
HaveError |= error(Loc, "this attribute does not apply to parameters");
if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
HaveError |= error(Loc, "this attribute does not apply to return values");
}
}
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
HasLinkage = true;
switch (Kind) {
default:
HasLinkage = false;
return GlobalValue::ExternalLinkage;
case lltok::kw_private:
return GlobalValue::PrivateLinkage;
case lltok::kw_internal:
return GlobalValue::InternalLinkage;
case lltok::kw_weak:
return GlobalValue::WeakAnyLinkage;
case lltok::kw_weak_odr:
return GlobalValue::WeakODRLinkage;
case lltok::kw_linkonce:
return GlobalValue::LinkOnceAnyLinkage;
case lltok::kw_linkonce_odr:
return GlobalValue::LinkOnceODRLinkage;
case lltok::kw_available_externally:
return GlobalValue::AvailableExternallyLinkage;
case lltok::kw_appending:
return GlobalValue::AppendingLinkage;
case lltok::kw_common:
return GlobalValue::CommonLinkage;
case lltok::kw_extern_weak:
return GlobalValue::ExternalWeakLinkage;
case lltok::kw_external:
return GlobalValue::ExternalLinkage;
}
}
/// parseOptionalLinkage
/// ::= /*empty*/
/// ::= 'private'
/// ::= 'internal'
/// ::= 'weak'
/// ::= 'weak_odr'
/// ::= 'linkonce'
/// ::= 'linkonce_odr'
/// ::= 'available_externally'
/// ::= 'appending'
/// ::= 'common'
/// ::= 'extern_weak'
/// ::= 'external'
bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
unsigned &Visibility,
unsigned &DLLStorageClass, bool &DSOLocal) {
Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
if (HasLinkage)
Lex.Lex();
parseOptionalDSOLocal(DSOLocal);
parseOptionalVisibility(Visibility);
parseOptionalDLLStorageClass(DLLStorageClass);
if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
}
return false;
}
void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
switch (Lex.getKind()) {
default:
DSOLocal = false;
break;
case lltok::kw_dso_local:
DSOLocal = true;
Lex.Lex();
break;
case lltok::kw_dso_preemptable:
DSOLocal = false;
Lex.Lex();
break;
}
}
/// parseOptionalVisibility
/// ::= /*empty*/
/// ::= 'default'
/// ::= 'hidden'
/// ::= 'protected'
///
void LLParser::parseOptionalVisibility(unsigned &Res) {
switch (Lex.getKind()) {
default:
Res = GlobalValue::DefaultVisibility;
return;
case lltok::kw_default:
Res = GlobalValue::DefaultVisibility;
break;
case lltok::kw_hidden:
Res = GlobalValue::HiddenVisibility;
break;
case lltok::kw_protected:
Res = GlobalValue::ProtectedVisibility;
break;
}
Lex.Lex();
}
bool LLParser::parseOptionalImportType(lltok::Kind Kind,
GlobalValueSummary::ImportKind &Res) {
switch (Kind) {
default:
return tokError("unknown import kind. Expect definition or declaration.");
case lltok::kw_definition:
Res = GlobalValueSummary::Definition;
return false;
case lltok::kw_declaration:
Res = GlobalValueSummary::Declaration;
return false;
}
}
/// parseOptionalDLLStorageClass
/// ::= /*empty*/
/// ::= 'dllimport'
/// ::= 'dllexport'
///
void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
switch (Lex.getKind()) {
default:
Res = GlobalValue::DefaultStorageClass;
return;
case lltok::kw_dllimport:
Res = GlobalValue::DLLImportStorageClass;
break;
case lltok::kw_dllexport:
Res = GlobalValue::DLLExportStorageClass;
break;
}
Lex.Lex();
}
/// parseOptionalCallingConv
/// ::= /*empty*/
/// ::= 'ccc'
/// ::= 'fastcc'
/// ::= 'intel_ocl_bicc'
/// ::= 'coldcc'
/// ::= 'cfguard_checkcc'
/// ::= 'x86_stdcallcc'
/// ::= 'x86_fastcallcc'
/// ::= 'x86_thiscallcc'
/// ::= 'x86_vectorcallcc'
/// ::= 'arm_apcscc'
/// ::= 'arm_aapcscc'
/// ::= 'arm_aapcs_vfpcc'
/// ::= 'aarch64_vector_pcs'
/// ::= 'aarch64_sve_vector_pcs'
/// ::= 'aarch64_sme_preservemost_from_x0'
/// ::= 'aarch64_sme_preservemost_from_x2'
/// ::= 'msp430_intrcc'
/// ::= 'avr_intrcc'
/// ::= 'avr_signalcc'
/// ::= 'ptx_kernel'
/// ::= 'ptx_device'
/// ::= 'spir_func'
/// ::= 'spir_kernel'
/// ::= 'x86_64_sysvcc'
/// ::= 'win64cc'
/// ::= 'anyregcc'
/// ::= 'preserve_mostcc'
/// ::= 'preserve_allcc'
/// ::= 'preserve_nonecc'
/// ::= 'ghccc'
/// ::= 'swiftcc'
/// ::= 'swifttailcc'
/// ::= 'x86_intrcc'
/// ::= 'hhvmcc'
/// ::= 'hhvm_ccc'
/// ::= 'cxx_fast_tlscc'
/// ::= 'amdgpu_vs'
/// ::= 'amdgpu_ls'
/// ::= 'amdgpu_hs'
/// ::= 'amdgpu_es'
/// ::= 'amdgpu_gs'
/// ::= 'amdgpu_ps'
/// ::= 'amdgpu_cs'
/// ::= 'amdgpu_cs_chain'
/// ::= 'amdgpu_cs_chain_preserve'
/// ::= 'amdgpu_kernel'
/// ::= 'tailcc'
/// ::= 'm68k_rtdcc'
/// ::= 'graalcc'
/// ::= 'riscv_vector_cc'
/// ::= 'cc' UINT
///
bool LLParser::parseOptionalCallingConv(unsigned &CC) {
switch (Lex.getKind()) {
default: CC = CallingConv::C; return false;
case lltok::kw_ccc: CC = CallingConv::C; break;
case lltok::kw_fastcc: CC = CallingConv::Fast; break;
case lltok::kw_coldcc: CC = CallingConv::Cold; break;
case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
case lltok::kw_aarch64_sve_vector_pcs:
CC = CallingConv::AArch64_SVE_VectorCall;
break;
case lltok::kw_aarch64_sme_preservemost_from_x0:
CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;
break;
case lltok::kw_aarch64_sme_preservemost_from_x2:
CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;
break;
case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
case lltok::kw_win64cc: CC = CallingConv::Win64; break;
case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
case lltok::kw_preserve_nonecc:CC = CallingConv::PreserveNone; break;
case lltok::kw_ghccc: CC = CallingConv::GHC; break;
case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
case lltok::kw_hhvmcc:
CC = CallingConv::DUMMY_HHVM;
break;
case lltok::kw_hhvm_ccc:
CC = CallingConv::DUMMY_HHVM_C;
break;
case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
case lltok::kw_amdgpu_cs_chain:
CC = CallingConv::AMDGPU_CS_Chain;
break;
case lltok::kw_amdgpu_cs_chain_preserve:
CC = CallingConv::AMDGPU_CS_ChainPreserve;
break;
case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
case lltok::kw_tailcc: CC = CallingConv::Tail; break;
case lltok::kw_m68k_rtdcc: CC = CallingConv::M68k_RTD; break;
case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
case lltok::kw_riscv_vector_cc:
CC = CallingConv::RISCV_VectorCall;
break;
case lltok::kw_cc: {
Lex.Lex();
return parseUInt32(CC);
}
}
Lex.Lex();
return false;
}
/// parseMetadataAttachment
/// ::= !dbg !42
bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
std::string Name = Lex.getStrVal();
Kind = M->getMDKindID(Name);
Lex.Lex();
return parseMDNode(MD);
}
/// parseInstructionMetadata
/// ::= !dbg !42 (',' !dbg !57)*
bool LLParser::parseInstructionMetadata(Instruction &Inst) {
do {
if (Lex.getKind() != lltok::MetadataVar)
return tokError("expected metadata after comma");
unsigned MDK;
MDNode *N;
if (parseMetadataAttachment(MDK, N))
return true;
if (MDK == LLVMContext::MD_DIAssignID)
TempDIAssignIDAttachments[N].push_back(&Inst);
else
Inst.setMetadata(MDK, N);
if (MDK == LLVMContext::MD_tbaa)
InstsWithTBAATag.push_back(&Inst);
// If this is the end of the list, we're done.
} while (EatIfPresent(lltok::comma));
return false;
}
/// parseGlobalObjectMetadataAttachment
/// ::= !dbg !57
bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
unsigned MDK;
MDNode *N;
if (parseMetadataAttachment(MDK, N))
return true;
GO.addMetadata(MDK, *N);
return false;
}
/// parseOptionalFunctionMetadata
/// ::= (!dbg !57)*
bool LLParser::parseOptionalFunctionMetadata(Function &F) {
while (Lex.getKind() == lltok::MetadataVar)
if (parseGlobalObjectMetadataAttachment(F))
return true;
return false;
}
/// parseOptionalAlignment
/// ::= /* empty */
/// ::= 'align' 4
bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
Alignment = std::nullopt;
if (!EatIfPresent(lltok::kw_align))
return false;
LocTy AlignLoc = Lex.getLoc();
uint64_t Value = 0;
LocTy ParenLoc = Lex.getLoc();
bool HaveParens = false;
if (AllowParens) {
if (EatIfPresent(lltok::lparen))
HaveParens = true;
}
if (parseUInt64(Value))
return true;
if (HaveParens && !EatIfPresent(lltok::rparen))
return error(ParenLoc, "expected ')'");
if (!isPowerOf2_64(Value))
return error(AlignLoc, "alignment is not a power of two");
if (Value > Value::MaximumAlignment)
return error(AlignLoc, "huge alignments are not supported yet");
Alignment = Align(Value);
return false;
}
/// parseOptionalCodeModel
/// ::= /* empty */
/// ::= 'code_model' "large"
bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
Lex.Lex();
auto StrVal = Lex.getStrVal();
auto ErrMsg = "expected global code model string";
if (StrVal == "tiny")
model = CodeModel::Tiny;
else if (StrVal == "small")
model = CodeModel::Small;
else if (StrVal == "kernel")
model = CodeModel::Kernel;
else if (StrVal == "medium")
model = CodeModel::Medium;
else if (StrVal == "large")
model = CodeModel::Large;
else
return tokError(ErrMsg);
if (parseToken(lltok::StringConstant, ErrMsg))
return true;
return false;
}
/// parseOptionalDerefAttrBytes
/// ::= /* empty */
/// ::= AttrKind '(' 4 ')'
///
/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
uint64_t &Bytes) {
assert((AttrKind == lltok::kw_dereferenceable ||
AttrKind == lltok::kw_dereferenceable_or_null) &&
"contract!");
Bytes = 0;
if (!EatIfPresent(AttrKind))
return false;
LocTy ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(ParenLoc, "expected '('");
LocTy DerefLoc = Lex.getLoc();
if (parseUInt64(Bytes))
return true;
ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(ParenLoc, "expected ')'");
if (!Bytes)
return error(DerefLoc, "dereferenceable bytes must be non-zero");
return false;
}
bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
Lex.Lex();
Kind = UWTableKind::Default;
if (!EatIfPresent(lltok::lparen))
return false;
LocTy KindLoc = Lex.getLoc();
if (Lex.getKind() == lltok::kw_sync)
Kind = UWTableKind::Sync;
else if (Lex.getKind() == lltok::kw_async)
Kind = UWTableKind::Async;
else
return error(KindLoc, "expected unwind table kind");
Lex.Lex();
return parseToken(lltok::rparen, "expected ')'");
}
bool LLParser::parseAllocKind(AllocFnKind &Kind) {
Lex.Lex();
LocTy ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(ParenLoc, "expected '('");
LocTy KindLoc = Lex.getLoc();
std::string Arg;
if (parseStringConstant(Arg))
return error(KindLoc, "expected allockind value");
for (StringRef A : llvm::split(Arg, ",")) {
if (A == "alloc") {
Kind |= AllocFnKind::Alloc;
} else if (A == "realloc") {
Kind |= AllocFnKind::Realloc;
} else if (A == "free") {
Kind |= AllocFnKind::Free;
} else if (A == "uninitialized") {
Kind |= AllocFnKind::Uninitialized;
} else if (A == "zeroed") {
Kind |= AllocFnKind::Zeroed;
} else if (A == "aligned") {
Kind |= AllocFnKind::Aligned;
} else {
return error(KindLoc, Twine("unknown allockind ") + A);
}
}
ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(ParenLoc, "expected ')'");
if (Kind == AllocFnKind::Unknown)
return error(KindLoc, "expected allockind value");
return false;
}
static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
switch (Tok) {
case lltok::kw_argmem:
return IRMemLocation::ArgMem;
case lltok::kw_inaccessiblemem:
return IRMemLocation::InaccessibleMem;
default:
return std::nullopt;
}
}
static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
switch (Tok) {
case lltok::kw_none:
return ModRefInfo::NoModRef;
case lltok::kw_read:
return ModRefInfo::Ref;
case lltok::kw_write:
return ModRefInfo::Mod;
case lltok::kw_readwrite:
return ModRefInfo::ModRef;
default:
return std::nullopt;
}
}
std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
MemoryEffects ME = MemoryEffects::none();
// We use syntax like memory(argmem: read), so the colon should not be
// interpreted as a label terminator.
Lex.setIgnoreColonInIdentifiers(true);
auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
Lex.Lex();
if (!EatIfPresent(lltok::lparen)) {
tokError("expected '('");
return std::nullopt;
}
bool SeenLoc = false;
do {
std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
if (Loc) {
Lex.Lex();
if (!EatIfPresent(lltok::colon)) {
tokError("expected ':' after location");
return std::nullopt;
}
}
std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
if (!MR) {
if (!Loc)
tokError("expected memory location (argmem, inaccessiblemem) "
"or access kind (none, read, write, readwrite)");
else
tokError("expected access kind (none, read, write, readwrite)");
return std::nullopt;
}
Lex.Lex();
if (Loc) {
SeenLoc = true;
ME = ME.getWithModRef(*Loc, *MR);
} else {
if (SeenLoc) {
tokError("default access kind must be specified first");
return std::nullopt;
}
ME = MemoryEffects(*MR);
}
if (EatIfPresent(lltok::rparen))
return ME;
} while (EatIfPresent(lltok::comma));
tokError("unterminated memory attribute");
return std::nullopt;
}
static unsigned keywordToFPClassTest(lltok::Kind Tok) {
switch (Tok) {
case lltok::kw_all:
return fcAllFlags;
case lltok::kw_nan:
return fcNan;
case lltok::kw_snan:
return fcSNan;
case lltok::kw_qnan:
return fcQNan;
case lltok::kw_inf:
return fcInf;
case lltok::kw_ninf:
return fcNegInf;
case lltok::kw_pinf:
return fcPosInf;
case lltok::kw_norm:
return fcNormal;
case lltok::kw_nnorm:
return fcNegNormal;
case lltok::kw_pnorm:
return fcPosNormal;
case lltok::kw_sub:
return fcSubnormal;
case lltok::kw_nsub:
return fcNegSubnormal;
case lltok::kw_psub:
return fcPosSubnormal;
case lltok::kw_zero:
return fcZero;
case lltok::kw_nzero:
return fcNegZero;
case lltok::kw_pzero:
return fcPosZero;
default:
return 0;
}
}
unsigned LLParser::parseNoFPClassAttr() {
unsigned Mask = fcNone;
Lex.Lex();
if (!EatIfPresent(lltok::lparen)) {
tokError("expected '('");
return 0;
}
do {
uint64_t Value = 0;
unsigned TestMask = keywordToFPClassTest(Lex.getKind());
if (TestMask != 0) {
Mask |= TestMask;
// TODO: Disallow overlapping masks to avoid copy paste errors
} else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
!parseUInt64(Value)) {
if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
return 0;
}
if (!EatIfPresent(lltok::rparen)) {
error(Lex.getLoc(), "expected ')'");
return 0;
}
return Value;
} else {
error(Lex.getLoc(), "expected nofpclass test mask");
return 0;
}
Lex.Lex();
if (EatIfPresent(lltok::rparen))
return Mask;
} while (1);
llvm_unreachable("unterminated nofpclass attribute");
}
/// parseOptionalCommaAlign
/// ::=
/// ::= ',' align 4
///
/// This returns with AteExtraComma set to true if it ate an excess comma at the
/// end.
bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
bool &AteExtraComma) {
AteExtraComma = false;
while (EatIfPresent(lltok::comma)) {
// Metadata at the end is an early exit.
if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
return false;
}
if (Lex.getKind() != lltok::kw_align)
return error(Lex.getLoc(), "expected metadata or 'align'");
if (parseOptionalAlignment(Alignment))
return true;
}
return false;
}
/// parseOptionalCommaAddrSpace
/// ::=
/// ::= ',' addrspace(1)
///
/// This returns with AteExtraComma set to true if it ate an excess comma at the
/// end.
bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
bool &AteExtraComma) {
AteExtraComma = false;
while (EatIfPresent(lltok::comma)) {
// Metadata at the end is an early exit.
if (Lex.getKind() == lltok::MetadataVar) {
AteExtraComma = true;
return false;
}
Loc = Lex.getLoc();
if (Lex.getKind() != lltok::kw_addrspace)
return error(Lex.getLoc(), "expected metadata or 'addrspace'");
if (parseOptionalAddrSpace(AddrSpace))
return true;
}
return false;
}
bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
std::optional<unsigned> &HowManyArg) {
Lex.Lex();
auto StartParen = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(StartParen, "expected '('");
if (parseUInt32(BaseSizeArg))
return true;
if (EatIfPresent(lltok::comma)) {
auto HowManyAt = Lex.getLoc();
unsigned HowMany;
if (parseUInt32(HowMany))
return true;
if (HowMany == BaseSizeArg)
return error(HowManyAt,
"'allocsize' indices can't refer to the same parameter");
HowManyArg = HowMany;
} else
HowManyArg = std::nullopt;
auto EndParen = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(EndParen, "expected ')'");
return false;
}
bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
unsigned &MaxValue) {
Lex.Lex();
auto StartParen = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(StartParen, "expected '('");
if (parseUInt32(MinValue))
return true;
if (EatIfPresent(lltok::comma)) {
if (parseUInt32(MaxValue))
return true;
} else
MaxValue = MinValue;
auto EndParen = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(EndParen, "expected ')'");
return false;
}
/// parseScopeAndOrdering
/// if isAtomic: ::= SyncScope? AtomicOrdering
/// else: ::=
///
/// This sets Scope and Ordering to the parsed values.
bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
AtomicOrdering &Ordering) {
if (!IsAtomic)
return false;
return parseScope(SSID) || parseOrdering(Ordering);
}
/// parseScope
/// ::= syncscope("singlethread" | "<target scope>")?
///
/// This sets synchronization scope ID to the ID of the parsed value.
bool LLParser::parseScope(SyncScope::ID &SSID) {
SSID = SyncScope::System;
if (EatIfPresent(lltok::kw_syncscope)) {
auto StartParenAt = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(StartParenAt, "Expected '(' in syncscope");
std::string SSN;
auto SSNAt = Lex.getLoc();
if (parseStringConstant(SSN))
return error(SSNAt, "Expected synchronization scope name");
auto EndParenAt = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(EndParenAt, "Expected ')' in syncscope");
SSID = Context.getOrInsertSyncScopeID(SSN);
}
return false;
}
/// parseOrdering
/// ::= AtomicOrdering
///
/// This sets Ordering to the parsed value.
bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
switch (Lex.getKind()) {
default:
return tokError("Expected ordering on atomic instruction");
case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
// Not specified yet:
// case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
case lltok::kw_seq_cst:
Ordering = AtomicOrdering::SequentiallyConsistent;
break;
}
Lex.Lex();
return false;
}
/// parseOptionalStackAlignment
/// ::= /* empty */
/// ::= 'alignstack' '(' 4 ')'
bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
Alignment = 0;
if (!EatIfPresent(lltok::kw_alignstack))
return false;
LocTy ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::lparen))
return error(ParenLoc, "expected '('");
LocTy AlignLoc = Lex.getLoc();
if (parseUInt32(Alignment))
return true;
ParenLoc = Lex.getLoc();
if (!EatIfPresent(lltok::rparen))
return error(ParenLoc, "expected ')'");
if (!isPowerOf2_32(Alignment))
return error(AlignLoc, "stack alignment is not a power of two");
return false;