LLVM 22.0.0git
PartiallyInlineLibCalls.cpp
Go to the documentation of this file.
1//===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass tries to partially inline the fast path of well-known library
10// functions, such as using square-root instructions for cases where sqrt()
11// does not need to set errno.
12//
13//===----------------------------------------------------------------------===//
14
20#include "llvm/IR/Dominators.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/MDBuilder.h"
27#include <optional>
28
29using namespace llvm;
30
31namespace llvm {
33} // namespace llvm
34
35#define DEBUG_TYPE "partially-inline-libcalls"
36
37DEBUG_COUNTER(PILCounter, "partially-inline-libcalls-transform",
38 "Controls transformations in partially-inline-libcalls");
39
40static bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
41 BasicBlock &CurrBB, Function::iterator &BB,
44 // There is no need to change the IR, since backend will emit sqrt
45 // instruction if the call has already been marked read-only.
46 if (Call->onlyReadsMemory())
47 return false;
48
49 if (!DebugCounter::shouldExecute(PILCounter))
50 return false;
51
52 // Do the following transformation:
53 //
54 // (before)
55 // dst = sqrt(src)
56 //
57 // (after)
58 // v0 = sqrt_noreadmem(src) # native sqrt instruction.
59 // [if (v0 is a NaN) || if (src < 0)]
60 // v1 = sqrt(src) # library call.
61 // dst = phi(v0, v1)
62 //
63
64 Type *Ty = Call->getType();
65 IRBuilder<> Builder(Call->getNextNode());
66
67 // Split CurrBB right after the call, create a 'then' block (that branches
68 // back to split-off tail of CurrBB) into which we'll insert a libcall.
70 Builder.getTrue(), Call->getNextNode(), /*Unreachable=*/false,
71 /*BranchWeights*/ nullptr, DTU);
72
73 auto *CurrBBTerm = cast<BranchInst>(CurrBB.getTerminator());
74 // We want an 'else' block though, not a 'then' block.
75 cast<BranchInst>(CurrBBTerm)->swapSuccessors();
76
77 // Create phi that will merge results of either sqrt and replace all uses.
78 BasicBlock *JoinBB = LibCallTerm->getSuccessor(0);
79 JoinBB->setName(CurrBB.getName() + ".split");
80 Builder.SetInsertPoint(JoinBB, JoinBB->begin());
81 PHINode *Phi = Builder.CreatePHI(Ty, 2);
82 Call->replaceAllUsesWith(Phi);
83
84 // Finally, insert the libcall into 'else' block.
85 BasicBlock *LibCallBB = LibCallTerm->getParent();
86 LibCallBB->setName("call.sqrt");
87 Builder.SetInsertPoint(LibCallTerm);
88 Instruction *LibCall = Call->clone();
89 Builder.Insert(LibCall);
90
91 // Add memory(none) attribute, so that the backend can use a native sqrt
92 // instruction for this call.
93 Call->setDoesNotAccessMemory();
94
95 // Insert a FP compare instruction and use it as the CurrBB branch condition.
96 Builder.SetInsertPoint(CurrBBTerm);
97 Value *FCmp = TTI->isFCmpOrdCheaperThanFCmpZero(Ty)
98 ? Builder.CreateFCmpORD(Call, Call)
99 : Builder.CreateFCmpOGE(Call->getOperand(0),
100 ConstantFP::get(Ty, 0.0));
101 CurrBBTerm->setCondition(FCmp);
103 CurrBBTerm->getFunction()->getEntryCount()) {
104 // Presume the quick path - where we don't call the library call - is the
105 // frequent one
106 MDBuilder MDB(CurrBBTerm->getContext());
107 CurrBBTerm->setMetadata(LLVMContext::MD_prof,
109 }
110 // Add phi operands.
111 Phi->addIncoming(Call, &CurrBB);
112 Phi->addIncoming(LibCall, LibCallBB);
113
114 BB = JoinBB->getIterator();
115 return true;
116}
117
120 DominatorTree *DT,
122 std::optional<DomTreeUpdater> DTU;
123 if (DT)
124 DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
125
126 bool Changed = false;
127
128 Function::iterator CurrBB;
129 for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
130 CurrBB = BB++;
131
132 for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
133 II != IE; ++II) {
135 Function *CalledFunc;
136
137 if (!Call || !(CalledFunc = Call->getCalledFunction()))
138 continue;
139
140 if (Call->isNoBuiltin() || Call->isStrictFP())
141 continue;
142
143 if (Call->isMustTailCall())
144 continue;
145
146 // Skip if function either has local linkage or is not a known library
147 // function.
148 LibFunc LF;
149 if (CalledFunc->hasLocalLinkage() ||
150 !TLI->getLibFunc(*CalledFunc, LF) || !TLI->has(LF))
151 continue;
152
153 switch (LF) {
154 case LibFunc_sqrtf:
155 case LibFunc_sqrt:
156 if (TTI->haveFastSqrt(Call->getType()) &&
157 optimizeSQRT(Call, CalledFunc, *CurrBB, BB, TTI,
158 DTU ? &*DTU : nullptr, ORE))
159 break;
160 continue;
161 default:
162 continue;
163 }
164
165 Changed = true;
166 break;
167 }
168 }
169
170 return Changed;
171}
172
185
186namespace {
187class PartiallyInlineLibCallsLegacyPass : public FunctionPass {
188public:
189 static char ID;
190
191 PartiallyInlineLibCallsLegacyPass() : FunctionPass(ID) {
194 }
195
196 void getAnalysisUsage(AnalysisUsage &AU) const override {
202 }
203
204 bool runOnFunction(Function &F) override {
205 if (skipFunction(F))
206 return false;
207
208 TargetLibraryInfo *TLI =
209 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
210 const TargetTransformInfo *TTI =
211 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
212 DominatorTree *DT = nullptr;
213 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
214 DT = &DTWP->getDomTree();
215 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
216 return runPartiallyInlineLibCalls(F, TLI, TTI, DT, ORE);
217 }
218};
219}
220
221char PartiallyInlineLibCallsLegacyPass::ID = 0;
222INITIALIZE_PASS_BEGIN(PartiallyInlineLibCallsLegacyPass,
223 "partially-inline-libcalls",
224 "Partially inline calls to library functions", false,
225 false)
230INITIALIZE_PASS_END(PartiallyInlineLibCallsLegacyPass,
231 "partially-inline-libcalls",
232 "Partially inline calls to library functions", false, false)
233
235 return new PartiallyInlineLibCallsLegacyPass();
236}
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition MD5.cpp:54
uint64_t IntrinsicInst * II
static bool runPartiallyInlineLibCalls(Function &F, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI, DominatorTree *DT, OptimizationRemarkEmitter *ORE)
static bool optimizeSQRT(CallInst *Call, Function *CalledFunc, BasicBlock &CurrBB, Function::iterator &BB, const TargetTransformInfo *TTI, DomTreeUpdater *DTU, OptimizationRemarkEmitter *ORE)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This pass exposes codegen information to IR-level passes.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:459
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
This class represents a function call, abstracting a target machine's calling convention.
static bool shouldExecute(unsigned CounterName)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:321
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:164
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
BasicBlockListType::iterator iterator
Definition Function.h:69
bool hasLocalLinkage() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2788
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI MDNode * createLikelyBranchWeights()
Return metadata containing two branch weights, with significant bias towards true destination.
Definition MDBuilder.cpp:43
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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...
Definition Pass.cpp:112
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
TargetTransformInfo TTI
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
LLVM_ABI FunctionPass * createPartiallyInlineLibCallsPass()
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void initializePartiallyInlineLibCallsLegacyPassPass(PassRegistry &)