blob: 17d07cdb2d4d5ab37c055678576f7580dbbac11e [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
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 file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000021#include "llvm/IRBuilder.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000026#include "llvm/ADT/STLExtras.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Analysis/ValueTracking.h"
Chad Rosierec7e92a2012-08-22 17:22:33 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000032#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000033#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000034#include "llvm/DataLayout.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000035#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000036#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000037using namespace llvm;
38
39STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000040STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000041
Chad Rosierec7e92a2012-08-22 17:22:33 +000042static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43 cl::init(false),
44 cl::desc("Enable unsafe double to float "
45 "shrinking for math lib calls"));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000046//===----------------------------------------------------------------------===//
47// Optimizer Base Class
48//===----------------------------------------------------------------------===//
49
50/// This class is the abstract base class for the set of optimizations that
51/// corresponds to one library call.
52namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000053class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054protected:
55 Function *Caller;
Micah Villmow3574eca2012-10-08 16:38:25 +000056 const DataLayout *TD;
Richard Osborne36498242011-03-03 13:17:51 +000057 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000058 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000059public:
Evan Chengeb8c6452010-03-24 20:19:04 +000060 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000061 virtual ~LibCallOptimization() {}
62
63 /// CallOptimizer - This pure virtual method is implemented by base classes to
64 /// do various optimizations. If this returns null then no transformation was
65 /// performed. If it returns CI, then it transformed the call and CI is to be
66 /// deleted. If it returns something else, replace CI with the new value and
67 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000069 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000070
Micah Villmow3574eca2012-10-08 16:38:25 +000071 Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
Richard Osborne36498242011-03-03 13:17:51 +000072 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000073 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000074 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000075 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000076 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000077 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000078
79 // We never change the calling convention.
80 if (CI->getCallingConv() != llvm::CallingConv::C)
81 return NULL;
82
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083 return CallOptimizer(CI->getCalledFunction(), CI, B);
84 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000085};
86} // End anonymous namespace.
87
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000088
89//===----------------------------------------------------------------------===//
90// Helper Functions
91//===----------------------------------------------------------------------===//
92
Richard Osborne36498242011-03-03 13:17:51 +000093static bool CallHasFloatingPointArgument(const CallInst *CI) {
94 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
95 it != e; ++it) {
96 if ((*it)->getType()->isFloatingPointTy())
97 return true;
98 }
99 return false;
100}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000101
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000102namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000103//===----------------------------------------------------------------------===//
104// Math Library Optimizations
105//===----------------------------------------------------------------------===//
106
107//===---------------------------------------===//
Chad Rosierec7e92a2012-08-22 17:22:33 +0000108// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000109
Chad Rosierec7e92a2012-08-22 17:22:33 +0000110struct UnaryDoubleFPOpt : public LibCallOptimization {
111 bool CheckRetType;
112 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
113 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
114 FunctionType *FT = Callee->getFunctionType();
115 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
116 !FT->getParamType(0)->isDoubleTy())
117 return 0;
118
119 if (CheckRetType) {
120 // Check if all the uses for function like 'sin' are converted to float.
121 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
122 ++UseI) {
123 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
124 if (Cast == 0 || !Cast->getType()->isFloatTy())
125 return 0;
126 }
127 }
128
129 // If this is something like 'floor((double)floatval)', convert to floorf.
130 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
131 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
132 return 0;
133
134 // floor((double)floatval) -> (double)floorf(floatval)
135 Value *V = Cast->getOperand(0);
136 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
137 return B.CreateFPExt(V, B.getDoubleTy());
138 }
139};
140
141//===---------------------------------------===//
142// 'cos*' Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000143struct CosOpt : public LibCallOptimization {
144 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000145 Value *Ret = NULL;
146 if (UnsafeFPShrink && Callee->getName() == "cos" &&
147 TLI->has(LibFunc::cosf)) {
148 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
149 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
150 }
151
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000152 FunctionType *FT = Callee->getFunctionType();
153 // Just make sure this has 1 argument of FP type, which matches the
154 // result type.
155 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
156 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000157 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000158
159 // cos(-x) -> cos(x)
160 Value *Op1 = CI->getArgOperand(0);
161 if (BinaryOperator::isFNeg(Op1)) {
162 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
163 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
164 }
Chad Rosierec7e92a2012-08-22 17:22:33 +0000165 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000166 }
167};
168
169//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000170// 'pow*' Optimizations
171
Chris Lattner3e8b6632009-09-02 06:11:42 +0000172struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000173 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000174 Value *Ret = NULL;
175 if (UnsafeFPShrink && Callee->getName() == "pow" &&
176 TLI->has(LibFunc::powf)) {
177 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
178 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
179 }
180
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000181 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000182 // Just make sure this has 2 arguments of the same FP type, which match the
183 // result type.
184 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
185 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000186 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000187 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000188
Gabor Greifaee5dc12010-06-24 10:42:46 +0000189 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000190 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
191 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
192 return Op1C;
193 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000194 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000195 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000196
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000197 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
Chad Rosierec7e92a2012-08-22 17:22:33 +0000198 if (Op2C == 0) return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000199
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000200 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000201 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000202
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000203 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000204 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
205 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000206 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000207 // TODO: In fast-math mode, this could be just sqrt(x).
208 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000209 Value *Inf = ConstantFP::getInfinity(CI->getType());
210 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000211 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
212 Callee->getAttributes());
213 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
214 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000215 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
216 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000217 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000218 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000219
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000220 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
221 return Op1;
222 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000224 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000225 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000226 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000227 return 0;
228 }
229};
230
231//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000232// 'exp2' Optimizations
233
Chris Lattner3e8b6632009-09-02 06:11:42 +0000234struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000235 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000236 Value *Ret = NULL;
237 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
238 TLI->has(LibFunc::exp2)) {
239 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
240 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
241 }
242
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000243 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000244 // Just make sure this has 1 argument of FP type, which matches the
245 // result type.
246 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000247 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000248 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000249
Gabor Greifaee5dc12010-06-24 10:42:46 +0000250 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000251 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
252 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
253 Value *LdExpArg = 0;
254 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
255 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000256 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000257 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
258 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000259 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000260 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000261
Chris Lattnere818f772008-05-02 18:43:35 +0000262 if (LdExpArg) {
263 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000264 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000265 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000266 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000267 Name = "ldexp";
268 else
269 Name = "ldexpl";
270
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000271 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000272 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000273 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000274
275 Module *M = Caller->getParent();
276 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000277 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000278 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000279 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
280 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
281 CI->setCallingConv(F->getCallingConv());
282
283 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000284 }
Chad Rosierec7e92a2012-08-22 17:22:33 +0000285 return Ret;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000286 }
287};
288
289//===----------------------------------------------------------------------===//
290// Integer Optimizations
291//===----------------------------------------------------------------------===//
292
293//===---------------------------------------===//
294// 'ffs*' Optimizations
295
Chris Lattner3e8b6632009-09-02 06:11:42 +0000296struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000297 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000298 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000299 // Just make sure this has 2 arguments of the same FP type, which match the
300 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000301 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000302 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000303 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000304 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000305
Gabor Greifaee5dc12010-06-24 10:42:46 +0000306 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000307
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000308 // Constant fold.
309 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
Benjamin Kramer0aae4bd2012-10-19 20:43:44 +0000310 if (CI->isZero()) // ffs(0) -> 0.
311 return B.getInt32(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000312 // ffs(c) -> cttz(c)+1
313 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000314 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000315
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000316 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +0000317 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000318 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000319 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +0000320 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +0000321 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
322 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +0000323
Benjamin Kramera9390a42011-09-27 20:39:19 +0000324 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000325 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000326 }
327};
328
329//===---------------------------------------===//
330// 'isdigit' Optimizations
331
Chris Lattner3e8b6632009-09-02 06:11:42 +0000332struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000333 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000334 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000335 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +0000336 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000337 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000338 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000339
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000340 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +0000341 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000342 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
343 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000344 return B.CreateZExt(Op, CI->getType());
345 }
346};
347
348//===---------------------------------------===//
349// 'isascii' Optimizations
350
Chris Lattner3e8b6632009-09-02 06:11:42 +0000351struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000352 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000353 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000354 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +0000355 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000356 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000357 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000358
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000359 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +0000360 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000361 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000362 return B.CreateZExt(Op, CI->getType());
363 }
364};
Eric Christopher37c8b862009-10-07 21:14:25 +0000365
Chris Lattner313f0e62008-06-09 08:26:51 +0000366//===---------------------------------------===//
367// 'abs', 'labs', 'llabs' Optimizations
368
Chris Lattner3e8b6632009-09-02 06:11:42 +0000369struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000370 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +0000372 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +0000373 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +0000374 FT->getParamType(0) != FT->getReturnType())
375 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000376
Chris Lattner313f0e62008-06-09 08:26:51 +0000377 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +0000378 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000379 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +0000380 "ispos");
381 Value *Neg = B.CreateNeg(Op, "neg");
382 return B.CreateSelect(Pos, Op, Neg);
383 }
384};
Eric Christopher37c8b862009-10-07 21:14:25 +0000385
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386
387//===---------------------------------------===//
388// 'toascii' Optimizations
389
Chris Lattner3e8b6632009-09-02 06:11:42 +0000390struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000392 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000393 // We require i32(i32)
394 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000395 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000396 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000397
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000398 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +0000399 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +0000400 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000401 }
402};
403
404//===----------------------------------------------------------------------===//
405// Formatting and IO Optimizations
406//===----------------------------------------------------------------------===//
407
408//===---------------------------------------===//
409// 'printf' Optimizations
410
Chris Lattner3e8b6632009-09-02 06:11:42 +0000411struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +0000412 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
413 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000414 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000415 StringRef FormatStr;
416 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000417 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418
419 // Empty format string -> noop.
420 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +0000421 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +0000422 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000423
Daniel Dunbard02be242011-02-12 18:19:57 +0000424 // Do not do any of the following transformations if the printf return value
425 // is used, in general the printf return value is not compatible with either
426 // putchar() or puts().
427 if (!CI->use_empty())
428 return 0;
429
430 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000431 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000432 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000433 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +0000434 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000435 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000436
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 // printf("foo\n") --> puts("foo")
438 if (FormatStr[FormatStr.size()-1] == '\n' &&
439 FormatStr.find('%') == std::string::npos) { // no format characters.
440 // Create a string literal with no \n on it. We expect the constant merge
441 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +0000442 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +0000443 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +0000444 Value *NewCI = EmitPutS(GV, B, TD, TLI);
445 return (CI->use_empty() || !NewCI) ?
446 NewCI :
447 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000449
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000450 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000451 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000452 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +0000453 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000454 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000455
Nuno Lopescd31fc72012-07-26 17:10:46 +0000456 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +0000457 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000458 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000459
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000460 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000461 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +0000462 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000463 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000464 }
465 return 0;
466 }
Richard Osborne36498242011-03-03 13:17:51 +0000467
468 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
469 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000470 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +0000471 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
472 !(FT->getReturnType()->isIntegerTy() ||
473 FT->getReturnType()->isVoidTy()))
474 return 0;
475
476 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
477 return V;
478 }
479
480 // printf(format, ...) -> iprintf(format, ...) if no floating point
481 // arguments.
482 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
483 Module *M = B.GetInsertBlock()->getParent()->getParent();
484 Constant *IPrintFFn =
485 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
486 CallInst *New = cast<CallInst>(CI->clone());
487 New->setCalledFunction(IPrintFFn);
488 B.Insert(New);
489 return New;
490 }
491 return 0;
492 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000493};
494
495//===---------------------------------------===//
496// 'sprintf' Optimizations
497
Chris Lattner3e8b6632009-09-02 06:11:42 +0000498struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +0000499 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
500 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000501 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000502 StringRef FormatStr;
503 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000504 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000505
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000506 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000507 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000508 // Make sure there's no % in the constant array. We could try to handle
509 // %% -> % in the future if we cared.
510 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
511 if (FormatStr[i] == '%')
512 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000513
Micah Villmow3574eca2012-10-08 16:38:25 +0000514 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000515 if (!TD) return 0;
516
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000517 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000518 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000519 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000520 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +0000521 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000522 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000523
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000524 // The remaining optimizations require the format string to be "%s" or "%c"
525 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000526 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
527 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000528 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000529
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000530 // Decode the second character of the format string.
531 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000532 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +0000533 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000534 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +0000535 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000536 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000537 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
538 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +0000539
Owen Andersoneed707b2009-07-24 23:12:02 +0000540 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000541 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000542
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000543 if (FormatStr[1] == 's') {
Micah Villmow3574eca2012-10-08 16:38:25 +0000544 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000545 if (!TD) return 0;
546
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000547 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000548 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000549
Nuno Lopes51004df2012-07-25 16:46:31 +0000550 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
551 if (!Len)
552 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000553 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +0000554 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000555 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000556 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000557
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000558 // The sprintf result is the unincremented number of bytes in the string.
559 return B.CreateIntCast(Len, CI->getType(), false);
560 }
561 return 0;
562 }
Richard Osborne419454a2011-03-03 14:09:28 +0000563
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000566 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +0000567 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
568 !FT->getParamType(1)->isPointerTy() ||
569 !FT->getReturnType()->isIntegerTy())
570 return 0;
571
572 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
573 return V;
574 }
575
Richard Osborneea2578c2011-03-03 14:21:22 +0000576 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +0000577 // point arguments.
578 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
579 Module *M = B.GetInsertBlock()->getParent()->getParent();
580 Constant *SIPrintFFn =
581 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
582 CallInst *New = cast<CallInst>(CI->clone());
583 New->setCalledFunction(SIPrintFFn);
584 B.Insert(New);
585 return New;
586 }
587 return 0;
588 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000589};
590
591//===---------------------------------------===//
592// 'fwrite' Optimizations
593
Chris Lattner3e8b6632009-09-02 06:11:42 +0000594struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000595 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000596 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000597 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000598 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
599 !FT->getParamType(1)->isIntegerTy() ||
600 !FT->getParamType(2)->isIntegerTy() ||
601 !FT->getParamType(3)->isPointerTy() ||
602 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000603 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000604
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000605 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000606 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
607 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000608 if (!SizeC || !CountC) return 0;
609 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +0000610
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000611 // If this is writing zero records, remove the call (it's a noop).
612 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +0000613 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000614
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000615 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +0000616 // This optimisation is only valid, if the return value is unused.
617 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000618 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +0000619 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
620 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000621 }
622
623 return 0;
624 }
625};
626
627//===---------------------------------------===//
628// 'fputs' Optimizations
629
Chris Lattner3e8b6632009-09-02 06:11:42 +0000630struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000631 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000632 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000633 if (!TD) return 0;
634
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000635 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000636 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000637 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
638 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000639 !CI->use_empty())
640 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000641
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000642 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000643 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000644 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000645 // Known to have no uses (see above).
646 return EmitFWrite(CI->getArgOperand(0),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000647 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000648 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000649 }
650};
651
652//===---------------------------------------===//
653// 'fprintf' Optimizations
654
Chris Lattner3e8b6632009-09-02 06:11:42 +0000655struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +0000656 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
657 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000658 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000659 StringRef FormatStr;
660 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +0000661 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000662
663 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000664 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000665 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
666 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000667 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000668
Micah Villmow3574eca2012-10-08 16:38:25 +0000669 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000670 if (!TD) return 0;
671
Nuno Lopes51004df2012-07-25 16:46:31 +0000672 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000673 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000674 FormatStr.size()),
675 CI->getArgOperand(0), B, TD, TLI);
676 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000677 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000678
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000679 // The remaining optimizations require the format string to be "%s" or "%c"
680 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000681 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
682 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000683 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000684
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000685 // Decode the second character of the format string.
686 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +0000687 // fprintf(F, "%c", chr) --> fputc(chr, F)
688 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000689 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
690 TD, TLI);
691 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000692 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000693
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000694 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +0000695 // fprintf(F, "%s", str) --> fputs(str, F)
696 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000697 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +0000698 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000699 }
700 return 0;
701 }
Richard Osborne022708f2011-03-03 14:20:22 +0000702
703 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
704 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000705 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +0000706 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
707 !FT->getParamType(1)->isPointerTy() ||
708 !FT->getReturnType()->isIntegerTy())
709 return 0;
710
711 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
712 return V;
713 }
714
715 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
716 // floating point arguments.
717 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
718 Module *M = B.GetInsertBlock()->getParent()->getParent();
719 Constant *FIPrintFFn =
720 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
721 CallInst *New = cast<CallInst>(CI->clone());
722 New->setCalledFunction(FIPrintFFn);
723 B.Insert(New);
724 return New;
725 }
726 return 0;
727 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000728};
729
Anders Carlsson303023d2010-11-30 06:19:18 +0000730//===---------------------------------------===//
731// 'puts' Optimizations
732
733struct PutsOpt : public LibCallOptimization {
734 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
735 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000736 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +0000737 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
738 !(FT->getReturnType()->isIntegerTy() ||
739 FT->getReturnType()->isVoidTy()))
740 return 0;
741
742 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000743 StringRef Str;
744 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +0000745 return 0;
746
Daniel Dunbard02be242011-02-12 18:19:57 +0000747 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +0000748 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +0000749 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +0000750 if (CI->use_empty() || !Res) return Res;
Anders Carlsson303023d2010-11-30 06:19:18 +0000751 return B.CreateIntCast(Res, CI->getType(), true);
752 }
753
754 return 0;
755 }
756};
757
Bill Wendlingac178222008-05-05 21:37:59 +0000758} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000759
760//===----------------------------------------------------------------------===//
761// SimplifyLibCalls Pass Implementation
762//===----------------------------------------------------------------------===//
763
764namespace {
765 /// This pass optimizes well known library functions from libc and libm.
766 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +0000767 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000768 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000769
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000770 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000771 // Math Library Optimizations
Chad Rosierec7e92a2012-08-22 17:22:33 +0000772 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
773 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000774 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +0000775 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
776 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000777 // Formatting and IO Optimizations
778 SPrintFOpt SPrintF; PrintFOpt PrintF;
779 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +0000780 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000781
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000782 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000783 public:
784 static char ID; // Pass identification
Meador Ingee6d781f2012-10-31 00:20:56 +0000785 SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
786 UnsafeUnaryDoubleFP(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000787 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
788 }
Eli Friedman9d434db2011-11-17 01:27:36 +0000789 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chad Rosierd7e25252012-08-22 16:52:57 +0000790 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
791
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000792 void InitOptimizations();
793 bool runOnFunction(Function &F);
794
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000795 void setDoesNotAccessMemory(Function &F);
796 void setOnlyReadsMemory(Function &F);
797 void setDoesNotThrow(Function &F);
798 void setDoesNotCapture(Function &F, unsigned n);
799 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000800 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000801
Chris Lattnere265ad82011-02-24 07:12:12 +0000802 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000803 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000804 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000805 }
806 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000807} // end anonymous namespace.
808
Chris Lattnerafbf4832011-02-24 07:16:14 +0000809char SimplifyLibCalls::ID = 0;
810
811INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
812 "Simplify well-known library calls", false, false)
813INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
814INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
815 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000816
817// Public interface to the Simplify LibCalls pass.
818FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +0000819 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000820}
821
Eli Friedman9d434db2011-11-17 01:27:36 +0000822void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
823 if (TLI->has(F))
824 Optimizations[TLI->getName(F)] = Opt;
825}
826
Chad Rosierd7e25252012-08-22 16:52:57 +0000827void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
828 LibCallOptimization* Opt) {
829 if (TLI->has(F1) && TLI->has(F2))
830 Optimizations[TLI->getName(F1)] = Opt;
831}
832
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000833/// Optimizations - Populate the Optimizations map with all the optimizations
834/// we know.
835void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000836 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000837 Optimizations["cosf"] = &Cos;
838 Optimizations["cos"] = &Cos;
839 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000840 Optimizations["powf"] = &Pow;
841 Optimizations["pow"] = &Pow;
842 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +0000843 Optimizations["llvm.pow.f32"] = &Pow;
844 Optimizations["llvm.pow.f64"] = &Pow;
845 Optimizations["llvm.pow.f80"] = &Pow;
846 Optimizations["llvm.pow.f128"] = &Pow;
847 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +0000848 Optimizations["exp2l"] = &Exp2;
849 Optimizations["exp2"] = &Exp2;
850 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +0000851 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
852 Optimizations["llvm.exp2.f128"] = &Exp2;
853 Optimizations["llvm.exp2.f80"] = &Exp2;
854 Optimizations["llvm.exp2.f64"] = &Exp2;
855 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +0000856
Chad Rosierd7e25252012-08-22 16:52:57 +0000857 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
858 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
Benjamin Kramer7f07d2f2012-08-22 19:39:15 +0000859 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
860 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
861 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
862 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
863 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
Chad Rosierec7e92a2012-08-22 17:22:33 +0000864
865 if(UnsafeFPShrink) {
866 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
867 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
868 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
869 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
870 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
871 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
872 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
873 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
874 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
875 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
876 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
877 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
878 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
879 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
880 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
881 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
882 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
883 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
884 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
885 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
886 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
887 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000888
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000889 // Integer Optimizations
890 Optimizations["ffs"] = &FFS;
891 Optimizations["ffsl"] = &FFS;
892 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +0000893 Optimizations["abs"] = &Abs;
894 Optimizations["labs"] = &Abs;
895 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000896 Optimizations["isdigit"] = &IsDigit;
897 Optimizations["isascii"] = &IsAscii;
898 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +0000899
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000900 // Formatting and IO Optimizations
901 Optimizations["sprintf"] = &SPrintF;
902 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +0000903 AddOpt(LibFunc::fwrite, &FWrite);
904 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000905 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +0000906 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000907}
908
909
910/// runOnFunction - Top level algorithm.
911///
912bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +0000913 TLI = &getAnalysis<TargetLibraryInfo>();
914
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000915 if (Optimizations.empty())
916 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +0000917
Micah Villmow3574eca2012-10-08 16:38:25 +0000918 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
Eric Christopher37c8b862009-10-07 21:14:25 +0000919
Owen Andersone922c022009-07-22 00:24:57 +0000920 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000921
922 bool Changed = false;
923 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
924 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
925 // Ignore non-calls.
926 CallInst *CI = dyn_cast<CallInst>(I++);
927 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000928
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000929 // Ignore indirect calls and calls to non-external functions.
930 Function *Callee = CI->getCalledFunction();
931 if (Callee == 0 || !Callee->isDeclaration() ||
932 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
933 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000934
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000935 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000936 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
937 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000938
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000939 // Set the builder to the instruction after the call.
940 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +0000941
Devang Patela2ab3992011-03-09 21:27:52 +0000942 // Use debug location of CI for all new instructions.
943 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
944
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000945 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +0000946 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000947 if (Result == 0) continue;
948
David Greene6a6b90e2010-01-05 01:27:21 +0000949 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
950 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +0000951
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000952 // Something changed!
953 Changed = true;
954 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +0000955
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000956 // Inspect the instruction after the call (which was potentially just
957 // added) next.
958 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +0000959
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000960 if (CI != Result && !CI->use_empty()) {
961 CI->replaceAllUsesWith(Result);
962 if (!Result->hasName())
963 Result->takeName(CI);
964 }
965 CI->eraseFromParent();
966 }
967 }
968 return Changed;
969}
970
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000971// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +0000972
973void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
974 if (!F.doesNotAccessMemory()) {
975 F.setDoesNotAccessMemory();
976 ++NumAnnotated;
977 Modified = true;
978 }
979}
980void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
981 if (!F.onlyReadsMemory()) {
982 F.setOnlyReadsMemory();
983 ++NumAnnotated;
984 Modified = true;
985 }
986}
987void SimplifyLibCalls::setDoesNotThrow(Function &F) {
988 if (!F.doesNotThrow()) {
989 F.setDoesNotThrow();
990 ++NumAnnotated;
991 Modified = true;
992 }
993}
994void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
995 if (!F.doesNotCapture(n)) {
996 F.setDoesNotCapture(n);
997 ++NumAnnotated;
998 Modified = true;
999 }
1000}
1001void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1002 if (!F.doesNotAlias(n)) {
1003 F.setDoesNotAlias(n);
1004 ++NumAnnotated;
1005 Modified = true;
1006 }
1007}
1008
Chris Lattnere265ad82011-02-24 07:12:12 +00001009
1010void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001011 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001012
Chris Lattnere265ad82011-02-24 07:12:12 +00001013 StringRef Name = F.getName();
1014 switch (Name[0]) {
1015 case 's':
1016 if (Name == "strlen") {
1017 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1018 return;
1019 setOnlyReadsMemory(F);
1020 setDoesNotThrow(F);
1021 setDoesNotCapture(F, 1);
1022 } else if (Name == "strchr" ||
1023 Name == "strrchr") {
1024 if (FTy->getNumParams() != 2 ||
1025 !FTy->getParamType(0)->isPointerTy() ||
1026 !FTy->getParamType(1)->isIntegerTy())
1027 return;
1028 setOnlyReadsMemory(F);
1029 setDoesNotThrow(F);
1030 } else if (Name == "strcpy" ||
1031 Name == "stpcpy" ||
1032 Name == "strcat" ||
1033 Name == "strtol" ||
1034 Name == "strtod" ||
1035 Name == "strtof" ||
1036 Name == "strtoul" ||
1037 Name == "strtoll" ||
1038 Name == "strtold" ||
1039 Name == "strncat" ||
1040 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001041 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001042 Name == "strtoull") {
1043 if (FTy->getNumParams() < 2 ||
1044 !FTy->getParamType(1)->isPointerTy())
1045 return;
1046 setDoesNotThrow(F);
1047 setDoesNotCapture(F, 2);
1048 } else if (Name == "strxfrm") {
1049 if (FTy->getNumParams() != 3 ||
1050 !FTy->getParamType(0)->isPointerTy() ||
1051 !FTy->getParamType(1)->isPointerTy())
1052 return;
1053 setDoesNotThrow(F);
1054 setDoesNotCapture(F, 1);
1055 setDoesNotCapture(F, 2);
1056 } else if (Name == "strcmp" ||
1057 Name == "strspn" ||
1058 Name == "strncmp" ||
1059 Name == "strcspn" ||
1060 Name == "strcoll" ||
1061 Name == "strcasecmp" ||
1062 Name == "strncasecmp") {
1063 if (FTy->getNumParams() < 2 ||
1064 !FTy->getParamType(0)->isPointerTy() ||
1065 !FTy->getParamType(1)->isPointerTy())
1066 return;
1067 setOnlyReadsMemory(F);
1068 setDoesNotThrow(F);
1069 setDoesNotCapture(F, 1);
1070 setDoesNotCapture(F, 2);
1071 } else if (Name == "strstr" ||
1072 Name == "strpbrk") {
1073 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1074 return;
1075 setOnlyReadsMemory(F);
1076 setDoesNotThrow(F);
1077 setDoesNotCapture(F, 2);
1078 } else if (Name == "strtok" ||
1079 Name == "strtok_r") {
1080 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1081 return;
1082 setDoesNotThrow(F);
1083 setDoesNotCapture(F, 2);
1084 } else if (Name == "scanf" ||
1085 Name == "setbuf" ||
1086 Name == "setvbuf") {
1087 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1088 return;
1089 setDoesNotThrow(F);
1090 setDoesNotCapture(F, 1);
1091 } else if (Name == "strdup" ||
1092 Name == "strndup") {
1093 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1094 !FTy->getParamType(0)->isPointerTy())
1095 return;
1096 setDoesNotThrow(F);
1097 setDoesNotAlias(F, 0);
1098 setDoesNotCapture(F, 1);
1099 } else if (Name == "stat" ||
1100 Name == "sscanf" ||
1101 Name == "sprintf" ||
1102 Name == "statvfs") {
1103 if (FTy->getNumParams() < 2 ||
1104 !FTy->getParamType(0)->isPointerTy() ||
1105 !FTy->getParamType(1)->isPointerTy())
1106 return;
1107 setDoesNotThrow(F);
1108 setDoesNotCapture(F, 1);
1109 setDoesNotCapture(F, 2);
1110 } else if (Name == "snprintf") {
1111 if (FTy->getNumParams() != 3 ||
1112 !FTy->getParamType(0)->isPointerTy() ||
1113 !FTy->getParamType(2)->isPointerTy())
1114 return;
1115 setDoesNotThrow(F);
1116 setDoesNotCapture(F, 1);
1117 setDoesNotCapture(F, 3);
1118 } else if (Name == "setitimer") {
1119 if (FTy->getNumParams() != 3 ||
1120 !FTy->getParamType(1)->isPointerTy() ||
1121 !FTy->getParamType(2)->isPointerTy())
1122 return;
1123 setDoesNotThrow(F);
1124 setDoesNotCapture(F, 2);
1125 setDoesNotCapture(F, 3);
1126 } else if (Name == "system") {
1127 if (FTy->getNumParams() != 1 ||
1128 !FTy->getParamType(0)->isPointerTy())
1129 return;
1130 // May throw; "system" is a valid pthread cancellation point.
1131 setDoesNotCapture(F, 1);
1132 }
1133 break;
1134 case 'm':
1135 if (Name == "malloc") {
1136 if (FTy->getNumParams() != 1 ||
1137 !FTy->getReturnType()->isPointerTy())
1138 return;
1139 setDoesNotThrow(F);
1140 setDoesNotAlias(F, 0);
1141 } else if (Name == "memcmp") {
1142 if (FTy->getNumParams() != 3 ||
1143 !FTy->getParamType(0)->isPointerTy() ||
1144 !FTy->getParamType(1)->isPointerTy())
1145 return;
1146 setOnlyReadsMemory(F);
1147 setDoesNotThrow(F);
1148 setDoesNotCapture(F, 1);
1149 setDoesNotCapture(F, 2);
1150 } else if (Name == "memchr" ||
1151 Name == "memrchr") {
1152 if (FTy->getNumParams() != 3)
1153 return;
1154 setOnlyReadsMemory(F);
1155 setDoesNotThrow(F);
1156 } else if (Name == "modf" ||
1157 Name == "modff" ||
1158 Name == "modfl" ||
1159 Name == "memcpy" ||
1160 Name == "memccpy" ||
1161 Name == "memmove") {
1162 if (FTy->getNumParams() < 2 ||
1163 !FTy->getParamType(1)->isPointerTy())
1164 return;
1165 setDoesNotThrow(F);
1166 setDoesNotCapture(F, 2);
1167 } else if (Name == "memalign") {
1168 if (!FTy->getReturnType()->isPointerTy())
1169 return;
1170 setDoesNotAlias(F, 0);
1171 } else if (Name == "mkdir" ||
1172 Name == "mktime") {
1173 if (FTy->getNumParams() == 0 ||
1174 !FTy->getParamType(0)->isPointerTy())
1175 return;
1176 setDoesNotThrow(F);
1177 setDoesNotCapture(F, 1);
1178 }
1179 break;
1180 case 'r':
1181 if (Name == "realloc") {
1182 if (FTy->getNumParams() != 2 ||
1183 !FTy->getParamType(0)->isPointerTy() ||
1184 !FTy->getReturnType()->isPointerTy())
1185 return;
1186 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00001187 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00001188 setDoesNotCapture(F, 1);
1189 } else if (Name == "read") {
1190 if (FTy->getNumParams() != 3 ||
1191 !FTy->getParamType(1)->isPointerTy())
1192 return;
1193 // May throw; "read" is a valid pthread cancellation point.
1194 setDoesNotCapture(F, 2);
1195 } else if (Name == "rmdir" ||
1196 Name == "rewind" ||
1197 Name == "remove" ||
1198 Name == "realpath") {
1199 if (FTy->getNumParams() < 1 ||
1200 !FTy->getParamType(0)->isPointerTy())
1201 return;
1202 setDoesNotThrow(F);
1203 setDoesNotCapture(F, 1);
1204 } else if (Name == "rename" ||
1205 Name == "readlink") {
1206 if (FTy->getNumParams() < 2 ||
1207 !FTy->getParamType(0)->isPointerTy() ||
1208 !FTy->getParamType(1)->isPointerTy())
1209 return;
1210 setDoesNotThrow(F);
1211 setDoesNotCapture(F, 1);
1212 setDoesNotCapture(F, 2);
1213 }
1214 break;
1215 case 'w':
1216 if (Name == "write") {
1217 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1218 return;
1219 // May throw; "write" is a valid pthread cancellation point.
1220 setDoesNotCapture(F, 2);
1221 }
1222 break;
1223 case 'b':
1224 if (Name == "bcopy") {
1225 if (FTy->getNumParams() != 3 ||
1226 !FTy->getParamType(0)->isPointerTy() ||
1227 !FTy->getParamType(1)->isPointerTy())
1228 return;
1229 setDoesNotThrow(F);
1230 setDoesNotCapture(F, 1);
1231 setDoesNotCapture(F, 2);
1232 } else if (Name == "bcmp") {
1233 if (FTy->getNumParams() != 3 ||
1234 !FTy->getParamType(0)->isPointerTy() ||
1235 !FTy->getParamType(1)->isPointerTy())
1236 return;
1237 setDoesNotThrow(F);
1238 setOnlyReadsMemory(F);
1239 setDoesNotCapture(F, 1);
1240 setDoesNotCapture(F, 2);
1241 } else if (Name == "bzero") {
1242 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1243 return;
1244 setDoesNotThrow(F);
1245 setDoesNotCapture(F, 1);
1246 }
1247 break;
1248 case 'c':
1249 if (Name == "calloc") {
1250 if (FTy->getNumParams() != 2 ||
1251 !FTy->getReturnType()->isPointerTy())
1252 return;
1253 setDoesNotThrow(F);
1254 setDoesNotAlias(F, 0);
1255 } else if (Name == "chmod" ||
1256 Name == "chown" ||
1257 Name == "ctermid" ||
1258 Name == "clearerr" ||
1259 Name == "closedir") {
1260 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1261 return;
1262 setDoesNotThrow(F);
1263 setDoesNotCapture(F, 1);
1264 }
1265 break;
1266 case 'a':
1267 if (Name == "atoi" ||
1268 Name == "atol" ||
1269 Name == "atof" ||
1270 Name == "atoll") {
1271 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1272 return;
1273 setDoesNotThrow(F);
1274 setOnlyReadsMemory(F);
1275 setDoesNotCapture(F, 1);
1276 } else if (Name == "access") {
1277 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1278 return;
1279 setDoesNotThrow(F);
1280 setDoesNotCapture(F, 1);
1281 }
1282 break;
1283 case 'f':
1284 if (Name == "fopen") {
1285 if (FTy->getNumParams() != 2 ||
1286 !FTy->getReturnType()->isPointerTy() ||
1287 !FTy->getParamType(0)->isPointerTy() ||
1288 !FTy->getParamType(1)->isPointerTy())
1289 return;
1290 setDoesNotThrow(F);
1291 setDoesNotAlias(F, 0);
1292 setDoesNotCapture(F, 1);
1293 setDoesNotCapture(F, 2);
1294 } else if (Name == "fdopen") {
1295 if (FTy->getNumParams() != 2 ||
1296 !FTy->getReturnType()->isPointerTy() ||
1297 !FTy->getParamType(1)->isPointerTy())
1298 return;
1299 setDoesNotThrow(F);
1300 setDoesNotAlias(F, 0);
1301 setDoesNotCapture(F, 2);
1302 } else if (Name == "feof" ||
1303 Name == "free" ||
1304 Name == "fseek" ||
1305 Name == "ftell" ||
1306 Name == "fgetc" ||
1307 Name == "fseeko" ||
1308 Name == "ftello" ||
1309 Name == "fileno" ||
1310 Name == "fflush" ||
1311 Name == "fclose" ||
1312 Name == "fsetpos" ||
1313 Name == "flockfile" ||
1314 Name == "funlockfile" ||
1315 Name == "ftrylockfile") {
1316 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1317 return;
1318 setDoesNotThrow(F);
1319 setDoesNotCapture(F, 1);
1320 } else if (Name == "ferror") {
1321 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1322 return;
1323 setDoesNotThrow(F);
1324 setDoesNotCapture(F, 1);
1325 setOnlyReadsMemory(F);
1326 } else if (Name == "fputc" ||
1327 Name == "fstat" ||
1328 Name == "frexp" ||
1329 Name == "frexpf" ||
1330 Name == "frexpl" ||
1331 Name == "fstatvfs") {
1332 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1333 return;
1334 setDoesNotThrow(F);
1335 setDoesNotCapture(F, 2);
1336 } else if (Name == "fgets") {
1337 if (FTy->getNumParams() != 3 ||
1338 !FTy->getParamType(0)->isPointerTy() ||
1339 !FTy->getParamType(2)->isPointerTy())
1340 return;
1341 setDoesNotThrow(F);
1342 setDoesNotCapture(F, 3);
1343 } else if (Name == "fread" ||
1344 Name == "fwrite") {
1345 if (FTy->getNumParams() != 4 ||
1346 !FTy->getParamType(0)->isPointerTy() ||
1347 !FTy->getParamType(3)->isPointerTy())
1348 return;
1349 setDoesNotThrow(F);
1350 setDoesNotCapture(F, 1);
1351 setDoesNotCapture(F, 4);
1352 } else if (Name == "fputs" ||
1353 Name == "fscanf" ||
1354 Name == "fprintf" ||
1355 Name == "fgetpos") {
1356 if (FTy->getNumParams() < 2 ||
1357 !FTy->getParamType(0)->isPointerTy() ||
1358 !FTy->getParamType(1)->isPointerTy())
1359 return;
1360 setDoesNotThrow(F);
1361 setDoesNotCapture(F, 1);
1362 setDoesNotCapture(F, 2);
1363 }
1364 break;
1365 case 'g':
1366 if (Name == "getc" ||
1367 Name == "getlogin_r" ||
1368 Name == "getc_unlocked") {
1369 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1370 return;
1371 setDoesNotThrow(F);
1372 setDoesNotCapture(F, 1);
1373 } else if (Name == "getenv") {
1374 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1375 return;
1376 setDoesNotThrow(F);
1377 setOnlyReadsMemory(F);
1378 setDoesNotCapture(F, 1);
1379 } else if (Name == "gets" ||
1380 Name == "getchar") {
1381 setDoesNotThrow(F);
1382 } else if (Name == "getitimer") {
1383 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1384 return;
1385 setDoesNotThrow(F);
1386 setDoesNotCapture(F, 2);
1387 } else if (Name == "getpwnam") {
1388 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1389 return;
1390 setDoesNotThrow(F);
1391 setDoesNotCapture(F, 1);
1392 }
1393 break;
1394 case 'u':
1395 if (Name == "ungetc") {
1396 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1397 return;
1398 setDoesNotThrow(F);
1399 setDoesNotCapture(F, 2);
1400 } else if (Name == "uname" ||
1401 Name == "unlink" ||
1402 Name == "unsetenv") {
1403 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1404 return;
1405 setDoesNotThrow(F);
1406 setDoesNotCapture(F, 1);
1407 } else if (Name == "utime" ||
1408 Name == "utimes") {
1409 if (FTy->getNumParams() != 2 ||
1410 !FTy->getParamType(0)->isPointerTy() ||
1411 !FTy->getParamType(1)->isPointerTy())
1412 return;
1413 setDoesNotThrow(F);
1414 setDoesNotCapture(F, 1);
1415 setDoesNotCapture(F, 2);
1416 }
1417 break;
1418 case 'p':
1419 if (Name == "putc") {
1420 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1421 return;
1422 setDoesNotThrow(F);
1423 setDoesNotCapture(F, 2);
1424 } else if (Name == "puts" ||
1425 Name == "printf" ||
1426 Name == "perror") {
1427 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1428 return;
1429 setDoesNotThrow(F);
1430 setDoesNotCapture(F, 1);
1431 } else if (Name == "pread" ||
1432 Name == "pwrite") {
1433 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1434 return;
1435 // May throw; these are valid pthread cancellation points.
1436 setDoesNotCapture(F, 2);
1437 } else if (Name == "putchar") {
1438 setDoesNotThrow(F);
1439 } else if (Name == "popen") {
1440 if (FTy->getNumParams() != 2 ||
1441 !FTy->getReturnType()->isPointerTy() ||
1442 !FTy->getParamType(0)->isPointerTy() ||
1443 !FTy->getParamType(1)->isPointerTy())
1444 return;
1445 setDoesNotThrow(F);
1446 setDoesNotAlias(F, 0);
1447 setDoesNotCapture(F, 1);
1448 setDoesNotCapture(F, 2);
1449 } else if (Name == "pclose") {
1450 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1451 return;
1452 setDoesNotThrow(F);
1453 setDoesNotCapture(F, 1);
1454 }
1455 break;
1456 case 'v':
1457 if (Name == "vscanf") {
1458 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1459 return;
1460 setDoesNotThrow(F);
1461 setDoesNotCapture(F, 1);
1462 } else if (Name == "vsscanf" ||
1463 Name == "vfscanf") {
1464 if (FTy->getNumParams() != 3 ||
1465 !FTy->getParamType(1)->isPointerTy() ||
1466 !FTy->getParamType(2)->isPointerTy())
1467 return;
1468 setDoesNotThrow(F);
1469 setDoesNotCapture(F, 1);
1470 setDoesNotCapture(F, 2);
1471 } else if (Name == "valloc") {
1472 if (!FTy->getReturnType()->isPointerTy())
1473 return;
1474 setDoesNotThrow(F);
1475 setDoesNotAlias(F, 0);
1476 } else if (Name == "vprintf") {
1477 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1478 return;
1479 setDoesNotThrow(F);
1480 setDoesNotCapture(F, 1);
1481 } else if (Name == "vfprintf" ||
1482 Name == "vsprintf") {
1483 if (FTy->getNumParams() != 3 ||
1484 !FTy->getParamType(0)->isPointerTy() ||
1485 !FTy->getParamType(1)->isPointerTy())
1486 return;
1487 setDoesNotThrow(F);
1488 setDoesNotCapture(F, 1);
1489 setDoesNotCapture(F, 2);
1490 } else if (Name == "vsnprintf") {
1491 if (FTy->getNumParams() != 4 ||
1492 !FTy->getParamType(0)->isPointerTy() ||
1493 !FTy->getParamType(2)->isPointerTy())
1494 return;
1495 setDoesNotThrow(F);
1496 setDoesNotCapture(F, 1);
1497 setDoesNotCapture(F, 3);
1498 }
1499 break;
1500 case 'o':
1501 if (Name == "open") {
1502 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1503 return;
1504 // May throw; "open" is a valid pthread cancellation point.
1505 setDoesNotCapture(F, 1);
1506 } else if (Name == "opendir") {
1507 if (FTy->getNumParams() != 1 ||
1508 !FTy->getReturnType()->isPointerTy() ||
1509 !FTy->getParamType(0)->isPointerTy())
1510 return;
1511 setDoesNotThrow(F);
1512 setDoesNotAlias(F, 0);
1513 setDoesNotCapture(F, 1);
1514 }
1515 break;
1516 case 't':
1517 if (Name == "tmpfile") {
1518 if (!FTy->getReturnType()->isPointerTy())
1519 return;
1520 setDoesNotThrow(F);
1521 setDoesNotAlias(F, 0);
1522 } else if (Name == "times") {
1523 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1524 return;
1525 setDoesNotThrow(F);
1526 setDoesNotCapture(F, 1);
1527 }
1528 break;
1529 case 'h':
1530 if (Name == "htonl" ||
1531 Name == "htons") {
1532 setDoesNotThrow(F);
1533 setDoesNotAccessMemory(F);
1534 }
1535 break;
1536 case 'n':
1537 if (Name == "ntohl" ||
1538 Name == "ntohs") {
1539 setDoesNotThrow(F);
1540 setDoesNotAccessMemory(F);
1541 }
1542 break;
1543 case 'l':
1544 if (Name == "lstat") {
1545 if (FTy->getNumParams() != 2 ||
1546 !FTy->getParamType(0)->isPointerTy() ||
1547 !FTy->getParamType(1)->isPointerTy())
1548 return;
1549 setDoesNotThrow(F);
1550 setDoesNotCapture(F, 1);
1551 setDoesNotCapture(F, 2);
1552 } else if (Name == "lchown") {
1553 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1554 return;
1555 setDoesNotThrow(F);
1556 setDoesNotCapture(F, 1);
1557 }
1558 break;
1559 case 'q':
1560 if (Name == "qsort") {
1561 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1562 return;
1563 // May throw; places call through function pointer.
1564 setDoesNotCapture(F, 4);
1565 }
1566 break;
1567 case '_':
1568 if (Name == "__strdup" ||
1569 Name == "__strndup") {
1570 if (FTy->getNumParams() < 1 ||
1571 !FTy->getReturnType()->isPointerTy() ||
1572 !FTy->getParamType(0)->isPointerTy())
1573 return;
1574 setDoesNotThrow(F);
1575 setDoesNotAlias(F, 0);
1576 setDoesNotCapture(F, 1);
1577 } else if (Name == "__strtok_r") {
1578 if (FTy->getNumParams() != 3 ||
1579 !FTy->getParamType(1)->isPointerTy())
1580 return;
1581 setDoesNotThrow(F);
1582 setDoesNotCapture(F, 2);
1583 } else if (Name == "_IO_getc") {
1584 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1585 return;
1586 setDoesNotThrow(F);
1587 setDoesNotCapture(F, 1);
1588 } else if (Name == "_IO_putc") {
1589 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1590 return;
1591 setDoesNotThrow(F);
1592 setDoesNotCapture(F, 2);
1593 }
1594 break;
1595 case 1:
1596 if (Name == "\1__isoc99_scanf") {
1597 if (FTy->getNumParams() < 1 ||
1598 !FTy->getParamType(0)->isPointerTy())
1599 return;
1600 setDoesNotThrow(F);
1601 setDoesNotCapture(F, 1);
1602 } else if (Name == "\1stat64" ||
1603 Name == "\1lstat64" ||
1604 Name == "\1statvfs64" ||
1605 Name == "\1__isoc99_sscanf") {
1606 if (FTy->getNumParams() < 1 ||
1607 !FTy->getParamType(0)->isPointerTy() ||
1608 !FTy->getParamType(1)->isPointerTy())
1609 return;
1610 setDoesNotThrow(F);
1611 setDoesNotCapture(F, 1);
1612 setDoesNotCapture(F, 2);
1613 } else if (Name == "\1fopen64") {
1614 if (FTy->getNumParams() != 2 ||
1615 !FTy->getReturnType()->isPointerTy() ||
1616 !FTy->getParamType(0)->isPointerTy() ||
1617 !FTy->getParamType(1)->isPointerTy())
1618 return;
1619 setDoesNotThrow(F);
1620 setDoesNotAlias(F, 0);
1621 setDoesNotCapture(F, 1);
1622 setDoesNotCapture(F, 2);
1623 } else if (Name == "\1fseeko64" ||
1624 Name == "\1ftello64") {
1625 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1626 return;
1627 setDoesNotThrow(F);
1628 setDoesNotCapture(F, 1);
1629 } else if (Name == "\1tmpfile64") {
1630 if (!FTy->getReturnType()->isPointerTy())
1631 return;
1632 setDoesNotThrow(F);
1633 setDoesNotAlias(F, 0);
1634 } else if (Name == "\1fstat64" ||
1635 Name == "\1fstatvfs64") {
1636 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1637 return;
1638 setDoesNotThrow(F);
1639 setDoesNotCapture(F, 2);
1640 } else if (Name == "\1open64") {
1641 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1642 return;
1643 // May throw; "open" is a valid pthread cancellation point.
1644 setDoesNotCapture(F, 1);
1645 }
1646 break;
1647 }
1648}
1649
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001650/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001651///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001652bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001653 Modified = false;
1654 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1655 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00001656 if (F.isDeclaration() && F.hasName())
1657 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001658 }
1659 return Modified;
1660}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001661
1662// TODO:
1663// Additional cases that we need to add to this file:
1664//
1665// cbrt:
1666// * cbrt(expN(X)) -> expN(x/3)
1667// * cbrt(sqrt(x)) -> pow(x,1/6)
1668// * cbrt(sqrt(x)) -> pow(x,1/9)
1669//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001670// exp, expf, expl:
1671// * exp(log(x)) -> x
1672//
1673// log, logf, logl:
1674// * log(exp(x)) -> x
1675// * log(x**y) -> y*log(x)
1676// * log(exp(y)) -> y*log(e)
1677// * log(exp2(y)) -> y*log(2)
1678// * log(exp10(y)) -> y*log(10)
1679// * log(sqrt(x)) -> 0.5*log(x)
1680// * log(pow(x,y)) -> y*log(x)
1681//
1682// lround, lroundf, lroundl:
1683// * lround(cnst) -> cnst'
1684//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001685// pow, powf, powl:
1686// * pow(exp(x),y) -> exp(x*y)
1687// * pow(sqrt(x),y) -> pow(x,y*0.5)
1688// * pow(pow(x,y),z)-> pow(x,y*z)
1689//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001690// round, roundf, roundl:
1691// * round(cnst) -> cnst'
1692//
1693// signbit:
1694// * signbit(cnst) -> cnst'
1695// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1696//
1697// sqrt, sqrtf, sqrtl:
1698// * sqrt(expN(x)) -> expN(x*0.5)
1699// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1700// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1701//
Chris Lattner18c7f802012-02-05 02:29:43 +00001702// strchr:
1703// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001704// tan, tanf, tanl:
1705// * tan(atan(x)) -> x
1706//
1707// trunc, truncf, truncl:
1708// * trunc(cnst) -> cnst'
1709//
1710//