blob: 22a01fc968f5286ba29ef897c170b856a15d9538 [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
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000093/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +000094/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000095static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
96 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
97 UI != E; ++UI) {
98 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
99 if (IC->isEquality())
100 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
101 if (C->isNullValue())
102 continue;
103 // Unknown instruction.
104 return false;
105 }
106 return true;
107}
Nadav Rotema94d6e82012-07-24 10:51:42 +0000108
Richard Osborne36498242011-03-03 13:17:51 +0000109static bool CallHasFloatingPointArgument(const CallInst *CI) {
110 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
111 it != e; ++it) {
112 if ((*it)->getType()->isFloatingPointTy())
113 return true;
114 }
115 return false;
116}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000117
Benjamin Kramer386e9182010-06-15 21:34:25 +0000118/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
119/// comparisons with With.
120static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
121 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
122 UI != E; ++UI) {
123 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
124 if (IC->isEquality() && IC->getOperand(1) == With)
125 continue;
126 // Unknown instruction.
127 return false;
128 }
129 return true;
130}
131
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000132//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000133// String and Memory LibCall Optimizations
134//===----------------------------------------------------------------------===//
135
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000136namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000137//===---------------------------------------===//
138// 'strchr' Optimizations
139
Chris Lattner3e8b6632009-09-02 06:11:42 +0000140struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000141 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000142 // Verify the "strchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000143 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000145 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000146 FT->getParamType(0) != FT->getReturnType() ||
147 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000149
Gabor Greifaee5dc12010-06-24 10:42:46 +0000150 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000151
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000152 // If the second operand is non-constant, see if we can compute the length
153 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000154 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000155 if (CharC == 0) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000156 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000157 if (!TD) return 0;
158
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000159 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000160 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000161 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000162
Gabor Greifaee5dc12010-06-24 10:42:46 +0000163 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000164 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Nuno Lopes51004df2012-07-25 16:46:31 +0000165 B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000166 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000167
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000168 // Otherwise, the character is a constant, see if the first argument is
169 // a string literal. If so, we can constant fold.
Chris Lattner18c7f802012-02-05 02:29:43 +0000170 StringRef Str;
171 if (!getConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000172 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000173
Chris Lattner18c7f802012-02-05 02:29:43 +0000174 // Compute the offset, make sure to handle the case when we're searching for
175 // zero (a weird way to spell strlen).
176 size_t I = CharC->getSExtValue() == 0 ?
177 Str.size() : Str.find(CharC->getSExtValue());
178 if (I == StringRef::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000179 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000180
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000181 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000182 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000183 }
184};
185
186//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000187// 'strrchr' Optimizations
188
189struct StrRChrOpt : public LibCallOptimization {
190 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
191 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000192 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000193 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000194 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000195 FT->getParamType(0) != FT->getReturnType() ||
196 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000197 return 0;
198
199 Value *SrcStr = CI->getArgOperand(0);
200 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
201
202 // Cannot fold anything if we're not looking for a constant.
203 if (!CharC)
204 return 0;
205
Chris Lattner18c7f802012-02-05 02:29:43 +0000206 StringRef Str;
207 if (!getConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000208 // strrchr(s, 0) -> strchr(s, 0)
209 if (TD && CharC->isZero())
Nuno Lopes51004df2012-07-25 16:46:31 +0000210 return EmitStrChr(SrcStr, '\0', B, TD, TLI);
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000211 return 0;
212 }
213
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000214 // Compute the offset.
Chris Lattner18c7f802012-02-05 02:29:43 +0000215 size_t I = CharC->getSExtValue() == 0 ?
216 Str.size() : Str.rfind(CharC->getSExtValue());
217 if (I == StringRef::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000218 return Constant::getNullValue(CI->getType());
219
220 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000221 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000222 }
223};
224
225//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000226// 'strcmp' Optimizations
227
Chris Lattner3e8b6632009-09-02 06:11:42 +0000228struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000229 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000230 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000231 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000232 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000233 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000235 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000236 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000237
Gabor Greifaee5dc12010-06-24 10:42:46 +0000238 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000239 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000240 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000241
Chris Lattner18c7f802012-02-05 02:29:43 +0000242 StringRef Str1, Str2;
243 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
244 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000245
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000246 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000247 if (HasStr1 && HasStr2)
Chris Lattner18c7f802012-02-05 02:29:43 +0000248 return ConstantInt::get(CI->getType(), Str1.compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000249
250 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
251 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
252 CI->getType()));
253
254 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
255 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000256
257 // strcmp(P, "x") -> memcmp(P, "x", 2)
258 uint64_t Len1 = GetStringLength(Str1P);
259 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000260 if (Len1 && Len2) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000261 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000262 if (!TD) return 0;
263
Nick Lewycky13a09e22008-12-21 00:19:21 +0000264 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000265 ConstantInt::get(TD->getIntPtrType(*Context),
Nuno Lopes51004df2012-07-25 16:46:31 +0000266 std::min(Len1, Len2)), B, TD, TLI);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000267 }
268
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000269 return 0;
270 }
271};
272
273//===---------------------------------------===//
274// 'strncmp' Optimizations
275
Chris Lattner3e8b6632009-09-02 06:11:42 +0000276struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000277 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000278 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000279 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000280 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000281 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000282 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000283 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000284 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000285 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000286
Gabor Greifaee5dc12010-06-24 10:42:46 +0000287 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000288 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000289 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000290
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000291 // Get the length argument if it is constant.
292 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000293 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000294 Length = LengthArg->getZExtValue();
295 else
296 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000297
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000298 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000299 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000300
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000301 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000302 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD, TLI);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000303
Chris Lattner18c7f802012-02-05 02:29:43 +0000304 StringRef Str1, Str2;
305 bool HasStr1 = getConstantStringInfo(Str1P, Str1);
306 bool HasStr2 = getConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000307
Eli Friedman79286082011-10-05 22:27:16 +0000308 // strncmp(x, y) -> cnst (if both x and y are constant strings)
309 if (HasStr1 && HasStr2) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000310 StringRef SubStr1 = Str1.substr(0, Length);
311 StringRef SubStr2 = Str2.substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000312 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
313 }
314
315 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
316 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
317 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000318
Bill Wendling0582ae92009-03-13 04:39:26 +0000319 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000320 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000321
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000322 return 0;
323 }
324};
325
326
327//===---------------------------------------===//
328// 'strcpy' Optimizations
329
Chris Lattner3e8b6632009-09-02 06:11:42 +0000330struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000331 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
332
333 StrCpyOpt(bool c) : OptChkCall(c) {}
334
Eric Christopher7a61d702008-08-08 19:39:37 +0000335 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000336 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000337 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000338 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000339 if (FT->getNumParams() != NumParams ||
340 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000341 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000342 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000343 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000344
Gabor Greifaee5dc12010-06-24 10:42:46 +0000345 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000346 if (Dst == Src) // strcpy(x,x) -> x
347 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000348
Micah Villmow3574eca2012-10-08 16:38:25 +0000349 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000350 if (!TD) return 0;
351
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000352 // See if we can get the length of the input string.
353 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000354 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000355
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000356 // We have enough information to now generate the memcpy call to do the
357 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000358 if (!OptChkCall ||
359 !EmitMemCpyChk(Dst, Src,
360 ConstantInt::get(TD->getIntPtrType(*Context), Len),
361 CI->getArgOperand(2), B, TD, TLI))
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000362 B.CreateMemCpy(Dst, Src,
363 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000364 return Dst;
365 }
366};
367
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000368//===---------------------------------------===//
David Majnemerac782662012-05-15 11:46:21 +0000369// 'stpcpy' Optimizations
370
371struct StpCpyOpt: public LibCallOptimization {
372 bool OptChkCall; // True if it's optimizing a __stpcpy_chk libcall.
373
374 StpCpyOpt(bool c) : OptChkCall(c) {}
375
376 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
377 // Verify the "stpcpy" function prototype.
378 unsigned NumParams = OptChkCall ? 3 : 2;
379 FunctionType *FT = Callee->getFunctionType();
380 if (FT->getNumParams() != NumParams ||
381 FT->getReturnType() != FT->getParamType(0) ||
382 FT->getParamType(0) != FT->getParamType(1) ||
383 FT->getParamType(0) != B.getInt8PtrTy())
384 return 0;
385
Micah Villmow3574eca2012-10-08 16:38:25 +0000386 // These optimizations require DataLayout.
David Majnemerac782662012-05-15 11:46:21 +0000387 if (!TD) return 0;
388
389 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Nuno Lopes51004df2012-07-25 16:46:31 +0000390 if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
391 Value *StrLen = EmitStrLen(Src, B, TD, TLI);
392 return StrLen ? B.CreateInBoundsGEP(Dst, StrLen) : 0;
393 }
David Majnemerac782662012-05-15 11:46:21 +0000394
395 // See if we can get the length of the input string.
396 uint64_t Len = GetStringLength(Src);
397 if (Len == 0) return 0;
398
399 Value *LenV = ConstantInt::get(TD->getIntPtrType(*Context), Len);
400 Value *DstEnd = B.CreateGEP(Dst,
401 ConstantInt::get(TD->getIntPtrType(*Context),
402 Len - 1));
403
404 // We have enough information to now generate the memcpy call to do the
405 // copy for us. Make a memcpy to copy the nul byte with align = 1.
Nuno Lopescd31fc72012-07-26 17:10:46 +0000406 if (!OptChkCall || !EmitMemCpyChk(Dst, Src, LenV, CI->getArgOperand(2), B,
407 TD, TLI))
David Majnemerac782662012-05-15 11:46:21 +0000408 B.CreateMemCpy(Dst, Src, LenV, 1);
409 return DstEnd;
410 }
411};
412
413//===---------------------------------------===//
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000414// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000415
Chris Lattner3e8b6632009-09-02 06:11:42 +0000416struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000417 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000418 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000419 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
420 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000421 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000422 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000423 return 0;
424
Gabor Greifaee5dc12010-06-24 10:42:46 +0000425 Value *Dst = CI->getArgOperand(0);
426 Value *Src = CI->getArgOperand(1);
427 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000428
429 // See if we can get the length of the input string.
430 uint64_t SrcLen = GetStringLength(Src);
431 if (SrcLen == 0) return 0;
432 --SrcLen;
433
434 if (SrcLen == 0) {
435 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000436 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000437 return Dst;
438 }
439
440 uint64_t Len;
441 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
442 Len = LengthArg->getZExtValue();
443 else
444 return 0;
445
446 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
447
Micah Villmow3574eca2012-10-08 16:38:25 +0000448 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000449 if (!TD) return 0;
450
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000451 // Let strncpy handle the zero padding
452 if (Len > SrcLen+1) return 0;
453
454 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000455 B.CreateMemCpy(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000457
458 return Dst;
459 }
460};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000461
462//===---------------------------------------===//
463// 'strlen' Optimizations
464
Chris Lattner3e8b6632009-09-02 06:11:42 +0000465struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000466 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000467 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000468 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000469 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000470 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000471 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000472
Gabor Greifaee5dc12010-06-24 10:42:46 +0000473 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000474
475 // Constant folding: strlen("xyz") -> 3
476 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000477 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000478
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000479 // strlen(x) != 0 --> *x != 0
480 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000481 if (IsOnlyUsedInZeroEqualityComparison(CI))
482 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
483 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000484 }
485};
486
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000487
488//===---------------------------------------===//
489// 'strpbrk' Optimizations
490
491struct StrPBrkOpt : public LibCallOptimization {
492 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000493 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000494 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000495 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000496 FT->getParamType(1) != FT->getParamType(0) ||
497 FT->getReturnType() != FT->getParamType(0))
498 return 0;
499
Chris Lattner18c7f802012-02-05 02:29:43 +0000500 StringRef S1, S2;
501 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
502 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000503
504 // strpbrk(s, "") -> NULL
505 // strpbrk("", s) -> NULL
506 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
507 return Constant::getNullValue(CI->getType());
508
509 // Constant folding.
510 if (HasS1 && HasS2) {
511 size_t I = S1.find_first_of(S2);
512 if (I == std::string::npos) // No match.
513 return Constant::getNullValue(CI->getType());
514
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000515 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000516 }
517
518 // strpbrk(s, "a") -> strchr(s, 'a')
519 if (TD && HasS2 && S2.size() == 1)
Nuno Lopes51004df2012-07-25 16:46:31 +0000520 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD, TLI);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000521
522 return 0;
523 }
524};
525
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000527// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000528
Chris Lattner3e8b6632009-09-02 06:11:42 +0000529struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000530 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000531 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000532 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000533 !FT->getParamType(0)->isPointerTy() ||
534 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000535 return 0;
536
Gabor Greifaee5dc12010-06-24 10:42:46 +0000537 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000538 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000539 // With a null EndPtr, this function won't capture the main argument.
540 // It would be readonly too, except that it still may write to errno.
Bill Wendling7d2f2492012-10-10 07:36:45 +0000541 Attributes::Builder B;
542 B.addAttribute(Attributes::NoCapture);
543 CI->addAttribute(1, Attributes::get(B));
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000544 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000545
546 return 0;
547 }
548};
549
Chris Lattner24604112009-12-16 09:32:05 +0000550//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000551// 'strspn' Optimizations
552
553struct StrSpnOpt : public LibCallOptimization {
554 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000555 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000556 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000557 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000558 FT->getParamType(1) != FT->getParamType(0) ||
559 !FT->getReturnType()->isIntegerTy())
560 return 0;
561
Chris Lattner18c7f802012-02-05 02:29:43 +0000562 StringRef S1, S2;
563 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
564 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000565
566 // strspn(s, "") -> 0
567 // strspn("", s) -> 0
568 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
569 return Constant::getNullValue(CI->getType());
570
571 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000572 if (HasS1 && HasS2) {
573 size_t Pos = S1.find_first_not_of(S2);
574 if (Pos == StringRef::npos) Pos = S1.size();
575 return ConstantInt::get(CI->getType(), Pos);
576 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000577
578 return 0;
579 }
580};
581
582//===---------------------------------------===//
583// 'strcspn' Optimizations
584
585struct StrCSpnOpt : public LibCallOptimization {
586 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000587 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000588 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000589 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000590 FT->getParamType(1) != FT->getParamType(0) ||
591 !FT->getReturnType()->isIntegerTy())
592 return 0;
593
Chris Lattner18c7f802012-02-05 02:29:43 +0000594 StringRef S1, S2;
595 bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
596 bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000597
598 // strcspn("", s) -> 0
599 if (HasS1 && S1.empty())
600 return Constant::getNullValue(CI->getType());
601
602 // Constant folding.
Chris Lattner18c7f802012-02-05 02:29:43 +0000603 if (HasS1 && HasS2) {
604 size_t Pos = S1.find_first_of(S2);
605 if (Pos == StringRef::npos) Pos = S1.size();
606 return ConstantInt::get(CI->getType(), Pos);
607 }
Benjamin Kramer9510a252010-09-30 00:58:35 +0000608
609 // strcspn(s, "") -> strlen(s)
610 if (TD && HasS2 && S2.empty())
Nuno Lopes51004df2012-07-25 16:46:31 +0000611 return EmitStrLen(CI->getArgOperand(0), B, TD, TLI);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000612
613 return 0;
614 }
615};
616
617//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000618// 'strstr' Optimizations
619
620struct StrStrOpt : public LibCallOptimization {
621 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000622 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000623 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000624 !FT->getParamType(0)->isPointerTy() ||
625 !FT->getParamType(1)->isPointerTy() ||
626 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000627 return 0;
628
629 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000630 if (CI->getArgOperand(0) == CI->getArgOperand(1))
631 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000632
Benjamin Kramer386e9182010-06-15 21:34:25 +0000633 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000634 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
Nuno Lopes51004df2012-07-25 16:46:31 +0000635 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD, TLI);
636 if (!StrLen)
637 return 0;
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000638 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Nuno Lopes51004df2012-07-25 16:46:31 +0000639 StrLen, B, TD, TLI);
640 if (!StrNCmp)
641 return 0;
Benjamin Kramer386e9182010-06-15 21:34:25 +0000642 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
643 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000644 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000645 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
646 ConstantInt::getNullValue(StrNCmp->getType()),
647 "cmp");
648 Old->replaceAllUsesWith(Cmp);
649 Old->eraseFromParent();
650 }
651 return CI;
652 }
653
Chris Lattner24604112009-12-16 09:32:05 +0000654 // See if either input string is a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +0000655 StringRef SearchStr, ToFindStr;
656 bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
657 bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000658
Chris Lattner24604112009-12-16 09:32:05 +0000659 // fold strstr(x, "") -> x.
660 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000661 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000662
Chris Lattner24604112009-12-16 09:32:05 +0000663 // If both strings are known, constant fold it.
664 if (HasStr1 && HasStr2) {
665 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000666
Chris Lattner18c7f802012-02-05 02:29:43 +0000667 if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000668 return Constant::getNullValue(CI->getType());
669
670 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000671 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000672 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
673 return B.CreateBitCast(Result, CI->getType());
674 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000675
Chris Lattner24604112009-12-16 09:32:05 +0000676 // fold strstr(x, "y") -> strchr(x, 'y').
Nuno Lopes51004df2012-07-25 16:46:31 +0000677 if (HasStr2 && ToFindStr.size() == 1) {
678 Value *StrChr= EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TD, TLI);
679 return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : 0;
680 }
Chris Lattner24604112009-12-16 09:32:05 +0000681 return 0;
682 }
683};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000684
Nick Lewycky4c498412009-02-13 15:31:46 +0000685
686//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000687// 'memcmp' Optimizations
688
Chris Lattner3e8b6632009-09-02 06:11:42 +0000689struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000690 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000691 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000692 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
693 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000694 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000695 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000696
Gabor Greifaee5dc12010-06-24 10:42:46 +0000697 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000698
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000699 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000700 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000701
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000702 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000703 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000704 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000705 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000706
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000707 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000708 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000709
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000710 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
711 if (Len == 1) {
712 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
713 CI->getType(), "lhsv");
714 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
715 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000716 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000717 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000718
Benjamin Kramer992a6372009-11-05 17:44:22 +0000719 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Chris Lattner18c7f802012-02-05 02:29:43 +0000720 StringRef LHSStr, RHSStr;
721 if (getConstantStringInfo(LHS, LHSStr) &&
722 getConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000723 // Make sure we're not reading out-of-bounds memory.
Chris Lattner18c7f802012-02-05 02:29:43 +0000724 if (Len > LHSStr.size() || Len > RHSStr.size())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000725 return 0;
726 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
727 return ConstantInt::get(CI->getType(), Ret);
728 }
729
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000730 return 0;
731 }
732};
733
734//===---------------------------------------===//
735// 'memcpy' Optimizations
736
Chris Lattner3e8b6632009-09-02 06:11:42 +0000737struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000738 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000739 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000740 if (!TD) return 0;
741
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000742 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000743 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000744 !FT->getParamType(0)->isPointerTy() ||
745 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000746 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000747 return 0;
748
749 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000750 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
751 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000752 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000753 }
754};
755
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000756//===---------------------------------------===//
757// 'memmove' Optimizations
758
Chris Lattner3e8b6632009-09-02 06:11:42 +0000759struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000760 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000761 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000762 if (!TD) return 0;
763
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000764 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000765 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000766 !FT->getParamType(0)->isPointerTy() ||
767 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000768 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000769 return 0;
770
771 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000772 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
773 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000774 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000775 }
776};
777
778//===---------------------------------------===//
779// 'memset' Optimizations
780
Chris Lattner3e8b6632009-09-02 06:11:42 +0000781struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000782 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000783 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +0000784 if (!TD) return 0;
785
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000786 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000787 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000788 !FT->getParamType(0)->isPointerTy() ||
789 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000790 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000791 return 0;
792
793 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000794 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
795 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000796 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000797 }
798};
799
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000800//===----------------------------------------------------------------------===//
801// Math Library Optimizations
802//===----------------------------------------------------------------------===//
803
804//===---------------------------------------===//
Chad Rosierec7e92a2012-08-22 17:22:33 +0000805// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000806
Chad Rosierec7e92a2012-08-22 17:22:33 +0000807struct UnaryDoubleFPOpt : public LibCallOptimization {
808 bool CheckRetType;
809 UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
810 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
811 FunctionType *FT = Callee->getFunctionType();
812 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
813 !FT->getParamType(0)->isDoubleTy())
814 return 0;
815
816 if (CheckRetType) {
817 // Check if all the uses for function like 'sin' are converted to float.
818 for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
819 ++UseI) {
820 FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
821 if (Cast == 0 || !Cast->getType()->isFloatTy())
822 return 0;
823 }
824 }
825
826 // If this is something like 'floor((double)floatval)', convert to floorf.
827 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
828 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
829 return 0;
830
831 // floor((double)floatval) -> (double)floorf(floatval)
832 Value *V = Cast->getOperand(0);
833 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
834 return B.CreateFPExt(V, B.getDoubleTy());
835 }
836};
837
838//===---------------------------------------===//
839// 'cos*' Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000840struct CosOpt : public LibCallOptimization {
841 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000842 Value *Ret = NULL;
843 if (UnsafeFPShrink && Callee->getName() == "cos" &&
844 TLI->has(LibFunc::cosf)) {
845 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
846 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
847 }
848
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000849 FunctionType *FT = Callee->getFunctionType();
850 // Just make sure this has 1 argument of FP type, which matches the
851 // result type.
852 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
853 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000854 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000855
856 // cos(-x) -> cos(x)
857 Value *Op1 = CI->getArgOperand(0);
858 if (BinaryOperator::isFNeg(Op1)) {
859 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
860 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
861 }
Chad Rosierec7e92a2012-08-22 17:22:33 +0000862 return Ret;
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000863 }
864};
865
866//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000867// 'pow*' Optimizations
868
Chris Lattner3e8b6632009-09-02 06:11:42 +0000869struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000870 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000871 Value *Ret = NULL;
872 if (UnsafeFPShrink && Callee->getName() == "pow" &&
873 TLI->has(LibFunc::powf)) {
874 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
875 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
876 }
877
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000878 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000879 // Just make sure this has 2 arguments of the same FP type, which match the
880 // result type.
881 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
882 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000883 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000884 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000885
Gabor Greifaee5dc12010-06-24 10:42:46 +0000886 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000887 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
888 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
889 return Op1C;
890 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000891 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000892 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000893
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000894 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
Chad Rosierec7e92a2012-08-22 17:22:33 +0000895 if (Op2C == 0) return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000896
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000897 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000898 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000899
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000900 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000901 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
902 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000903 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000904 // TODO: In fast-math mode, this could be just sqrt(x).
905 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000906 Value *Inf = ConstantFP::getInfinity(CI->getType());
907 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000908 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
909 Callee->getAttributes());
910 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
911 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000912 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
913 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000914 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000915 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000916
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000917 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
918 return Op1;
919 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000920 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000921 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000922 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000923 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000924 return 0;
925 }
926};
927
928//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000929// 'exp2' Optimizations
930
Chris Lattner3e8b6632009-09-02 06:11:42 +0000931struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000932 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chad Rosierec7e92a2012-08-22 17:22:33 +0000933 Value *Ret = NULL;
934 if (UnsafeFPShrink && Callee->getName() == "exp2" &&
935 TLI->has(LibFunc::exp2)) {
936 UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
937 Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
938 }
939
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000940 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000941 // Just make sure this has 1 argument of FP type, which matches the
942 // result type.
943 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000944 !FT->getParamType(0)->isFloatingPointTy())
Chad Rosierec7e92a2012-08-22 17:22:33 +0000945 return Ret;
Eric Christopher37c8b862009-10-07 21:14:25 +0000946
Gabor Greifaee5dc12010-06-24 10:42:46 +0000947 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000948 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
949 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
950 Value *LdExpArg = 0;
951 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
952 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000953 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000954 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
955 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000956 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000957 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000958
Chris Lattnere818f772008-05-02 18:43:35 +0000959 if (LdExpArg) {
960 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000961 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000962 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000963 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000964 Name = "ldexp";
965 else
966 Name = "ldexpl";
967
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000968 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000969 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000970 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000971
972 Module *M = Caller->getParent();
973 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000974 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000975 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000976 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
977 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
978 CI->setCallingConv(F->getCallingConv());
979
980 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000981 }
Chad Rosierec7e92a2012-08-22 17:22:33 +0000982 return Ret;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000983 }
984};
985
986//===----------------------------------------------------------------------===//
987// Integer Optimizations
988//===----------------------------------------------------------------------===//
989
990//===---------------------------------------===//
991// 'ffs*' Optimizations
992
Chris Lattner3e8b6632009-09-02 06:11:42 +0000993struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000994 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000995 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000996 // Just make sure this has 2 arguments of the same FP type, which match the
997 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000998 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000999 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001000 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001001 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001002
Gabor Greifaee5dc12010-06-24 10:42:46 +00001003 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001004
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001005 // Constant fold.
1006 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1007 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001008 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001009 // ffs(c) -> cttz(c)+1
1010 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001011 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001012
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001013 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001014 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001015 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001016 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001017 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001018 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1019 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001020
Benjamin Kramera9390a42011-09-27 20:39:19 +00001021 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001022 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001023 }
1024};
1025
1026//===---------------------------------------===//
1027// 'isdigit' Optimizations
1028
Chris Lattner3e8b6632009-09-02 06:11:42 +00001029struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001030 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001031 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001032 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001033 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001034 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001035 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001036
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001037 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001038 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001039 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1040 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001041 return B.CreateZExt(Op, CI->getType());
1042 }
1043};
1044
1045//===---------------------------------------===//
1046// 'isascii' Optimizations
1047
Chris Lattner3e8b6632009-09-02 06:11:42 +00001048struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001049 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001050 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001051 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001052 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001053 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001054 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001055
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001056 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001057 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001058 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001059 return B.CreateZExt(Op, CI->getType());
1060 }
1061};
Eric Christopher37c8b862009-10-07 21:14:25 +00001062
Chris Lattner313f0e62008-06-09 08:26:51 +00001063//===---------------------------------------===//
1064// 'abs', 'labs', 'llabs' Optimizations
1065
Chris Lattner3e8b6632009-09-02 06:11:42 +00001066struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001067 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001068 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001069 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001070 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001071 FT->getParamType(0) != FT->getReturnType())
1072 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001073
Chris Lattner313f0e62008-06-09 08:26:51 +00001074 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001075 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001076 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001077 "ispos");
1078 Value *Neg = B.CreateNeg(Op, "neg");
1079 return B.CreateSelect(Pos, Op, Neg);
1080 }
1081};
Eric Christopher37c8b862009-10-07 21:14:25 +00001082
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001083
1084//===---------------------------------------===//
1085// 'toascii' Optimizations
1086
Chris Lattner3e8b6632009-09-02 06:11:42 +00001087struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001088 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001089 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001090 // We require i32(i32)
1091 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001092 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001093 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001094
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001095 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001096 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001097 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001098 }
1099};
1100
1101//===----------------------------------------------------------------------===//
1102// Formatting and IO Optimizations
1103//===----------------------------------------------------------------------===//
1104
1105//===---------------------------------------===//
1106// 'printf' Optimizations
1107
Chris Lattner3e8b6632009-09-02 06:11:42 +00001108struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001109 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1110 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001111 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001112 StringRef FormatStr;
1113 if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001114 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001115
1116 // Empty format string -> noop.
1117 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001118 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001119 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001120
Daniel Dunbard02be242011-02-12 18:19:57 +00001121 // Do not do any of the following transformations if the printf return value
1122 // is used, in general the printf return value is not compatible with either
1123 // putchar() or puts().
1124 if (!CI->use_empty())
1125 return 0;
1126
1127 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001128 if (FormatStr.size() == 1) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001129 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001130 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001131 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001132 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001133
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001134 // printf("foo\n") --> puts("foo")
1135 if (FormatStr[FormatStr.size()-1] == '\n' &&
1136 FormatStr.find('%') == std::string::npos) { // no format characters.
1137 // Create a string literal with no \n on it. We expect the constant merge
1138 // pass to be run after this pass, to merge duplicate strings.
Chris Lattner18c7f802012-02-05 02:29:43 +00001139 FormatStr = FormatStr.drop_back();
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001140 Value *GV = B.CreateGlobalString(FormatStr, "str");
Nuno Lopes51004df2012-07-25 16:46:31 +00001141 Value *NewCI = EmitPutS(GV, B, TD, TLI);
1142 return (CI->use_empty() || !NewCI) ?
1143 NewCI :
1144 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001145 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001146
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001147 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001148 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001149 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001150 CI->getArgOperand(1)->getType()->isIntegerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001151 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001152
Nuno Lopescd31fc72012-07-26 17:10:46 +00001153 if (CI->use_empty() || !Res) return Res;
Chris Lattner74965f22009-11-09 04:57:04 +00001154 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001155 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001156
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001157 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001158 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001159 CI->getArgOperand(1)->getType()->isPointerTy()) {
Nuno Lopes51004df2012-07-25 16:46:31 +00001160 return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001161 }
1162 return 0;
1163 }
Richard Osborne36498242011-03-03 13:17:51 +00001164
1165 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1166 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001167 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001168 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1169 !(FT->getReturnType()->isIntegerTy() ||
1170 FT->getReturnType()->isVoidTy()))
1171 return 0;
1172
1173 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1174 return V;
1175 }
1176
1177 // printf(format, ...) -> iprintf(format, ...) if no floating point
1178 // arguments.
1179 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1180 Module *M = B.GetInsertBlock()->getParent()->getParent();
1181 Constant *IPrintFFn =
1182 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1183 CallInst *New = cast<CallInst>(CI->clone());
1184 New->setCalledFunction(IPrintFFn);
1185 B.Insert(New);
1186 return New;
1187 }
1188 return 0;
1189 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001190};
1191
1192//===---------------------------------------===//
1193// 'sprintf' Optimizations
1194
Chris Lattner3e8b6632009-09-02 06:11:42 +00001195struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001196 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1197 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001198 // Check for a fixed format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001199 StringRef FormatStr;
1200 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001201 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001202
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001203 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001204 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001205 // Make sure there's no % in the constant array. We could try to handle
1206 // %% -> % in the future if we cared.
1207 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1208 if (FormatStr[i] == '%')
1209 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001210
Micah Villmow3574eca2012-10-08 16:38:25 +00001211 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001212 if (!TD) return 0;
1213
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001214 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001215 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1216 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1217 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001218 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001219 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001220
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 // The remaining optimizations require the format string to be "%s" or "%c"
1222 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001223 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1224 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001225 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001226
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001227 // Decode the second character of the format string.
1228 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001229 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001230 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001231 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001232 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001233 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001234 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1235 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001236
Owen Andersoneed707b2009-07-24 23:12:02 +00001237 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001238 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001239
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001240 if (FormatStr[1] == 's') {
Micah Villmow3574eca2012-10-08 16:38:25 +00001241 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001242 if (!TD) return 0;
1243
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001244 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001245 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001246
Nuno Lopes51004df2012-07-25 16:46:31 +00001247 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
1248 if (!Len)
1249 return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001250 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001251 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001252 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001253 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001254
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001255 // The sprintf result is the unincremented number of bytes in the string.
1256 return B.CreateIntCast(Len, CI->getType(), false);
1257 }
1258 return 0;
1259 }
Richard Osborne419454a2011-03-03 14:09:28 +00001260
1261 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1262 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001263 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001264 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1265 !FT->getParamType(1)->isPointerTy() ||
1266 !FT->getReturnType()->isIntegerTy())
1267 return 0;
1268
1269 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1270 return V;
1271 }
1272
Richard Osborneea2578c2011-03-03 14:21:22 +00001273 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001274 // point arguments.
1275 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1276 Module *M = B.GetInsertBlock()->getParent()->getParent();
1277 Constant *SIPrintFFn =
1278 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1279 CallInst *New = cast<CallInst>(CI->clone());
1280 New->setCalledFunction(SIPrintFFn);
1281 B.Insert(New);
1282 return New;
1283 }
1284 return 0;
1285 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286};
1287
1288//===---------------------------------------===//
1289// 'fwrite' Optimizations
1290
Chris Lattner3e8b6632009-09-02 06:11:42 +00001291struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001292 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001293 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001294 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001295 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1296 !FT->getParamType(1)->isIntegerTy() ||
1297 !FT->getParamType(2)->isIntegerTy() ||
1298 !FT->getParamType(3)->isPointerTy() ||
1299 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001300 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001301
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001302 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001303 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1304 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001305 if (!SizeC || !CountC) return 0;
1306 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001307
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001308 // If this is writing zero records, remove the call (it's a noop).
1309 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001310 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001311
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001312 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001313 // This optimisation is only valid, if the return value is unused.
1314 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001315 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
Nuno Lopes51004df2012-07-25 16:46:31 +00001316 Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
1317 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001318 }
1319
1320 return 0;
1321 }
1322};
1323
1324//===---------------------------------------===//
1325// 'fputs' Optimizations
1326
Chris Lattner3e8b6632009-09-02 06:11:42 +00001327struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001328 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001329 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001330 if (!TD) return 0;
1331
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001332 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001333 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001334 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1335 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001336 !CI->use_empty())
1337 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001338
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001339 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001340 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001341 if (!Len) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001342 // Known to have no uses (see above).
1343 return EmitFWrite(CI->getArgOperand(0),
1344 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1345 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001346 }
1347};
1348
1349//===---------------------------------------===//
1350// 'fprintf' Optimizations
1351
Chris Lattner3e8b6632009-09-02 06:11:42 +00001352struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001353 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1354 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001355 // All the optimizations depend on the format string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001356 StringRef FormatStr;
1357 if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001358 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359
1360 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001361 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1363 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001364 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001365
Micah Villmow3574eca2012-10-08 16:38:25 +00001366 // These optimizations require DataLayout.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001367 if (!TD) return 0;
1368
Nuno Lopes51004df2012-07-25 16:46:31 +00001369 Value *NewCI = EmitFWrite(CI->getArgOperand(1),
1370 ConstantInt::get(TD->getIntPtrType(*Context),
1371 FormatStr.size()),
1372 CI->getArgOperand(0), B, TD, TLI);
1373 return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001374 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001375
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001376 // The remaining optimizations require the format string to be "%s" or "%c"
1377 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001378 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1379 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001380 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001381
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001382 // Decode the second character of the format string.
1383 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001384 // fprintf(F, "%c", chr) --> fputc(chr, F)
1385 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001386 Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
1387 TD, TLI);
1388 return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001389 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001390
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001391 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001392 // fprintf(F, "%s", str) --> fputs(str, F)
1393 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001394 return 0;
Nuno Lopes51004df2012-07-25 16:46:31 +00001395 return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001396 }
1397 return 0;
1398 }
Richard Osborne022708f2011-03-03 14:20:22 +00001399
1400 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1401 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001402 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001403 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1404 !FT->getParamType(1)->isPointerTy() ||
1405 !FT->getReturnType()->isIntegerTy())
1406 return 0;
1407
1408 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1409 return V;
1410 }
1411
1412 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1413 // floating point arguments.
1414 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1415 Module *M = B.GetInsertBlock()->getParent()->getParent();
1416 Constant *FIPrintFFn =
1417 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1418 CallInst *New = cast<CallInst>(CI->clone());
1419 New->setCalledFunction(FIPrintFFn);
1420 B.Insert(New);
1421 return New;
1422 }
1423 return 0;
1424 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001425};
1426
Anders Carlsson303023d2010-11-30 06:19:18 +00001427//===---------------------------------------===//
1428// 'puts' Optimizations
1429
1430struct PutsOpt : public LibCallOptimization {
1431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1432 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001433 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001434 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1435 !(FT->getReturnType()->isIntegerTy() ||
1436 FT->getReturnType()->isVoidTy()))
1437 return 0;
1438
1439 // Check for a constant string.
Chris Lattner18c7f802012-02-05 02:29:43 +00001440 StringRef Str;
1441 if (!getConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001442 return 0;
1443
Daniel Dunbard02be242011-02-12 18:19:57 +00001444 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001445 // puts("") -> putchar('\n')
Nuno Lopes51004df2012-07-25 16:46:31 +00001446 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
Nuno Lopescd31fc72012-07-26 17:10:46 +00001447 if (CI->use_empty() || !Res) return Res;
Anders Carlsson303023d2010-11-30 06:19:18 +00001448 return B.CreateIntCast(Res, CI->getType(), true);
1449 }
1450
1451 return 0;
1452 }
1453};
1454
Bill Wendlingac178222008-05-05 21:37:59 +00001455} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001456
1457//===----------------------------------------------------------------------===//
1458// SimplifyLibCalls Pass Implementation
1459//===----------------------------------------------------------------------===//
1460
1461namespace {
1462 /// This pass optimizes well known library functions from libc and libm.
1463 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001464 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001465 TargetLibraryInfo *TLI;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001466
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001467 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001468 // String and Memory LibCall Optimizations
Meador Inge73d8a582012-10-13 16:45:32 +00001469 StrChrOpt StrChr; StrRChrOpt StrRChr;
David Majnemerac782662012-05-15 11:46:21 +00001470 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1471 StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
1472 StpCpyOpt StpCpy; StpCpyOpt StpCpyChk;
1473 StrNCpyOpt StrNCpy;
1474 StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001475 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001476 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001477 // Math Library Optimizations
Chad Rosierec7e92a2012-08-22 17:22:33 +00001478 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
1479 UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001480 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001481 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1482 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001483 // Formatting and IO Optimizations
1484 SPrintFOpt SPrintF; PrintFOpt PrintF;
1485 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001486 PutsOpt Puts;
Nadav Rotema94d6e82012-07-24 10:51:42 +00001487
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001488 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001489 public:
1490 static char ID; // Pass identification
David Majnemerac782662012-05-15 11:46:21 +00001491 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true),
Chad Rosierec7e92a2012-08-22 17:22:33 +00001492 StpCpy(false), StpCpyChk(true),
1493 UnaryDoubleFP(false), UnsafeUnaryDoubleFP(true) {
Owen Anderson081c34b2010-10-19 17:21:58 +00001494 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1495 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001496 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chad Rosierd7e25252012-08-22 16:52:57 +00001497 void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
1498
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001499 void InitOptimizations();
1500 bool runOnFunction(Function &F);
1501
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001502 void setDoesNotAccessMemory(Function &F);
1503 void setOnlyReadsMemory(Function &F);
1504 void setDoesNotThrow(Function &F);
1505 void setDoesNotCapture(Function &F, unsigned n);
1506 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001507 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001508
Chris Lattnere265ad82011-02-24 07:12:12 +00001509 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001510 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001511 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001512 }
1513 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001514} // end anonymous namespace.
1515
Chris Lattnerafbf4832011-02-24 07:16:14 +00001516char SimplifyLibCalls::ID = 0;
1517
1518INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1519 "Simplify well-known library calls", false, false)
1520INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1521INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1522 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001523
1524// Public interface to the Simplify LibCalls pass.
1525FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001526 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001527}
1528
Eli Friedman9d434db2011-11-17 01:27:36 +00001529void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1530 if (TLI->has(F))
1531 Optimizations[TLI->getName(F)] = Opt;
1532}
1533
Chad Rosierd7e25252012-08-22 16:52:57 +00001534void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
1535 LibCallOptimization* Opt) {
1536 if (TLI->has(F1) && TLI->has(F2))
1537 Optimizations[TLI->getName(F1)] = Opt;
1538}
1539
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001540/// Optimizations - Populate the Optimizations map with all the optimizations
1541/// we know.
1542void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001543 // String and Memory LibCall Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001544 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001545 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001546 Optimizations["strcmp"] = &StrCmp;
1547 Optimizations["strncmp"] = &StrNCmp;
1548 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001549 Optimizations["strncpy"] = &StrNCpy;
David Majnemerac782662012-05-15 11:46:21 +00001550 Optimizations["stpcpy"] = &StpCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001551 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001552 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001553 Optimizations["strtol"] = &StrTo;
1554 Optimizations["strtod"] = &StrTo;
1555 Optimizations["strtof"] = &StrTo;
1556 Optimizations["strtoul"] = &StrTo;
1557 Optimizations["strtoll"] = &StrTo;
1558 Optimizations["strtold"] = &StrTo;
1559 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001560 Optimizations["strspn"] = &StrSpn;
1561 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001562 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001563 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001564 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001565 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001566 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001567
Evan Cheng0289b412010-03-23 15:48:04 +00001568 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001569 Optimizations["__strcpy_chk"] = &StrCpyChk;
David Majnemerac782662012-05-15 11:46:21 +00001570 Optimizations["__stpcpy_chk"] = &StpCpyChk;
Evan Cheng0289b412010-03-23 15:48:04 +00001571
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001572 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001573 Optimizations["cosf"] = &Cos;
1574 Optimizations["cos"] = &Cos;
1575 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001576 Optimizations["powf"] = &Pow;
1577 Optimizations["pow"] = &Pow;
1578 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001579 Optimizations["llvm.pow.f32"] = &Pow;
1580 Optimizations["llvm.pow.f64"] = &Pow;
1581 Optimizations["llvm.pow.f80"] = &Pow;
1582 Optimizations["llvm.pow.f128"] = &Pow;
1583 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001584 Optimizations["exp2l"] = &Exp2;
1585 Optimizations["exp2"] = &Exp2;
1586 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001587 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1588 Optimizations["llvm.exp2.f128"] = &Exp2;
1589 Optimizations["llvm.exp2.f80"] = &Exp2;
1590 Optimizations["llvm.exp2.f64"] = &Exp2;
1591 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001592
Chad Rosierd7e25252012-08-22 16:52:57 +00001593 AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
1594 AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
Benjamin Kramer7f07d2f2012-08-22 19:39:15 +00001595 AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
1596 AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
1597 AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
1598 AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
1599 AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
Chad Rosierec7e92a2012-08-22 17:22:33 +00001600
1601 if(UnsafeFPShrink) {
1602 AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
1603 AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
1604 AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
1605 AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
1606 AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
1607 AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
1608 AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
1609 AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
1610 AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
1611 AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
1612 AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
1613 AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
1614 AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
1615 AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
1616 AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
1617 AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
1618 AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
1619 AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
1620 AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
1621 AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
1622 AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
1623 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001624
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625 // Integer Optimizations
1626 Optimizations["ffs"] = &FFS;
1627 Optimizations["ffsl"] = &FFS;
1628 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001629 Optimizations["abs"] = &Abs;
1630 Optimizations["labs"] = &Abs;
1631 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001632 Optimizations["isdigit"] = &IsDigit;
1633 Optimizations["isascii"] = &IsAscii;
1634 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001635
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001636 // Formatting and IO Optimizations
1637 Optimizations["sprintf"] = &SPrintF;
1638 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001639 AddOpt(LibFunc::fwrite, &FWrite);
1640 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001641 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001642 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001643}
1644
1645
1646/// runOnFunction - Top level algorithm.
1647///
1648bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001649 TLI = &getAnalysis<TargetLibraryInfo>();
1650
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001651 if (Optimizations.empty())
1652 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001653
Micah Villmow3574eca2012-10-08 16:38:25 +00001654 const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001655
Owen Andersone922c022009-07-22 00:24:57 +00001656 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001657
1658 bool Changed = false;
1659 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1660 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1661 // Ignore non-calls.
1662 CallInst *CI = dyn_cast<CallInst>(I++);
1663 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001664
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001665 // Ignore indirect calls and calls to non-external functions.
1666 Function *Callee = CI->getCalledFunction();
1667 if (Callee == 0 || !Callee->isDeclaration() ||
1668 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1669 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001670
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001671 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001672 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1673 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001674
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001675 // Set the builder to the instruction after the call.
1676 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001677
Devang Patela2ab3992011-03-09 21:27:52 +00001678 // Use debug location of CI for all new instructions.
1679 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1680
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001681 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001682 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001683 if (Result == 0) continue;
1684
David Greene6a6b90e2010-01-05 01:27:21 +00001685 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1686 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001687
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001688 // Something changed!
1689 Changed = true;
1690 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001691
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001692 // Inspect the instruction after the call (which was potentially just
1693 // added) next.
1694 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001695
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001696 if (CI != Result && !CI->use_empty()) {
1697 CI->replaceAllUsesWith(Result);
1698 if (!Result->hasName())
1699 Result->takeName(CI);
1700 }
1701 CI->eraseFromParent();
1702 }
1703 }
1704 return Changed;
1705}
1706
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001707// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001708
1709void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1710 if (!F.doesNotAccessMemory()) {
1711 F.setDoesNotAccessMemory();
1712 ++NumAnnotated;
1713 Modified = true;
1714 }
1715}
1716void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1717 if (!F.onlyReadsMemory()) {
1718 F.setOnlyReadsMemory();
1719 ++NumAnnotated;
1720 Modified = true;
1721 }
1722}
1723void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1724 if (!F.doesNotThrow()) {
1725 F.setDoesNotThrow();
1726 ++NumAnnotated;
1727 Modified = true;
1728 }
1729}
1730void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1731 if (!F.doesNotCapture(n)) {
1732 F.setDoesNotCapture(n);
1733 ++NumAnnotated;
1734 Modified = true;
1735 }
1736}
1737void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1738 if (!F.doesNotAlias(n)) {
1739 F.setDoesNotAlias(n);
1740 ++NumAnnotated;
1741 Modified = true;
1742 }
1743}
1744
Chris Lattnere265ad82011-02-24 07:12:12 +00001745
1746void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001747 FunctionType *FTy = F.getFunctionType();
Nadav Rotema94d6e82012-07-24 10:51:42 +00001748
Chris Lattnere265ad82011-02-24 07:12:12 +00001749 StringRef Name = F.getName();
1750 switch (Name[0]) {
1751 case 's':
1752 if (Name == "strlen") {
1753 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1754 return;
1755 setOnlyReadsMemory(F);
1756 setDoesNotThrow(F);
1757 setDoesNotCapture(F, 1);
1758 } else if (Name == "strchr" ||
1759 Name == "strrchr") {
1760 if (FTy->getNumParams() != 2 ||
1761 !FTy->getParamType(0)->isPointerTy() ||
1762 !FTy->getParamType(1)->isIntegerTy())
1763 return;
1764 setOnlyReadsMemory(F);
1765 setDoesNotThrow(F);
1766 } else if (Name == "strcpy" ||
1767 Name == "stpcpy" ||
1768 Name == "strcat" ||
1769 Name == "strtol" ||
1770 Name == "strtod" ||
1771 Name == "strtof" ||
1772 Name == "strtoul" ||
1773 Name == "strtoll" ||
1774 Name == "strtold" ||
1775 Name == "strncat" ||
1776 Name == "strncpy" ||
David Majnemerac782662012-05-15 11:46:21 +00001777 Name == "stpncpy" ||
Chris Lattnere265ad82011-02-24 07:12:12 +00001778 Name == "strtoull") {
1779 if (FTy->getNumParams() < 2 ||
1780 !FTy->getParamType(1)->isPointerTy())
1781 return;
1782 setDoesNotThrow(F);
1783 setDoesNotCapture(F, 2);
1784 } else if (Name == "strxfrm") {
1785 if (FTy->getNumParams() != 3 ||
1786 !FTy->getParamType(0)->isPointerTy() ||
1787 !FTy->getParamType(1)->isPointerTy())
1788 return;
1789 setDoesNotThrow(F);
1790 setDoesNotCapture(F, 1);
1791 setDoesNotCapture(F, 2);
1792 } else if (Name == "strcmp" ||
1793 Name == "strspn" ||
1794 Name == "strncmp" ||
1795 Name == "strcspn" ||
1796 Name == "strcoll" ||
1797 Name == "strcasecmp" ||
1798 Name == "strncasecmp") {
1799 if (FTy->getNumParams() < 2 ||
1800 !FTy->getParamType(0)->isPointerTy() ||
1801 !FTy->getParamType(1)->isPointerTy())
1802 return;
1803 setOnlyReadsMemory(F);
1804 setDoesNotThrow(F);
1805 setDoesNotCapture(F, 1);
1806 setDoesNotCapture(F, 2);
1807 } else if (Name == "strstr" ||
1808 Name == "strpbrk") {
1809 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1810 return;
1811 setOnlyReadsMemory(F);
1812 setDoesNotThrow(F);
1813 setDoesNotCapture(F, 2);
1814 } else if (Name == "strtok" ||
1815 Name == "strtok_r") {
1816 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1817 return;
1818 setDoesNotThrow(F);
1819 setDoesNotCapture(F, 2);
1820 } else if (Name == "scanf" ||
1821 Name == "setbuf" ||
1822 Name == "setvbuf") {
1823 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1824 return;
1825 setDoesNotThrow(F);
1826 setDoesNotCapture(F, 1);
1827 } else if (Name == "strdup" ||
1828 Name == "strndup") {
1829 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1830 !FTy->getParamType(0)->isPointerTy())
1831 return;
1832 setDoesNotThrow(F);
1833 setDoesNotAlias(F, 0);
1834 setDoesNotCapture(F, 1);
1835 } else if (Name == "stat" ||
1836 Name == "sscanf" ||
1837 Name == "sprintf" ||
1838 Name == "statvfs") {
1839 if (FTy->getNumParams() < 2 ||
1840 !FTy->getParamType(0)->isPointerTy() ||
1841 !FTy->getParamType(1)->isPointerTy())
1842 return;
1843 setDoesNotThrow(F);
1844 setDoesNotCapture(F, 1);
1845 setDoesNotCapture(F, 2);
1846 } else if (Name == "snprintf") {
1847 if (FTy->getNumParams() != 3 ||
1848 !FTy->getParamType(0)->isPointerTy() ||
1849 !FTy->getParamType(2)->isPointerTy())
1850 return;
1851 setDoesNotThrow(F);
1852 setDoesNotCapture(F, 1);
1853 setDoesNotCapture(F, 3);
1854 } else if (Name == "setitimer") {
1855 if (FTy->getNumParams() != 3 ||
1856 !FTy->getParamType(1)->isPointerTy() ||
1857 !FTy->getParamType(2)->isPointerTy())
1858 return;
1859 setDoesNotThrow(F);
1860 setDoesNotCapture(F, 2);
1861 setDoesNotCapture(F, 3);
1862 } else if (Name == "system") {
1863 if (FTy->getNumParams() != 1 ||
1864 !FTy->getParamType(0)->isPointerTy())
1865 return;
1866 // May throw; "system" is a valid pthread cancellation point.
1867 setDoesNotCapture(F, 1);
1868 }
1869 break;
1870 case 'm':
1871 if (Name == "malloc") {
1872 if (FTy->getNumParams() != 1 ||
1873 !FTy->getReturnType()->isPointerTy())
1874 return;
1875 setDoesNotThrow(F);
1876 setDoesNotAlias(F, 0);
1877 } else if (Name == "memcmp") {
1878 if (FTy->getNumParams() != 3 ||
1879 !FTy->getParamType(0)->isPointerTy() ||
1880 !FTy->getParamType(1)->isPointerTy())
1881 return;
1882 setOnlyReadsMemory(F);
1883 setDoesNotThrow(F);
1884 setDoesNotCapture(F, 1);
1885 setDoesNotCapture(F, 2);
1886 } else if (Name == "memchr" ||
1887 Name == "memrchr") {
1888 if (FTy->getNumParams() != 3)
1889 return;
1890 setOnlyReadsMemory(F);
1891 setDoesNotThrow(F);
1892 } else if (Name == "modf" ||
1893 Name == "modff" ||
1894 Name == "modfl" ||
1895 Name == "memcpy" ||
1896 Name == "memccpy" ||
1897 Name == "memmove") {
1898 if (FTy->getNumParams() < 2 ||
1899 !FTy->getParamType(1)->isPointerTy())
1900 return;
1901 setDoesNotThrow(F);
1902 setDoesNotCapture(F, 2);
1903 } else if (Name == "memalign") {
1904 if (!FTy->getReturnType()->isPointerTy())
1905 return;
1906 setDoesNotAlias(F, 0);
1907 } else if (Name == "mkdir" ||
1908 Name == "mktime") {
1909 if (FTy->getNumParams() == 0 ||
1910 !FTy->getParamType(0)->isPointerTy())
1911 return;
1912 setDoesNotThrow(F);
1913 setDoesNotCapture(F, 1);
1914 }
1915 break;
1916 case 'r':
1917 if (Name == "realloc") {
1918 if (FTy->getNumParams() != 2 ||
1919 !FTy->getParamType(0)->isPointerTy() ||
1920 !FTy->getReturnType()->isPointerTy())
1921 return;
1922 setDoesNotThrow(F);
Nuno Lopesfd99cab2012-06-25 23:26:10 +00001923 setDoesNotAlias(F, 0);
Chris Lattnere265ad82011-02-24 07:12:12 +00001924 setDoesNotCapture(F, 1);
1925 } else if (Name == "read") {
1926 if (FTy->getNumParams() != 3 ||
1927 !FTy->getParamType(1)->isPointerTy())
1928 return;
1929 // May throw; "read" is a valid pthread cancellation point.
1930 setDoesNotCapture(F, 2);
1931 } else if (Name == "rmdir" ||
1932 Name == "rewind" ||
1933 Name == "remove" ||
1934 Name == "realpath") {
1935 if (FTy->getNumParams() < 1 ||
1936 !FTy->getParamType(0)->isPointerTy())
1937 return;
1938 setDoesNotThrow(F);
1939 setDoesNotCapture(F, 1);
1940 } else if (Name == "rename" ||
1941 Name == "readlink") {
1942 if (FTy->getNumParams() < 2 ||
1943 !FTy->getParamType(0)->isPointerTy() ||
1944 !FTy->getParamType(1)->isPointerTy())
1945 return;
1946 setDoesNotThrow(F);
1947 setDoesNotCapture(F, 1);
1948 setDoesNotCapture(F, 2);
1949 }
1950 break;
1951 case 'w':
1952 if (Name == "write") {
1953 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1954 return;
1955 // May throw; "write" is a valid pthread cancellation point.
1956 setDoesNotCapture(F, 2);
1957 }
1958 break;
1959 case 'b':
1960 if (Name == "bcopy") {
1961 if (FTy->getNumParams() != 3 ||
1962 !FTy->getParamType(0)->isPointerTy() ||
1963 !FTy->getParamType(1)->isPointerTy())
1964 return;
1965 setDoesNotThrow(F);
1966 setDoesNotCapture(F, 1);
1967 setDoesNotCapture(F, 2);
1968 } else if (Name == "bcmp") {
1969 if (FTy->getNumParams() != 3 ||
1970 !FTy->getParamType(0)->isPointerTy() ||
1971 !FTy->getParamType(1)->isPointerTy())
1972 return;
1973 setDoesNotThrow(F);
1974 setOnlyReadsMemory(F);
1975 setDoesNotCapture(F, 1);
1976 setDoesNotCapture(F, 2);
1977 } else if (Name == "bzero") {
1978 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1979 return;
1980 setDoesNotThrow(F);
1981 setDoesNotCapture(F, 1);
1982 }
1983 break;
1984 case 'c':
1985 if (Name == "calloc") {
1986 if (FTy->getNumParams() != 2 ||
1987 !FTy->getReturnType()->isPointerTy())
1988 return;
1989 setDoesNotThrow(F);
1990 setDoesNotAlias(F, 0);
1991 } else if (Name == "chmod" ||
1992 Name == "chown" ||
1993 Name == "ctermid" ||
1994 Name == "clearerr" ||
1995 Name == "closedir") {
1996 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1997 return;
1998 setDoesNotThrow(F);
1999 setDoesNotCapture(F, 1);
2000 }
2001 break;
2002 case 'a':
2003 if (Name == "atoi" ||
2004 Name == "atol" ||
2005 Name == "atof" ||
2006 Name == "atoll") {
2007 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2008 return;
2009 setDoesNotThrow(F);
2010 setOnlyReadsMemory(F);
2011 setDoesNotCapture(F, 1);
2012 } else if (Name == "access") {
2013 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2014 return;
2015 setDoesNotThrow(F);
2016 setDoesNotCapture(F, 1);
2017 }
2018 break;
2019 case 'f':
2020 if (Name == "fopen") {
2021 if (FTy->getNumParams() != 2 ||
2022 !FTy->getReturnType()->isPointerTy() ||
2023 !FTy->getParamType(0)->isPointerTy() ||
2024 !FTy->getParamType(1)->isPointerTy())
2025 return;
2026 setDoesNotThrow(F);
2027 setDoesNotAlias(F, 0);
2028 setDoesNotCapture(F, 1);
2029 setDoesNotCapture(F, 2);
2030 } else if (Name == "fdopen") {
2031 if (FTy->getNumParams() != 2 ||
2032 !FTy->getReturnType()->isPointerTy() ||
2033 !FTy->getParamType(1)->isPointerTy())
2034 return;
2035 setDoesNotThrow(F);
2036 setDoesNotAlias(F, 0);
2037 setDoesNotCapture(F, 2);
2038 } else if (Name == "feof" ||
2039 Name == "free" ||
2040 Name == "fseek" ||
2041 Name == "ftell" ||
2042 Name == "fgetc" ||
2043 Name == "fseeko" ||
2044 Name == "ftello" ||
2045 Name == "fileno" ||
2046 Name == "fflush" ||
2047 Name == "fclose" ||
2048 Name == "fsetpos" ||
2049 Name == "flockfile" ||
2050 Name == "funlockfile" ||
2051 Name == "ftrylockfile") {
2052 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2053 return;
2054 setDoesNotThrow(F);
2055 setDoesNotCapture(F, 1);
2056 } else if (Name == "ferror") {
2057 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2058 return;
2059 setDoesNotThrow(F);
2060 setDoesNotCapture(F, 1);
2061 setOnlyReadsMemory(F);
2062 } else if (Name == "fputc" ||
2063 Name == "fstat" ||
2064 Name == "frexp" ||
2065 Name == "frexpf" ||
2066 Name == "frexpl" ||
2067 Name == "fstatvfs") {
2068 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2069 return;
2070 setDoesNotThrow(F);
2071 setDoesNotCapture(F, 2);
2072 } else if (Name == "fgets") {
2073 if (FTy->getNumParams() != 3 ||
2074 !FTy->getParamType(0)->isPointerTy() ||
2075 !FTy->getParamType(2)->isPointerTy())
2076 return;
2077 setDoesNotThrow(F);
2078 setDoesNotCapture(F, 3);
2079 } else if (Name == "fread" ||
2080 Name == "fwrite") {
2081 if (FTy->getNumParams() != 4 ||
2082 !FTy->getParamType(0)->isPointerTy() ||
2083 !FTy->getParamType(3)->isPointerTy())
2084 return;
2085 setDoesNotThrow(F);
2086 setDoesNotCapture(F, 1);
2087 setDoesNotCapture(F, 4);
2088 } else if (Name == "fputs" ||
2089 Name == "fscanf" ||
2090 Name == "fprintf" ||
2091 Name == "fgetpos") {
2092 if (FTy->getNumParams() < 2 ||
2093 !FTy->getParamType(0)->isPointerTy() ||
2094 !FTy->getParamType(1)->isPointerTy())
2095 return;
2096 setDoesNotThrow(F);
2097 setDoesNotCapture(F, 1);
2098 setDoesNotCapture(F, 2);
2099 }
2100 break;
2101 case 'g':
2102 if (Name == "getc" ||
2103 Name == "getlogin_r" ||
2104 Name == "getc_unlocked") {
2105 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2106 return;
2107 setDoesNotThrow(F);
2108 setDoesNotCapture(F, 1);
2109 } else if (Name == "getenv") {
2110 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2111 return;
2112 setDoesNotThrow(F);
2113 setOnlyReadsMemory(F);
2114 setDoesNotCapture(F, 1);
2115 } else if (Name == "gets" ||
2116 Name == "getchar") {
2117 setDoesNotThrow(F);
2118 } else if (Name == "getitimer") {
2119 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2120 return;
2121 setDoesNotThrow(F);
2122 setDoesNotCapture(F, 2);
2123 } else if (Name == "getpwnam") {
2124 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2125 return;
2126 setDoesNotThrow(F);
2127 setDoesNotCapture(F, 1);
2128 }
2129 break;
2130 case 'u':
2131 if (Name == "ungetc") {
2132 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2133 return;
2134 setDoesNotThrow(F);
2135 setDoesNotCapture(F, 2);
2136 } else if (Name == "uname" ||
2137 Name == "unlink" ||
2138 Name == "unsetenv") {
2139 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2140 return;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 1);
2143 } else if (Name == "utime" ||
2144 Name == "utimes") {
2145 if (FTy->getNumParams() != 2 ||
2146 !FTy->getParamType(0)->isPointerTy() ||
2147 !FTy->getParamType(1)->isPointerTy())
2148 return;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
2151 setDoesNotCapture(F, 2);
2152 }
2153 break;
2154 case 'p':
2155 if (Name == "putc") {
2156 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2157 return;
2158 setDoesNotThrow(F);
2159 setDoesNotCapture(F, 2);
2160 } else if (Name == "puts" ||
2161 Name == "printf" ||
2162 Name == "perror") {
2163 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2164 return;
2165 setDoesNotThrow(F);
2166 setDoesNotCapture(F, 1);
2167 } else if (Name == "pread" ||
2168 Name == "pwrite") {
2169 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2170 return;
2171 // May throw; these are valid pthread cancellation points.
2172 setDoesNotCapture(F, 2);
2173 } else if (Name == "putchar") {
2174 setDoesNotThrow(F);
2175 } else if (Name == "popen") {
2176 if (FTy->getNumParams() != 2 ||
2177 !FTy->getReturnType()->isPointerTy() ||
2178 !FTy->getParamType(0)->isPointerTy() ||
2179 !FTy->getParamType(1)->isPointerTy())
2180 return;
2181 setDoesNotThrow(F);
2182 setDoesNotAlias(F, 0);
2183 setDoesNotCapture(F, 1);
2184 setDoesNotCapture(F, 2);
2185 } else if (Name == "pclose") {
2186 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2187 return;
2188 setDoesNotThrow(F);
2189 setDoesNotCapture(F, 1);
2190 }
2191 break;
2192 case 'v':
2193 if (Name == "vscanf") {
2194 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2195 return;
2196 setDoesNotThrow(F);
2197 setDoesNotCapture(F, 1);
2198 } else if (Name == "vsscanf" ||
2199 Name == "vfscanf") {
2200 if (FTy->getNumParams() != 3 ||
2201 !FTy->getParamType(1)->isPointerTy() ||
2202 !FTy->getParamType(2)->isPointerTy())
2203 return;
2204 setDoesNotThrow(F);
2205 setDoesNotCapture(F, 1);
2206 setDoesNotCapture(F, 2);
2207 } else if (Name == "valloc") {
2208 if (!FTy->getReturnType()->isPointerTy())
2209 return;
2210 setDoesNotThrow(F);
2211 setDoesNotAlias(F, 0);
2212 } else if (Name == "vprintf") {
2213 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2214 return;
2215 setDoesNotThrow(F);
2216 setDoesNotCapture(F, 1);
2217 } else if (Name == "vfprintf" ||
2218 Name == "vsprintf") {
2219 if (FTy->getNumParams() != 3 ||
2220 !FTy->getParamType(0)->isPointerTy() ||
2221 !FTy->getParamType(1)->isPointerTy())
2222 return;
2223 setDoesNotThrow(F);
2224 setDoesNotCapture(F, 1);
2225 setDoesNotCapture(F, 2);
2226 } else if (Name == "vsnprintf") {
2227 if (FTy->getNumParams() != 4 ||
2228 !FTy->getParamType(0)->isPointerTy() ||
2229 !FTy->getParamType(2)->isPointerTy())
2230 return;
2231 setDoesNotThrow(F);
2232 setDoesNotCapture(F, 1);
2233 setDoesNotCapture(F, 3);
2234 }
2235 break;
2236 case 'o':
2237 if (Name == "open") {
2238 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2239 return;
2240 // May throw; "open" is a valid pthread cancellation point.
2241 setDoesNotCapture(F, 1);
2242 } else if (Name == "opendir") {
2243 if (FTy->getNumParams() != 1 ||
2244 !FTy->getReturnType()->isPointerTy() ||
2245 !FTy->getParamType(0)->isPointerTy())
2246 return;
2247 setDoesNotThrow(F);
2248 setDoesNotAlias(F, 0);
2249 setDoesNotCapture(F, 1);
2250 }
2251 break;
2252 case 't':
2253 if (Name == "tmpfile") {
2254 if (!FTy->getReturnType()->isPointerTy())
2255 return;
2256 setDoesNotThrow(F);
2257 setDoesNotAlias(F, 0);
2258 } else if (Name == "times") {
2259 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2260 return;
2261 setDoesNotThrow(F);
2262 setDoesNotCapture(F, 1);
2263 }
2264 break;
2265 case 'h':
2266 if (Name == "htonl" ||
2267 Name == "htons") {
2268 setDoesNotThrow(F);
2269 setDoesNotAccessMemory(F);
2270 }
2271 break;
2272 case 'n':
2273 if (Name == "ntohl" ||
2274 Name == "ntohs") {
2275 setDoesNotThrow(F);
2276 setDoesNotAccessMemory(F);
2277 }
2278 break;
2279 case 'l':
2280 if (Name == "lstat") {
2281 if (FTy->getNumParams() != 2 ||
2282 !FTy->getParamType(0)->isPointerTy() ||
2283 !FTy->getParamType(1)->isPointerTy())
2284 return;
2285 setDoesNotThrow(F);
2286 setDoesNotCapture(F, 1);
2287 setDoesNotCapture(F, 2);
2288 } else if (Name == "lchown") {
2289 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2290 return;
2291 setDoesNotThrow(F);
2292 setDoesNotCapture(F, 1);
2293 }
2294 break;
2295 case 'q':
2296 if (Name == "qsort") {
2297 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2298 return;
2299 // May throw; places call through function pointer.
2300 setDoesNotCapture(F, 4);
2301 }
2302 break;
2303 case '_':
2304 if (Name == "__strdup" ||
2305 Name == "__strndup") {
2306 if (FTy->getNumParams() < 1 ||
2307 !FTy->getReturnType()->isPointerTy() ||
2308 !FTy->getParamType(0)->isPointerTy())
2309 return;
2310 setDoesNotThrow(F);
2311 setDoesNotAlias(F, 0);
2312 setDoesNotCapture(F, 1);
2313 } else if (Name == "__strtok_r") {
2314 if (FTy->getNumParams() != 3 ||
2315 !FTy->getParamType(1)->isPointerTy())
2316 return;
2317 setDoesNotThrow(F);
2318 setDoesNotCapture(F, 2);
2319 } else if (Name == "_IO_getc") {
2320 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2321 return;
2322 setDoesNotThrow(F);
2323 setDoesNotCapture(F, 1);
2324 } else if (Name == "_IO_putc") {
2325 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2326 return;
2327 setDoesNotThrow(F);
2328 setDoesNotCapture(F, 2);
2329 }
2330 break;
2331 case 1:
2332 if (Name == "\1__isoc99_scanf") {
2333 if (FTy->getNumParams() < 1 ||
2334 !FTy->getParamType(0)->isPointerTy())
2335 return;
2336 setDoesNotThrow(F);
2337 setDoesNotCapture(F, 1);
2338 } else if (Name == "\1stat64" ||
2339 Name == "\1lstat64" ||
2340 Name == "\1statvfs64" ||
2341 Name == "\1__isoc99_sscanf") {
2342 if (FTy->getNumParams() < 1 ||
2343 !FTy->getParamType(0)->isPointerTy() ||
2344 !FTy->getParamType(1)->isPointerTy())
2345 return;
2346 setDoesNotThrow(F);
2347 setDoesNotCapture(F, 1);
2348 setDoesNotCapture(F, 2);
2349 } else if (Name == "\1fopen64") {
2350 if (FTy->getNumParams() != 2 ||
2351 !FTy->getReturnType()->isPointerTy() ||
2352 !FTy->getParamType(0)->isPointerTy() ||
2353 !FTy->getParamType(1)->isPointerTy())
2354 return;
2355 setDoesNotThrow(F);
2356 setDoesNotAlias(F, 0);
2357 setDoesNotCapture(F, 1);
2358 setDoesNotCapture(F, 2);
2359 } else if (Name == "\1fseeko64" ||
2360 Name == "\1ftello64") {
2361 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2362 return;
2363 setDoesNotThrow(F);
2364 setDoesNotCapture(F, 1);
2365 } else if (Name == "\1tmpfile64") {
2366 if (!FTy->getReturnType()->isPointerTy())
2367 return;
2368 setDoesNotThrow(F);
2369 setDoesNotAlias(F, 0);
2370 } else if (Name == "\1fstat64" ||
2371 Name == "\1fstatvfs64") {
2372 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2373 return;
2374 setDoesNotThrow(F);
2375 setDoesNotCapture(F, 2);
2376 } else if (Name == "\1open64") {
2377 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2378 return;
2379 // May throw; "open" is a valid pthread cancellation point.
2380 setDoesNotCapture(F, 1);
2381 }
2382 break;
2383 }
2384}
2385
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002386/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002387///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002388bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002389 Modified = false;
2390 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2391 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002392 if (F.isDeclaration() && F.hasName())
2393 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002394 }
2395 return Modified;
2396}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002397
2398// TODO:
2399// Additional cases that we need to add to this file:
2400//
2401// cbrt:
2402// * cbrt(expN(X)) -> expN(x/3)
2403// * cbrt(sqrt(x)) -> pow(x,1/6)
2404// * cbrt(sqrt(x)) -> pow(x,1/9)
2405//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002406// exp, expf, expl:
2407// * exp(log(x)) -> x
2408//
2409// log, logf, logl:
2410// * log(exp(x)) -> x
2411// * log(x**y) -> y*log(x)
2412// * log(exp(y)) -> y*log(e)
2413// * log(exp2(y)) -> y*log(2)
2414// * log(exp10(y)) -> y*log(10)
2415// * log(sqrt(x)) -> 0.5*log(x)
2416// * log(pow(x,y)) -> y*log(x)
2417//
2418// lround, lroundf, lroundl:
2419// * lround(cnst) -> cnst'
2420//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002421// pow, powf, powl:
2422// * pow(exp(x),y) -> exp(x*y)
2423// * pow(sqrt(x),y) -> pow(x,y*0.5)
2424// * pow(pow(x,y),z)-> pow(x,y*z)
2425//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002426// round, roundf, roundl:
2427// * round(cnst) -> cnst'
2428//
2429// signbit:
2430// * signbit(cnst) -> cnst'
2431// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2432//
2433// sqrt, sqrtf, sqrtl:
2434// * sqrt(expN(x)) -> expN(x*0.5)
2435// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2436// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2437//
Chris Lattner18c7f802012-02-05 02:29:43 +00002438// strchr:
2439// * strchr(p, 0) -> strlen(p)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002440// tan, tanf, tanl:
2441// * tan(atan(x)) -> x
2442//
2443// trunc, truncf, truncl:
2444// * trunc(cnst) -> cnst'
2445//
2446//