40 if (!ExportGV.hasLocalLinkage())
43 auto Name = ExportGV.getName();
45 if (!PromoteExtra.
count(&ExportGV)) {
56 std::string NewName = (
Name + ModuleId).str();
58 if (
const auto *
C = ExportGV.getComdat())
62 ExportGV.setName(NewName);
72 if (!RenamedComdats.
empty())
74 if (
auto *
C = GO.getComdat()) {
75 auto Replacement = RenamedComdats.
find(
C);
76 if (Replacement != RenamedComdats.
end())
77 GO.setComdat(Replacement->second);
88 auto ExternalizeTypeId = [&](
CallInst *CI,
unsigned ArgNo) {
90 cast<MetadataAsValue>(CI->
getArgOperand(ArgNo))->getMetadata();
92 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
93 Metadata *&GlobalMD = LocalToGlobal[MD];
95 std::string NewName = (
Twine(LocalToGlobal.
size()) + ModuleId).str();
106 for (
const Use &U : TypeTestFunc->
uses()) {
107 auto CI = cast<CallInst>(U.getUser());
108 ExternalizeTypeId(CI, 1);
114 for (
const Use &U : TypeCheckedLoadFunc->
uses()) {
115 auto CI = cast<CallInst>(U.getUser());
116 ExternalizeTypeId(CI, 2);
125 for (
auto MD : MDs) {
126 auto I = LocalToGlobal.
find(MD->getOperand(1));
127 if (
I == LocalToGlobal.
end()) {
140 void simplifyExternals(
Module &M) {
176 std::vector<GlobalValue *> V;
178 if (!ShouldKeepDefinition(&GV))
187 if (
auto *F = dyn_cast<Function>(C))
189 if (isa<GlobalValue>(C))
192 forEachVirtualFunction(cast<Constant>(
Op), Fn);
198 void splitAndWriteThinLTOBitcode(
202 if (ModuleId.empty()) {
219 promoteTypeIds(M, ModuleId);
240 std::set<const Function *> EligibleVirtualFns;
245 if (HasTypeMetadata(&GV)) {
250 if (!RT || RT->getBitWidth() > 64 || F->
arg_empty() ||
255 if (!ArgT || ArgT->getBitWidth() > 64)
260 EligibleVirtualFns.insert(F);
265 std::unique_ptr<Module> MergedM(
268 if (MergedMComdats.
count(C))
270 if (
auto *F = dyn_cast<Function>(GV))
271 return EligibleVirtualFns.count(F);
272 if (
auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->
getBaseObject()))
273 return HasTypeMetadata(GVar);
277 MergedM->setModuleInlineAsm(
"");
296 if (
auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->
getBaseObject()))
297 if (HasTypeMetadata(GVar))
300 if (MergedMComdats.
count(C))
305 promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
306 promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
308 auto &Ctx = MergedM->getContext();
310 for (
auto V : CfiFunctions) {
326 for (
auto Type : Types)
331 if(!CfiFunctionMDs.
empty()) {
332 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"cfi.functions");
333 for (
auto MD : CfiFunctionMDs)
338 for (
auto &A : M.aliases()) {
339 if (!isa<Function>(
A.getAliasee()))
342 auto *F = cast<Function>(
A.getAliasee());
356 if (!FunctionAliases.
empty()) {
357 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"aliases");
358 for (
auto MD : FunctionAliases)
372 if (!Symvers.
empty()) {
373 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata(
"symvers");
374 for (
auto MD : Symvers)
378 simplifyExternals(*MergedM);
397 W.writeModule(M,
false, &Index,
399 W.writeModule(*MergedM,
false, &MergedMIndex);
411 W2.writeThinLinkBitcode(M, Index, ModHash);
412 W2.writeModule(*MergedM,
false,
416 *ThinLinkOS << Buffer;
421 bool requiresSplit(
Module &M) {
434 if (requiresSplit(M))
435 return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
448 if (ThinLinkOS && Index)
452 class WriteThinLTOBitcode :
public ModulePass {
460 WriteThinLTOBitcode() :
ModulePass(ID), OS(
dbgs()), ThinLinkOS(nullptr) {
465 :
ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
469 StringRef getPassName()
const override {
return "ThinLTO Bitcode Writer"; }
471 bool runOnModule(
Module &M)
override {
473 &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
488 "Write ThinLTO Bitcode",
false,
true)
497 return new WriteThinLTOBitcode(Str, ThinLinkOS);
504 writeThinLTOBitcode(OS, ThinLinkOS,
void setVisibility(VisibilityTypes V)
const Function & getFunction() const
bool isDeclarationForLinker() const
void push_back(const T &Elt)
ModulePass * createWriteThinLTOBitcodePass(raw_ostream &Str, raw_ostream *ThinLinkOS=nullptr)
Write ThinLTO-ready bitcode to Str.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
iterator_range< use_iterator > uses()
bool hasLocalLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
A Module instance is used to store all the information related to an LLVM module. ...
static MDString * get(LLVMContext &Context, StringRef Str)
This is the interface to build a ModuleSummaryIndex for a module.
Implements a dense probed hash-table based set.
Available for inspection, not emission.
Analysis providing profile information.
void addOperand(MDNode *M)
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
An efficient, type-erasing, non-owning reference to a callable.
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Externally visible function.
block Block Frequency true
MemoryAccessKind computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
Analysis pass to provide the ModuleSummaryIndex object.
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
iterator_range< global_object_iterator > global_objects()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
void setName(const Twine &Name)
Change the name of the value.
void WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out, const ModuleSummaryIndex &Index, const ModuleHash &ModHash)
Write the specified thin link bitcode file (i.e., the minimized bitcode file) to the given raw output...
global_iterator global_begin()
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void setComdat(Comdat *C)
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Type * getReturnType() const
Returns the type of the ret val.
static void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module...
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
A set of analyses that are preserved following a run of a transformation pass.
VisibilityTypes getVisibility() const
write thinlto Write ThinLTO Bitcode
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void setArgOperand(unsigned i, Value *v)
Class to represent integer types.
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
static void write(bool isBE, void *P, T V)
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
global_iterator global_end()
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void initializeWriteThinLTOBitcodePass(PassRegistry &)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const Comdat * getComdat() const
void setPreservesAll()
Set by analyses that do not transform their input at all.
amdgpu Simplify well known AMD library false Value Value * Arg
const Comdat * getComdat() const
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Provides passes for computing function attributes based on interprocedural analyses.
LLVM_NODISCARD bool empty() const
const GlobalObject * getBaseObject() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
LLVM Value Representation.
A vector that has set insertion semantics.
This class implements an extremely fast bulk output stream that can only output to a stream...
iterator_range< global_iterator > globals()
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
This header defines various interfaces for pass management in LLVM.
INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode", "Write ThinLTO Bitcode", false, true) INITIALIZE_PASS_END(WriteThinLTOBitcode
iterator_range< global_value_iterator > global_values()
static IntegerType * getInt8Ty(LLVMContext &C)
PointerType * getType() const
Global values are always pointers.
Legacy wrapper pass to provide the ModuleSummaryIndex object.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...