1 //===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass tries to partially inline the fast path of well-known library
11 // functions, such as using square-root instructions for cases where sqrt()
12 // does not need to set errno.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/TargetLibraryInfo.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "partially-inline-libcalls"
27 
28 namespace {
29   class PartiallyInlineLibCalls : public FunctionPass {
30   public:
31     static char ID;
32 
33     PartiallyInlineLibCalls() :
34       FunctionPass(ID) {
35       initializePartiallyInlineLibCallsPass(*PassRegistry::getPassRegistry());
36     }
37 
38     void getAnalysisUsage(AnalysisUsage &AU) const override;
39     bool runOnFunction(Function &F) override;
40 
41   private:
42     /// Optimize calls to sqrt.
43     bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
44                       BasicBlock &CurrBB, Function::iterator &BB);
45   };
46 
47   char PartiallyInlineLibCalls::ID = 0;
48 }
49 
50 INITIALIZE_PASS(PartiallyInlineLibCalls, "partially-inline-libcalls",
51                 "Partially inline calls to library functions", false, false)
52 
53 void PartiallyInlineLibCalls::getAnalysisUsage(AnalysisUsage &AU) const {
54   AU.addRequired<TargetLibraryInfoWrapperPass>();
55   AU.addRequired<TargetTransformInfoWrapperPass>();
56   FunctionPass::getAnalysisUsage(AU);
57 }
58 
59 bool PartiallyInlineLibCalls::runOnFunction(Function &F) {
60   bool Changed = false;
61   Function::iterator CurrBB;
62   TargetLibraryInfo *TLI =
63       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
64   const TargetTransformInfo *TTI =
65       &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
66   for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
67     CurrBB = BB++;
68 
69     for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
70          II != IE; ++II) {
71       CallInst *Call = dyn_cast<CallInst>(&*II);
72       Function *CalledFunc;
73 
74       if (!Call || !(CalledFunc = Call->getCalledFunction()))
75         continue;
76 
77       // Skip if function either has local linkage or is not a known library
78       // function.
79       LibFunc::Func LibFunc;
80       if (CalledFunc->hasLocalLinkage() || !CalledFunc->hasName() ||
81           !TLI->getLibFunc(CalledFunc->getName(), LibFunc))
82         continue;
83 
84       switch (LibFunc) {
85       case LibFunc::sqrtf:
86       case LibFunc::sqrt:
87         if (TTI->haveFastSqrt(Call->getType()) &&
88             optimizeSQRT(Call, CalledFunc, *CurrBB, BB))
89           break;
90         continue;
91       default:
92         continue;
93       }
94 
95       Changed = true;
96       break;
97     }
98   }
99 
100   return Changed;
101 }
102 
103 bool PartiallyInlineLibCalls::optimizeSQRT(CallInst *Call,
104                                            Function *CalledFunc,
105                                            BasicBlock &CurrBB,
106                                            Function::iterator &BB) {
107   // There is no need to change the IR, since backend will emit sqrt
108   // instruction if the call has already been marked read-only.
109   if (Call->onlyReadsMemory())
110     return false;
111 
112   // The call must have the expected result type.
113   if (!Call->getType()->isFloatingPointTy())
114     return false;
115 
116   // Do the following transformation:
117   //
118   // (before)
119   // dst = sqrt(src)
120   //
121   // (after)
122   // v0 = sqrt_noreadmem(src) # native sqrt instruction.
123   // if (v0 is a NaN)
124   //   v1 = sqrt(src)         # library call.
125   // dst = phi(v0, v1)
126   //
127 
128   // Move all instructions following Call to newly created block JoinBB.
129   // Create phi and replace all uses.
130   BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode());
131   IRBuilder<> Builder(JoinBB, JoinBB->begin());
132   PHINode *Phi = Builder.CreatePHI(Call->getType(), 2);
133   Call->replaceAllUsesWith(Phi);
134 
135   // Create basic block LibCallBB and insert a call to library function sqrt.
136   BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt",
137                                              CurrBB.getParent(), JoinBB);
138   Builder.SetInsertPoint(LibCallBB);
139   Instruction *LibCall = Call->clone();
140   Builder.Insert(LibCall);
141   Builder.CreateBr(JoinBB);
142 
143   // Add attribute "readnone" so that backend can use a native sqrt instruction
144   // for this call. Insert a FP compare instruction and a conditional branch
145   // at the end of CurrBB.
146   Call->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
147   CurrBB.getTerminator()->eraseFromParent();
148   Builder.SetInsertPoint(&CurrBB);
149   Value *FCmp = Builder.CreateFCmpOEQ(Call, Call);
150   Builder.CreateCondBr(FCmp, JoinBB, LibCallBB);
151 
152   // Add phi operands.
153   Phi->addIncoming(Call, &CurrBB);
154   Phi->addIncoming(LibCall, LibCallBB);
155 
156   BB = JoinBB->getIterator();
157   return true;
158 }
159 
160 FunctionPass *llvm::createPartiallyInlineLibCallsPass() {
161   return new PartiallyInlineLibCalls();
162 }
163