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
15#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
16#include "llvm/Analysis/DomTreeUpdater.h"
17#include "llvm/Analysis/OptimizationRemarkEmitter.h"
18#include "llvm/Analysis/TargetLibraryInfo.h"
19#include "llvm/Analysis/TargetTransformInfo.h"
20#include "llvm/IR/Dominators.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/MDBuilder.h"
23#include "llvm/InitializePasses.h"
24#include "llvm/Support/DebugCounter.h"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27#include <optional>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "partially-inline-libcalls"
32
33DEBUG_COUNTER(PILCounter, "partially-inline-libcalls-transform",
34 "Controls transformations in partially-inline-libcalls");
35
36static bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
37 BasicBlock &CurrBB, Function::iterator &BB,
38 const TargetTransformInfo *TTI, DomTreeUpdater *DTU,
39 OptimizationRemarkEmitter *ORE) {
40 // There is no need to change the IR, since backend will emit sqrt
41 // instruction if the call has already been marked read-only.
42 if (Call->onlyReadsMemory())
43 return false;
44
45 if (!DebugCounter::shouldExecute(Counter&: PILCounter))
46 return false;
47
48 // Do the following transformation:
49 //
50 // (before)
51 // dst = sqrt(src)
52 //
53 // (after)
54 // v0 = sqrt_noreadmem(src) # native sqrt instruction.
55 // [if (v0 is a NaN) || if (src < 0)]
56 // v1 = sqrt(src) # library call.
57 // dst = phi(v0, v1)
58 //
59
60 Type *Ty = Call->getType();
61 IRBuilder<> Builder(Call->getNextNode());
62
63 // Split CurrBB right after the call, create a 'then' block (that branches
64 // back to split-off tail of CurrBB) into which we'll insert a libcall.
65 Instruction *LibCallTerm = SplitBlockAndInsertIfThen(
66 Cond: Builder.getTrue(), SplitBefore: Call->getNextNode(), /*Unreachable=*/false,
67 /*BranchWeights*/ nullptr, DTU);
68
69 auto *CurrBBTerm = cast<CondBrInst>(Val: CurrBB.getTerminator());
70 // We want an 'else' block though, not a 'then' block.
71 CurrBBTerm->swapSuccessors();
72
73 // Create phi that will merge results of either sqrt and replace all uses.
74 BasicBlock *JoinBB = LibCallTerm->getSuccessor(Idx: 0);
75 JoinBB->setName(CurrBB.getName() + ".split");
76 Builder.SetInsertPoint(TheBB: JoinBB, IP: JoinBB->begin());
77 PHINode *Phi = Builder.CreatePHI(Ty, NumReservedValues: 2);
78 Call->replaceAllUsesWith(V: Phi);
79
80 // Finally, insert the libcall into 'else' block.
81 BasicBlock *LibCallBB = LibCallTerm->getParent();
82 LibCallBB->setName("call.sqrt");
83 Builder.SetInsertPoint(LibCallTerm);
84 Instruction *LibCall = Call->clone();
85 Builder.Insert(I: LibCall);
86
87 // Add memory(none) attribute, so that the backend can use a native sqrt
88 // instruction for this call.
89 Call->setDoesNotAccessMemory();
90
91 // Insert a FP compare instruction and use it as the CurrBB branch condition.
92 Builder.SetInsertPoint(CurrBBTerm);
93 Value *FCmp = TTI->isFCmpOrdCheaperThanFCmpZero(Ty)
94 ? Builder.CreateFCmpORD(LHS: Call, RHS: Call)
95 : Builder.CreateFCmpOGE(LHS: Call->getOperand(i_nocapture: 0),
96 RHS: ConstantFP::get(Ty, V: 0.0));
97 CurrBBTerm->setCondition(FCmp);
98 if (CurrBBTerm->getFunction()->getEntryCount()) {
99 // Presume the quick path - where we don't call the library call - is the
100 // frequent one
101 MDBuilder MDB(CurrBBTerm->getContext());
102 CurrBBTerm->setMetadata(KindID: LLVMContext::MD_prof,
103 Node: MDB.createLikelyBranchWeights());
104 }
105 // Add phi operands.
106 Phi->addIncoming(V: Call, BB: &CurrBB);
107 Phi->addIncoming(V: LibCall, BB: LibCallBB);
108
109 BB = JoinBB->getIterator();
110 return true;
111}
112
113static bool runPartiallyInlineLibCalls(Function &F, TargetLibraryInfo *TLI,
114 const TargetTransformInfo *TTI,
115 DominatorTree *DT,
116 OptimizationRemarkEmitter *ORE) {
117 std::optional<DomTreeUpdater> DTU;
118 if (DT)
119 DTU.emplace(args&: DT, args: DomTreeUpdater::UpdateStrategy::Lazy);
120
121 bool Changed = false;
122
123 Function::iterator CurrBB;
124 for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
125 CurrBB = BB++;
126
127 for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
128 II != IE; ++II) {
129 CallInst *Call = dyn_cast<CallInst>(Val: &*II);
130 Function *CalledFunc;
131
132 if (!Call || !(CalledFunc = Call->getCalledFunction()))
133 continue;
134
135 if (Call->isNoBuiltin() || Call->isStrictFP())
136 continue;
137
138 if (Call->isMustTailCall())
139 continue;
140
141 // Skip if function either has local linkage or is not a known library
142 // function.
143 if (CalledFunc->hasLocalLinkage())
144 continue;
145
146 LibFunc LF = TLI->getLibFunc(FDecl: *CalledFunc);
147 if (!TLI->has(F: LF))
148 continue;
149
150 switch (LF) {
151 case LibFunc_sqrtf:
152 case LibFunc_sqrt:
153 if (TTI->haveFastSqrt(Ty: Call->getType()) &&
154 optimizeSQRT(Call, CalledFunc, CurrBB&: *CurrBB, BB, TTI,
155 DTU: DTU ? &*DTU : nullptr, ORE))
156 break;
157 continue;
158 default:
159 continue;
160 }
161
162 Changed = true;
163 break;
164 }
165 }
166
167 return Changed;
168}
169
170PreservedAnalyses
171PartiallyInlineLibCallsPass::run(Function &F, FunctionAnalysisManager &AM) {
172 auto &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
173 auto &TTI = AM.getResult<TargetIRAnalysis>(IR&: F);
174 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(IR&: F);
175 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(IR&: F);
176 if (!runPartiallyInlineLibCalls(F, TLI: &TLI, TTI: &TTI, DT, ORE: &ORE))
177 return PreservedAnalyses::all();
178 PreservedAnalyses PA;
179 PA.preserve<DominatorTreeAnalysis>();
180 return PA;
181}
182
183namespace {
184class PartiallyInlineLibCallsLegacyPass : public FunctionPass {
185public:
186 static char ID;
187
188 PartiallyInlineLibCallsLegacyPass() : FunctionPass(ID) {
189 initializePartiallyInlineLibCallsLegacyPassPass(
190 *PassRegistry::getPassRegistry());
191 }
192
193 void getAnalysisUsage(AnalysisUsage &AU) const override {
194 AU.addRequired<TargetLibraryInfoWrapperPass>();
195 AU.addRequired<TargetTransformInfoWrapperPass>();
196 AU.addPreserved<DominatorTreeWrapperPass>();
197 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
198 FunctionPass::getAnalysisUsage(AU);
199 }
200
201 bool runOnFunction(Function &F) override {
202 if (skipFunction(F))
203 return false;
204
205 TargetLibraryInfo *TLI =
206 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
207 const TargetTransformInfo *TTI =
208 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
209 DominatorTree *DT = nullptr;
210 if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
211 DT = &DTWP->getDomTree();
212 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
213 return runPartiallyInlineLibCalls(F, TLI, TTI, DT, ORE);
214 }
215};
216}
217
218char PartiallyInlineLibCallsLegacyPass::ID = 0;
219INITIALIZE_PASS_BEGIN(PartiallyInlineLibCallsLegacyPass,
220 "partially-inline-libcalls",
221 "Partially inline calls to library functions", false,
222 false)
223INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
224INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
225INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
226INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
227INITIALIZE_PASS_END(PartiallyInlineLibCallsLegacyPass,
228 "partially-inline-libcalls",
229 "Partially inline calls to library functions", false, false)
230
231FunctionPass *llvm::createPartiallyInlineLibCallsPass() {
232 return new PartiallyInlineLibCallsLegacyPass();
233}
234