1//===---- GlobalMergeFunctions.cpp - Global merge functions -------*- C++ -===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//===----------------------------------------------------------------------===//
9// This pass implements the global merge function pass.
11//===----------------------------------------------------------------------===//
25 #define DEBUG_TYPE "global-merge-func"
32 cl::desc(
"Disable codegen data for function merging. Local "
33 "merging is still enabled within a module."),
37 "Number of functions that are actually merged using function hash");
38 STATISTIC(NumAnalyzedModues,
"Number of modules that are analyzed");
39 STATISTIC(NumAnalyzedFunctions,
"Number of functions that are analyzed");
40 STATISTIC(NumEligibleFunctions,
"Number of functions that are eligible");
42/// Returns true if the \OpIdx operand of \p CI is the callee operand.
55 if (Callee->isIntrinsic())
57 auto Name = Callee->getName();
58 // objc_msgSend stubs must be called, and can't have their address taken.
59 if (Name.starts_with(
"objc_msgSend$"))
61 // Calls to dtrace probes must generate unique patchpoints.
62 if (Name.starts_with(
"__dtrace"))
66 // The operand is the callee and it has already been signed. Ignore this
67 // because we cannot add another ptrauth bundle to the call instruction.
71 // The target of the arc-attached call must be a constant and cannot be
80/// Returns true if function \p F is eligible for merging.
82 if (
F->isDeclaration())
85 if (
F->hasFnAttribute(llvm::Attribute::NoMerge) ||
86 F->hasFnAttribute(llvm::Attribute::AlwaysInline))
89 if (
F->hasAvailableExternallyLinkage())
92 if (
F->getFunctionType()->isVarArg())
98 // Unnamed functions are skipped for simplicity.
102 // If function contains callsites with musttail, if we merge
103 // it, the merged function will have the musttail callsite, but
104 // the number of parameters can change, thus the parameter count
105 // of the callsite will mismatch with the function itself.
109 if (CB && CB->isMustTailCall())
118 switch (
I->getOpcode()) {
119 case Instruction::Load:
120 case Instruction::Store:
121 case Instruction::Call:
122 case Instruction::Invoke:
129// This function takes an instruction, \p I, and an operand index, \p OpIdx.
130// It returns true if the operand should be ignored in the hash computation.
131// If \p OpIdx is out of range based on the other instruction context, it cannot
134 if (
OpIdx >=
I->getNumOperands())
152 ++NumAnalyzedFunctions;
154 ++NumEligibleFunctions;
158 // Convert the operand map to a vector for a serialization-friendly
161 for (
auto &Pair : *FI.IndexOperandHashMap)
165 M.getModuleIdentifier(), FI.IndexInstruction->size(),
166 std::move(IndexOperandHashes));
168 LocalFunctionMap->insert(SF);
173/// Tuple to hold function info to process merging.
183// Given the func info, and the parameterized locations, create and return
184// a new merged function by replacing the original constants with the new
189 // Synthesize a new merged function name by appending ".Tgm" to the root
191 auto *MergedFunc = FI.
F;
192 std::string NewFunctionName =
194 auto *M = MergedFunc->getParent();
195 assert(!M->getFunction(NewFunctionName));
198 // Get the original params' types.
200 // Append const parameter types that are passed in.
201 ParamTypes.
append(ConstParamTypes.
begin(), ConstParamTypes.
end());
203 ParamTypes,
/*isVarArg=*/false);
205 // Declare a new function
208 if (
auto *SP = MergedFunc->getSubprogram())
214 NewFunction->
addFnAttr(Attribute::NoInline);
216 // Add the new function before the root function.
217 M->getFunctionList().insert(MergedFunc->getIterator(), NewFunction);
219 // Move the body of MergedFunc into the NewFunction.
220 NewFunction->
splice(NewFunction->
begin(), MergedFunc);
222 // Update the original args by the new args.
223 auto NewArgIter = NewFunction->
arg_begin();
224 for (
Argument &OrigArg : MergedFunc->args()) {
229 // Replace the original Constants by the new args.
230 unsigned NumOrigArgs = MergedFunc->arg_size();
231 for (
unsigned ParamIdx = 0; ParamIdx < ParamLocsVec.
size(); ++ParamIdx) {
233 for (
auto [InstIndex, OpndIndex] : ParamLocsVec[ParamIdx]) {
236 if (OrigC->getType() != NewArg->
getType()) {
237 IRBuilder<> Builder(Inst->getParent(), Inst->getIterator());
238 Inst->setOperand(OpndIndex,
239 Builder.CreateAggregateCast(NewArg, OrigC->
getType()));
241 Inst->setOperand(OpndIndex, NewArg);
249// Given the original function (Thunk) and the merged function (ToFunc), create
250// a thunk to the merged function.
257 Thunk->dropAllReferences();
263 unsigned ParamIdx = 0;
266 // Add arguments which are passed through Thunk.
267 for (
Argument &AI : Thunk->args()) {
269 Builder.CreateAggregateCast(&AI, ToFuncTy->getParamType(ParamIdx)));
273 // Add new arguments defined by Params.
274 for (
auto *Param : Params) {
275 assert(ParamIdx < ToFuncTy->getNumParams());
277 Builder.CreateAggregateCast(Param, ToFuncTy->getParamType(ParamIdx)));
281 CallInst *CI = Builder.CreateCall(ToFunc, Args);
288 if (Thunk->getReturnType()->isVoidTy())
289 Builder.CreateRetVoid();
291 Builder.CreateRet(Builder.CreateAggregateCast(CI, Thunk->getReturnType()));
294// Check if the old merged/optimized IndexOperandHashMap is compatible with
295// the current IndexOperandHashMap. An operand hash may not be stable across
296// different builds due to varying modules combined. To address this, we relax
297// the hash check condition by comparing Const hash patterns instead of absolute
298// hash values. For example, let's assume we have three Consts located at idx1,
299// idx3, and idx6, where their corresponding hashes are hash1, hash2, and hash1
300// in the old merged map below:
301// Old (Merged): [(idx1, hash1), (idx3, hash2), (idx6, hash1)]
302// Current: [(idx1, hash1'), (idx3, hash2'), (idx6, hash1')]
303// If the current function also has three Consts in the same locations,
304// with hash sequences hash1', hash2', and hash1' where the first and third
305// are the same as the old hash sequences, we consider them matched.
311 for (
const auto &[Index, OldHash] : OldInstOpndIndexToConstHash) {
312 auto It = CurrInstOpndIndexToConstHash.
find(Index);
313 if (It == CurrInstOpndIndexToConstHash.
end())
316 auto CurrHash = It->second;
317 auto J = OldHashToCurrHash.
find(OldHash);
318 if (J == OldHashToCurrHash.
end())
319 OldHashToCurrHash.
insert({OldHash, CurrHash});
320 else if (J->second != CurrHash)
327// Validate the locations pointed by a param has the same hash and Constant.
333 std::optional<stable_hash> OldHash;
334 std::optional<Constant *> OldConst;
338 auto [InstIndex, OpndIndex] =
Loc;
340 const auto *Inst = IndexInstruction.
lookup(InstIndex);
344 OldConst = CurrConst;
345 }
else if (CurrConst != *OldConst || CurrHash != *OldHash) {
355 std::map<std::vector<stable_hash>,
ParamLocs> HashSeqToLocs;
357 unsigned StableFunctionCount = SFS.
size();
359 for (
auto &[
IndexPair, Hash] : *RSF.IndexOperandHashMap) {
360 // Const hash sequence across stable functions.
361 // We will allocate a parameter per unique hash squence.
362 // can't use SmallVector as key
363 std::vector<stable_hash> ConstHashSeq;
364 ConstHashSeq.push_back(Hash);
365 bool Identical =
true;
366 for (
unsigned J = 1; J < StableFunctionCount; ++J) {
368 auto SHash = SF->IndexOperandHashMap->at(
IndexPair);
371 ConstHashSeq.push_back(SHash);
377 // For each unique Const hash sequence (parameter), add the locations.
378 HashSeqToLocs[ConstHashSeq].push_back(
IndexPair);
382 for (
auto &[HashSeq, Locs] : HashSeqToLocs)
395 // Collect stable functions related to the current module.
402 if (FunctionMap->
contains(FI.FunctionHash))
403 HashToFuncs[FI.FunctionHash].emplace_back(&
F, std::move(FI));
406 for (
auto &[Hash, Funcs] : HashToFuncs) {
407 std::optional<ParamLocsVecTy> ParamLocsVec;
409 auto &SFS = FunctionMap->
at(Hash);
413 // Iterate functions with the same hash.
414 for (
auto &[
F, FI] : Funcs) {
415 // Check if the function is compatible with any stable function
416 // in terms of the number of instructions and ignored operands.
417 if (RFS->InstCount != FI.IndexInstruction->size())
423 auto [InstIndex, OpndIndex] = Index;
424 assert(InstIndex < FHI.IndexInstruction->
size());
425 auto *Inst = FHI.IndexInstruction->lookup(InstIndex);
431 if (!hasValidSharedConst(RFS.get(), FI))
434 for (
auto &SF : SFS) {
436 assert(hasValidSharedConst(SF.get(), FI));
437 // Check if there is any stable function that is compatiable with the
440 *FI.IndexOperandHashMap))
442 if (!ParamLocsVec.has_value()) {
445 <<
" with Params " << ParamLocsVec->size() <<
"\n");
451 // If a stable function matching the current one is found,
452 // create a candidate for merging and proceed to the next function.
453 FuncMergeInfos.
emplace_back(SF.get(),
F, FI.IndexInstruction.get());
457 unsigned FuncMergeInfoSize = FuncMergeInfos.
size();
458 if (FuncMergeInfoSize == 0)
462 << FuncMergeInfoSize <<
" for hash: " << Hash <<
"\n");
464 for (
auto &FMI : FuncMergeInfos) {
467 // We've already validated all locations of constant operands pointed by
468 // the parameters. Populate parameters pointing to the original constants.
473 auto &[InstIndex, OpndIndex] =
ParamLocs[0];
474 auto *Inst = FMI.IndexInstruction->lookup(InstIndex);
480 // Create a merged function derived from the current function.
485 dbgs() <<
"[GlobalMergeFunc] Merged function (hash:" << FMI.SF->Hash
486 <<
") " << MergedFunc->
getName() <<
" generated from "
487 << FMI.F->getName() <<
":\n";
491 // Transform the current function into a thunk that calls the merged
495 dbgs() <<
"[GlobalMergeFunc] Thunk generated: \n";
498 ++NumMergedFunctions;
506 // Initialize the local function map regardless of the merger mode.
507 LocalFunctionMap = std::make_unique<StableFunctionMap>();
509 // Disable codegen data for merging. The local merge is still enabled.
513 // (Full)LTO module does not have functions added to the index.
514 // In this case, we run a local merger without using codegen data.
515 if (Index && !Index->hasExportedFunctions(M))
525 LLVM_DEBUG(
dbgs() <<
"Emit function map. Size: " << LocalFunctionMap->size()
527 // No need to emit the function map if it is empty.
528 if (LocalFunctionMap->empty())
533 std::vector<CGDataPatchItem> PatchItems;
536 COS.
patch(PatchItems);
539 OS.
str(),
"in-memory stable function map",
false);
541 Triple TT(M.getTargetTriple());
552 // Use the prior CG data to optimistically create global merge candidates.
556 // Emit the local function map to the custom section, __llvm_merge before
560 LocalFunctionMap->finalize();
561 FuncMap = LocalFunctionMap.get();
564 return merge(M, FuncMap);
569class GlobalMergeFuncPassWrapper :
public ModulePass {
574 GlobalMergeFuncPassWrapper();
582 StringRef getPassName()
const override {
return "Global Merge Functions"; }
584 bool runOnModule(
Module &M)
override;
589char GlobalMergeFuncPassWrapper::ID = 0;
591 "Global merge function pass",
false,
false)
594 return new GlobalMergeFuncPassWrapper();
597GlobalMergeFuncPassWrapper::GlobalMergeFuncPassWrapper() :
ModulePass(
ID) {
602bool GlobalMergeFuncPassWrapper::runOnModule(
Module &M) {
603 const ModuleSummaryIndex *
Index =
nullptr;
604 if (
auto *IndexWrapperPass =
605 getAnalysisIfAvailable<ImmutableModuleSummaryIndexWrapperPass>())
606 Index = IndexWrapperPass->getIndex();
608 return GlobalMergeFunc(Index).run(M);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool checkConstHashCompatible(const DenseMap< IndexPair, stable_hash > &OldInstOpndIndexToConstHash, const DenseMap< IndexPair, stable_hash > &CurrInstOpndIndexToConstHash)
static ParamLocsVecTy computeParamInfo(const StableFunctionMap::StableFunctionEntries &SFS)
static cl::opt< bool > DisableCGDataForMerging("disable-cgdata-for-merging", cl::Hidden, cl::desc("Disable codegen data for function merging. Local " "merging is still enabled within a module."), cl::init(false))
static bool canParameterizeCallOperand(const CallBase *CI, unsigned OpIdx)
static Function * createMergedFunction(FuncMergeInfo &FI, ArrayRef< Type * > ConstParamTypes, const ParamLocsVecTy &ParamLocsVec)
static void createThunk(FuncMergeInfo &FI, ArrayRef< Constant * > Params, Function *ToFunc)
static bool isEligibleInstructionForConstantSharing(const Instruction *I)
static bool ignoreOp(const Instruction *I, unsigned OpIdx)
bool isEligibleFunction(Function *F)
Returns true if function F is eligible for merging.
static bool checkConstLocationCompatible(const StableFunctionMap::StableFunctionEntry &SF, const IndexInstrMap &IndexInstruction, const ParamLocsVecTy &ParamLocsVec)
static bool isCalleeOperand(const CallBase *CI, unsigned OpIdx)
Returns true if the \OpIdx operand of CI is the callee operand.
Machine Check Debug Module
This is the interface to build a ModuleSummaryIndex for a module.
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A container for analyses that lazily runs them and caches their results.
Represent the analysis usage information of a pass.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
LLVM Basic Block Representation.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
A wrapper class to abstract writer stream with support of bytes back patching.
LLVM_ABI void patch(ArrayRef< CGDataPatchItem > P)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
void setCallingConv(CallingConv::ID CC)
bool isOperandBundleOfType(uint32_t ID, unsigned Idx) const
Return true if the operand at index Idx is a bundle operand that has tag ID ID.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Value * getCalledOperand() const
const Use & getCalledOperandUse() const
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
AttributeList getAttributes() const
Return the attribute list for this Function.
Argument * getArg(unsigned i) const
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
GlobalMergeFunc is a ModulePass that implements a function merging mechanism using stable function ha...
void analyze(Module &M)
Analyze module to create stable function into LocalFunctionMap.
void initializeMergerMode(const Module &M)
bool merge(Module &M, const StableFunctionMap *FunctionMap)
Merge functions in the module using the given function map.
void emitFunctionMap(Module &M)
Emit LocalFunctionMap into __llvm_merge section.
static constexpr char MergingInstanceSuffix[]
The suffix used to identify the merged function that parameterizes the constant values.
void setDLLStorageClass(DLLStorageClassTypes C)
void setLinkage(LinkageTypes LT)
@ InternalLinkage
Rename collisions when linking (static functions).
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Legacy wrapper pass to provide the ModuleSummaryIndex object.
@ OB_clang_arc_attachedcall
ValueT lookup(const KeyT &Key) const
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
std::string str() const
str - Get the contents as an std::string.
Triple - Helper class for working with autoconf configuration names.
const Use & getOperandUse(unsigned i) const
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
bool hasStableFunctionMap()
const StableFunctionMap * getStableFunctionMap()
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI FunctionHashInfo StructuralHashWithDifferences(const Function &F, IgnoreOperandFunc IgnoreOp)
Computes a structural hash of a given function, considering the structure and content of the function...
MapVector< unsigned, Instruction * > IndexInstrMap
A map from an instruction index to an instruction pointer.
LLVM_ABI ModulePass * createGlobalMergeFuncPass()
This pass performs merging similar functions globally.
SmallVector< IndexPairHash > IndexOperandHashVecType
auto dyn_cast_or_null(const Y &Val)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringRef get_stable_name(StringRef Name)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
SmallVector< IndexPair, 4 > ParamLocs
LLVM_ABI void initializeGlobalMergeFuncPassWrapperPass(PassRegistry &)
std::pair< unsigned, unsigned > IndexPair
The pair of an instruction index and a operand index.
SmallVector< ParamLocs, 8 > ParamLocsVecTy
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void embedBufferInModule(Module &M, MemoryBufferRef Buf, StringRef SectionName, Align Alignment=Align(1))
Embed the memory buffer Buf into the module M as a global using the specified section name.
LLVM_ABI std::string getCodeGenDataSectionName(CGDataSectKind CGSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Implement std::hash so that hash_code can be used in STL containers.
Tuple to hold function info to process merging.
FuncMergeInfo(StableFunctionMap::StableFunctionEntry *SF, Function *F, IndexInstrMap *IndexInstruction)
StableFunctionMap::StableFunctionEntry * SF
IndexInstrMap * IndexInstruction
This struct is a compact representation of a valid (non-zero power of two) alignment.
PreservedAnalyses run(Module &M, AnalysisManager< Module > &)
const ModuleSummaryIndex * ImportSummary
static LLVM_ABI void serialize(raw_ostream &OS, const StableFunctionMap *FunctionMap, std::vector< CGDataPatchItem > &PatchItems)
A static helper function to serialize the stable function map without owning the stable function map.
An efficient form of StableFunction for fast look-up.
std::unique_ptr< IndexOperandHashMapType > IndexOperandHashMap
A map from an IndexPair to a stable_hash which was skipped.
unsigned InstCount
The number of instructions.
SmallVector< std::unique_ptr< StableFunctionEntry > > StableFunctionEntries
const StableFunctionEntries & at(HashFuncsMapType::key_type FunctionHash) const
bool contains(HashFuncsMapType::key_type FunctionHash) const
A stable function is a function with a stable hash while tracking the locations of ignored operands a...