blob: dcfcf1a876491011f4acb20d9f1aaacb50fc788f [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"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000021#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000022#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000026#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000028#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000029#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000032#include "llvm/ADT/STLExtras.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000033#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000035#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000036using namespace llvm;
37
38STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000039STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000040
41//===----------------------------------------------------------------------===//
42// Optimizer Base Class
43//===----------------------------------------------------------------------===//
44
45/// This class is the abstract base class for the set of optimizations that
46/// corresponds to one library call.
47namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000049protected:
50 Function *Caller;
51 const TargetData *TD;
Richard Osborne36498242011-03-03 13:17:51 +000052 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000053 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054public:
Evan Chengeb8c6452010-03-24 20:19:04 +000055 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000056 virtual ~LibCallOptimization() {}
57
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
62 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000063 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000064 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000065
Richard Osborne36498242011-03-03 13:17:51 +000066 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000068 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000069 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000070 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000071 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000072 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000073
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
76 return NULL;
77
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000078 return CallOptimizer(CI->getCalledFunction(), CI, B);
79 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000080};
81} // End anonymous namespace.
82
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083
84//===----------------------------------------------------------------------===//
85// Helper Functions
86//===----------------------------------------------------------------------===//
87
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000088/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +000089/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000090static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
Richard Osborne36498242011-03-03 13:17:51 +0000103
104static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
106 it != e; ++it) {
107 if ((*it)->getType()->isFloatingPointTy())
108 return true;
109 }
110 return false;
111}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112
Benjamin Kramer386e9182010-06-15 21:34:25 +0000113/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114/// comparisons with With.
115static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
117 UI != E; ++UI) {
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
120 continue;
121 // Unknown instruction.
122 return false;
123 }
124 return true;
125}
126
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000127//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128// String and Memory LibCall Optimizations
129//===----------------------------------------------------------------------===//
130
131//===---------------------------------------===//
132// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000133namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000134struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000136 // Verify the "strcat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000137 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000138 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000139 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
142 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000143
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000147
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000150 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000151 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000152
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000153 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 if (Len == 0)
155 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000156
157 // These optimizations require TargetData.
158 if (!TD) return 0;
159
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000160 EmitStrLenMemCpy(Src, Dst, Len, B);
161 return Dst;
162 }
163
164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
Eric Christopherb6174e32010-03-05 22:25:30 +0000167 Value *DstLen = EmitStrLen(Dst, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +0000168
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000173
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000178 }
179};
180
181//===---------------------------------------===//
182// 'strncat' Optimizations
183
Chris Lattner3e8b6632009-09-02 06:11:42 +0000184struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000187 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000188 if (FT->getNumParams() != 3 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000189 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000192 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000193 return 0;
194
195 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000198 uint64_t Len;
199
200 // We don't do anything if length is not constant
Gabor Greifaee5dc12010-06-24 10:42:46 +0000201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000202 Len = LengthArg->getZExtValue();
203 else
204 return 0;
205
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
210
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
215
Dan Gohmanf14d9192009-08-18 00:48:13 +0000216 // These optimizations require TargetData.
217 if (!TD) return 0;
218
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
221
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000225 return Dst;
226 }
227};
228
229//===---------------------------------------===//
230// 'strchr' Optimizations
231
Chris Lattner3e8b6632009-09-02 06:11:42 +0000232struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234 // Verify the "strchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000235 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000236 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000237 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000240 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000241
Gabor Greifaee5dc12010-06-24 10:42:46 +0000242 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000243
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000247 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000248 // These optimizations require TargetData.
249 if (!TD) return 0;
250
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000251 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000253 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000254
Gabor Greifaee5dc12010-06-24 10:42:46 +0000255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
257 B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258 }
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000259
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000262 std::string Str;
263 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000264 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000265
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000266 // strchr can find the nul character.
267 Str += '\0';
268
269 // Compute the offset.
270 size_t I = Str.find(CharC->getSExtValue());
271 if (I == std::string::npos) // Didn't find the char. strchr returns null.
Benjamin Kramere2609902010-09-29 22:29:12 +0000272 return Constant::getNullValue(CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000273
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000274 // strchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000275 return B.CreateGEP(SrcStr, B.getInt64(I), "strchr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000276 }
277};
278
279//===---------------------------------------===//
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000280// 'strrchr' Optimizations
281
282struct StrRChrOpt : public LibCallOptimization {
283 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
284 // Verify the "strrchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000285 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000286 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000287 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000290 return 0;
291
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294
295 // Cannot fold anything if we're not looking for a constant.
296 if (!CharC)
297 return 0;
298
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000299 std::string Str;
300 if (!GetConstantStringInfo(SrcStr, Str)) {
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
303 return EmitStrChr(SrcStr, '\0', B, TD);
304 return 0;
305 }
306
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000307 // strrchr can find the nul character.
308 Str += '\0';
309
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000310 // Compute the offset.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000311 size_t I = Str.rfind(CharC->getSExtValue());
312 if (I == std::string::npos) // Didn't find the char. Return null.
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000313 return Constant::getNullValue(CI->getType());
314
315 // strrchr(s+n,c) -> gep(s+n+i,c)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000316 return B.CreateGEP(SrcStr, B.getInt64(I), "strrchr");
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000317 }
318};
319
320//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000321// 'strcmp' Optimizations
322
Chris Lattner3e8b6632009-09-02 06:11:42 +0000323struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000325 // Verify the "strcmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000327 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000328 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000329 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000330 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000332
Gabor Greifaee5dc12010-06-24 10:42:46 +0000333 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000335 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000336
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000337 std::string Str1, Str2;
338 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
339 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000340
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000341 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000342 if (HasStr1 && HasStr2)
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000343 return ConstantInt::get(CI->getType(),
344 StringRef(Str1).compare(Str2));
Eli Friedman79286082011-10-05 22:27:16 +0000345
346 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
347 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
348 CI->getType()));
349
350 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
351 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000352
353 // strcmp(P, "x") -> memcmp(P, "x", 2)
354 uint64_t Len1 = GetStringLength(Str1P);
355 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000356 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000357 // These optimizations require TargetData.
358 if (!TD) return 0;
359
Nick Lewycky13a09e22008-12-21 00:19:21 +0000360 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000361 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000362 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000363 }
364
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000365 return 0;
366 }
367};
368
369//===---------------------------------------===//
370// 'strncmp' Optimizations
371
Chris Lattner3e8b6632009-09-02 06:11:42 +0000372struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000374 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000375 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000376 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000377 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000378 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000379 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000380 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000381 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000382
Gabor Greifaee5dc12010-06-24 10:42:46 +0000383 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000384 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000385 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000386
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000387 // Get the length argument if it is constant.
388 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000389 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000390 Length = LengthArg->getZExtValue();
391 else
392 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000393
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000394 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000395 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000396
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000397 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000398 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000399
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000400 std::string Str1, Str2;
401 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
402 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000403
Eli Friedman79286082011-10-05 22:27:16 +0000404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2) {
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000406 StringRef SubStr1 = StringRef(Str1).substr(0, Length);
407 StringRef SubStr2 = StringRef(Str2).substr(0, Length);
Eli Friedman79286082011-10-05 22:27:16 +0000408 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
409 }
410
411 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
412 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
413 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000414
Bill Wendling0582ae92009-03-13 04:39:26 +0000415 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000416 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000417
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418 return 0;
419 }
420};
421
422
423//===---------------------------------------===//
424// 'strcpy' Optimizations
425
Chris Lattner3e8b6632009-09-02 06:11:42 +0000426struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000427 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
428
429 StrCpyOpt(bool c) : OptChkCall(c) {}
430
Eric Christopher7a61d702008-08-08 19:39:37 +0000431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000432 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000433 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000434 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000435 if (FT->getNumParams() != NumParams ||
436 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000438 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000439 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Gabor Greifaee5dc12010-06-24 10:42:46 +0000441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000444
Dan Gohmanf14d9192009-08-18 00:48:13 +0000445 // These optimizations require TargetData.
446 if (!TD) return 0;
447
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 // See if we can get the length of the input string.
449 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000450 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000451
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000452 // We have enough information to now generate the memcpy call to do the
453 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000454 if (OptChkCall)
455 EmitMemCpyChk(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000457 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000458 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000459 B.CreateMemCpy(Dst, Src,
460 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000461 return Dst;
462 }
463};
464
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000465//===---------------------------------------===//
466// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000467
Chris Lattner3e8b6632009-09-02 06:11:42 +0000468struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000470 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000471 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
472 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000473 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000474 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000475 return 0;
476
Gabor Greifaee5dc12010-06-24 10:42:46 +0000477 Value *Dst = CI->getArgOperand(0);
478 Value *Src = CI->getArgOperand(1);
479 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000480
481 // See if we can get the length of the input string.
482 uint64_t SrcLen = GetStringLength(Src);
483 if (SrcLen == 0) return 0;
484 --SrcLen;
485
486 if (SrcLen == 0) {
487 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000488 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000489 return Dst;
490 }
491
492 uint64_t Len;
493 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
494 Len = LengthArg->getZExtValue();
495 else
496 return 0;
497
498 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
499
Dan Gohmanf14d9192009-08-18 00:48:13 +0000500 // These optimizations require TargetData.
501 if (!TD) return 0;
502
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000503 // Let strncpy handle the zero padding
504 if (Len > SrcLen+1) return 0;
505
506 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000507 B.CreateMemCpy(Dst, Src,
508 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000509
510 return Dst;
511 }
512};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000513
514//===---------------------------------------===//
515// 'strlen' Optimizations
516
Chris Lattner3e8b6632009-09-02 06:11:42 +0000517struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000518 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000519 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000520 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000521 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000522 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000523 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000524
Gabor Greifaee5dc12010-06-24 10:42:46 +0000525 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526
527 // Constant folding: strlen("xyz") -> 3
528 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000529 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000530
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000531 // strlen(x) != 0 --> *x != 0
532 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000533 if (IsOnlyUsedInZeroEqualityComparison(CI))
534 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
535 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000536 }
537};
538
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000539
540//===---------------------------------------===//
541// 'strpbrk' Optimizations
542
543struct StrPBrkOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000545 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000546 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000547 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000548 FT->getParamType(1) != FT->getParamType(0) ||
549 FT->getReturnType() != FT->getParamType(0))
550 return 0;
551
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000552 std::string S1, S2;
553 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000555
556 // strpbrk(s, "") -> NULL
557 // strpbrk("", s) -> NULL
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
560
561 // Constant folding.
562 if (HasS1 && HasS2) {
563 size_t I = S1.find_first_of(S2);
564 if (I == std::string::npos) // No match.
565 return Constant::getNullValue(CI->getType());
566
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000567 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000568 }
569
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (TD && HasS2 && S2.size() == 1)
572 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
573
574 return 0;
575 }
576};
577
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000578//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000579// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000580
Chris Lattner3e8b6632009-09-02 06:11:42 +0000581struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000583 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000584 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000585 !FT->getParamType(0)->isPointerTy() ||
586 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000587 return 0;
588
Gabor Greifaee5dc12010-06-24 10:42:46 +0000589 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000590 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000591 // With a null EndPtr, this function won't capture the main argument.
592 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000593 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000594 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000595
596 return 0;
597 }
598};
599
Chris Lattner24604112009-12-16 09:32:05 +0000600//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000601// 'strspn' Optimizations
602
603struct StrSpnOpt : public LibCallOptimization {
604 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000606 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000607 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000608 FT->getParamType(1) != FT->getParamType(0) ||
609 !FT->getReturnType()->isIntegerTy())
610 return 0;
611
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000612 std::string S1, S2;
613 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
614 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000615
616 // strspn(s, "") -> 0
617 // strspn("", s) -> 0
618 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
619 return Constant::getNullValue(CI->getType());
620
621 // Constant folding.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000622 if (HasS1 && HasS2)
623 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
Benjamin Kramer9510a252010-09-30 00:58:35 +0000624
625 return 0;
626 }
627};
628
629//===---------------------------------------===//
630// 'strcspn' Optimizations
631
632struct StrCSpnOpt : public LibCallOptimization {
633 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000634 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000635 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000636 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
639 return 0;
640
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000641 std::string S1, S2;
642 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
Benjamin Kramer9510a252010-09-30 00:58:35 +0000644
645 // strcspn("", s) -> 0
646 if (HasS1 && S1.empty())
647 return Constant::getNullValue(CI->getType());
648
649 // Constant folding.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000650 if (HasS1 && HasS2)
651 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
Benjamin Kramer9510a252010-09-30 00:58:35 +0000652
653 // strcspn(s, "") -> strlen(s)
654 if (TD && HasS2 && S2.empty())
655 return EmitStrLen(CI->getArgOperand(0), B, TD);
656
657 return 0;
658 }
659};
660
661//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000662// 'strstr' Optimizations
663
664struct StrStrOpt : public LibCallOptimization {
665 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000667 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000668 !FT->getParamType(0)->isPointerTy() ||
669 !FT->getParamType(1)->isPointerTy() ||
670 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000671 return 0;
672
673 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000674 if (CI->getArgOperand(0) == CI->getArgOperand(1))
675 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000676
Benjamin Kramer386e9182010-06-15 21:34:25 +0000677 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000678 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
679 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
680 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000681 StrLen, B, TD);
682 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
683 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000684 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000685 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
686 ConstantInt::getNullValue(StrNCmp->getType()),
687 "cmp");
688 Old->replaceAllUsesWith(Cmp);
689 Old->eraseFromParent();
690 }
691 return CI;
692 }
693
Chris Lattner24604112009-12-16 09:32:05 +0000694 // See if either input string is a constant string.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000695 std::string SearchStr, ToFindStr;
696 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
697 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000698
Chris Lattner24604112009-12-16 09:32:05 +0000699 // fold strstr(x, "") -> x.
700 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000702
Chris Lattner24604112009-12-16 09:32:05 +0000703 // If both strings are known, constant fold it.
704 if (HasStr1 && HasStr2) {
705 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000706
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000707 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
Chris Lattner24604112009-12-16 09:32:05 +0000708 return Constant::getNullValue(CI->getType());
709
710 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000711 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000712 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
713 return B.CreateBitCast(Result, CI->getType());
714 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000715
Chris Lattner24604112009-12-16 09:32:05 +0000716 // fold strstr(x, "y") -> strchr(x, 'y').
717 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000718 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
719 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000720 return 0;
721 }
722};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000723
Nick Lewycky4c498412009-02-13 15:31:46 +0000724
725//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726// 'memcmp' Optimizations
727
Chris Lattner3e8b6632009-09-02 06:11:42 +0000728struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000730 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
732 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000733 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000734 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000735
Gabor Greifaee5dc12010-06-24 10:42:46 +0000736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000737
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000738 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000739 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000740
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000741 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000743 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000744 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000745
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000746 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000747 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000748
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000749 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
750 if (Len == 1) {
751 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
752 CI->getType(), "lhsv");
753 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
754 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000755 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000756 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000757
Benjamin Kramer992a6372009-11-05 17:44:22 +0000758 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000759 std::string LHSStr, RHSStr;
760 if (GetConstantStringInfo(LHS, LHSStr) &&
761 GetConstantStringInfo(RHS, RHSStr)) {
Benjamin Kramer992a6372009-11-05 17:44:22 +0000762 // Make sure we're not reading out-of-bounds memory.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +0000763 if (Len > LHSStr.length() || Len > RHSStr.length())
Benjamin Kramer992a6372009-11-05 17:44:22 +0000764 return 0;
765 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
766 return ConstantInt::get(CI->getType(), Ret);
767 }
768
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000769 return 0;
770 }
771};
772
773//===---------------------------------------===//
774// 'memcpy' Optimizations
775
Chris Lattner3e8b6632009-09-02 06:11:42 +0000776struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000777 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000778 // These optimizations require TargetData.
779 if (!TD) return 0;
780
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000781 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000782 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000783 !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000785 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000786 return 0;
787
788 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000789 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
790 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000791 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000792 }
793};
794
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000795//===---------------------------------------===//
796// 'memmove' Optimizations
797
Chris Lattner3e8b6632009-09-02 06:11:42 +0000798struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000799 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000800 // These optimizations require TargetData.
801 if (!TD) return 0;
802
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000803 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000804 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000805 !FT->getParamType(0)->isPointerTy() ||
806 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000807 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000808 return 0;
809
810 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000811 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
812 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000813 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000814 }
815};
816
817//===---------------------------------------===//
818// 'memset' Optimizations
819
Chris Lattner3e8b6632009-09-02 06:11:42 +0000820struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000822 // These optimizations require TargetData.
823 if (!TD) return 0;
824
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000825 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000826 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000827 !FT->getParamType(0)->isPointerTy() ||
828 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000829 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000830 return 0;
831
832 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000833 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
834 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000835 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000836 }
837};
838
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839//===----------------------------------------------------------------------===//
840// Math Library Optimizations
841//===----------------------------------------------------------------------===//
842
843//===---------------------------------------===//
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000844// 'cos*' Optimizations
845
846struct CosOpt : public LibCallOptimization {
847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
848 FunctionType *FT = Callee->getFunctionType();
849 // Just make sure this has 1 argument of FP type, which matches the
850 // result type.
851 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
852 !FT->getParamType(0)->isFloatingPointTy())
853 return 0;
854
855 // cos(-x) -> cos(x)
856 Value *Op1 = CI->getArgOperand(0);
857 if (BinaryOperator::isFNeg(Op1)) {
858 BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
859 return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
860 }
861 return 0;
862 }
863};
864
865//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000866// 'pow*' Optimizations
867
Chris Lattner3e8b6632009-09-02 06:11:42 +0000868struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000869 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000870 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000871 // Just make sure this has 2 arguments of the same FP type, which match the
872 // result type.
873 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
874 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000875 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000876 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000877
Gabor Greifaee5dc12010-06-24 10:42:46 +0000878 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000879 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
880 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
881 return Op1C;
882 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000883 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000884 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000885
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000886 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
887 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000888
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000889 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000890 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000891
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000892 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000893 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
894 // This is faster than calling pow, and still handles negative zero
Nick Lewyckya6b21ea2011-12-27 18:25:50 +0000895 // and negative infinity correctly.
Dan Gohman79cb8402009-09-25 23:10:17 +0000896 // TODO: In fast-math mode, this could be just sqrt(x).
897 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000898 Value *Inf = ConstantFP::getInfinity(CI->getType());
899 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000900 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
901 Callee->getAttributes());
902 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
903 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000904 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
905 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000906 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000907 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000908
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000909 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
910 return Op1;
911 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000912 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000913 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000914 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000915 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000916 return 0;
917 }
918};
919
920//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000921// 'exp2' Optimizations
922
Chris Lattner3e8b6632009-09-02 06:11:42 +0000923struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000924 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000925 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000926 // Just make sure this has 1 argument of FP type, which matches the
927 // result type.
928 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000929 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000930 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000931
Gabor Greifaee5dc12010-06-24 10:42:46 +0000932 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000933 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
934 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
935 Value *LdExpArg = 0;
936 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
937 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000938 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000939 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
940 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000941 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000942 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000943
Chris Lattnere818f772008-05-02 18:43:35 +0000944 if (LdExpArg) {
945 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000946 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000947 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000948 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000949 Name = "ldexp";
950 else
951 Name = "ldexpl";
952
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000953 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000954 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000955 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000956
957 Module *M = Caller->getParent();
958 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000959 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000960 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000961 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
962 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
963 CI->setCallingConv(F->getCallingConv());
964
965 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000966 }
967 return 0;
968 }
969};
Chris Lattnere818f772008-05-02 18:43:35 +0000970
971//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000972// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
973
Chris Lattner3e8b6632009-09-02 06:11:42 +0000974struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000975 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000976 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000977 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
978 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000979 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000980
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000981 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000982 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000983 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000984 return 0;
985
986 // floor((double)floatval) -> (double)floorf(floatval)
987 Value *V = Cast->getOperand(0);
Benjamin Kramerb5ccb252011-11-15 19:12:09 +0000988 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000989 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000990 }
991};
992
993//===----------------------------------------------------------------------===//
994// Integer Optimizations
995//===----------------------------------------------------------------------===//
996
997//===---------------------------------------===//
998// 'ffs*' Optimizations
999
Chris Lattner3e8b6632009-09-02 06:11:42 +00001000struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001001 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001002 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001003 // Just make sure this has 2 arguments of the same FP type, which match the
1004 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001005 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +00001006 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +00001007 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001008 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001009
Gabor Greifaee5dc12010-06-24 10:42:46 +00001010 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001011
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001012 // Constant fold.
1013 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1014 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001015 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001016 // ffs(c) -> cttz(c)+1
1017 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001019
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001020 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +00001021 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001022 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001023 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001024 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001025 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1026 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001027
Benjamin Kramera9390a42011-09-27 20:39:19 +00001028 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001029 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001030 }
1031};
1032
1033//===---------------------------------------===//
1034// 'isdigit' Optimizations
1035
Chris Lattner3e8b6632009-09-02 06:11:42 +00001036struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001037 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001038 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001039 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001040 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001041 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001042 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001043
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001044 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001045 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001046 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1047 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001048 return B.CreateZExt(Op, CI->getType());
1049 }
1050};
1051
1052//===---------------------------------------===//
1053// 'isascii' Optimizations
1054
Chris Lattner3e8b6632009-09-02 06:11:42 +00001055struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001057 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001058 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001059 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001060 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001061 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001062
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001063 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001064 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001065 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001066 return B.CreateZExt(Op, CI->getType());
1067 }
1068};
Eric Christopher37c8b862009-10-07 21:14:25 +00001069
Chris Lattner313f0e62008-06-09 08:26:51 +00001070//===---------------------------------------===//
1071// 'abs', 'labs', 'llabs' Optimizations
1072
Chris Lattner3e8b6632009-09-02 06:11:42 +00001073struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001074 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001075 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001076 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001077 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001078 FT->getParamType(0) != FT->getReturnType())
1079 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001080
Chris Lattner313f0e62008-06-09 08:26:51 +00001081 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001082 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001083 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001084 "ispos");
1085 Value *Neg = B.CreateNeg(Op, "neg");
1086 return B.CreateSelect(Pos, Op, Neg);
1087 }
1088};
Eric Christopher37c8b862009-10-07 21:14:25 +00001089
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001090
1091//===---------------------------------------===//
1092// 'toascii' Optimizations
1093
Chris Lattner3e8b6632009-09-02 06:11:42 +00001094struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001095 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001096 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001097 // We require i32(i32)
1098 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001099 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001100 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001101
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001102 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001103 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001104 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001105 }
1106};
1107
1108//===----------------------------------------------------------------------===//
1109// Formatting and IO Optimizations
1110//===----------------------------------------------------------------------===//
1111
1112//===---------------------------------------===//
1113// 'printf' Optimizations
1114
Chris Lattner3e8b6632009-09-02 06:11:42 +00001115struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001116 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1117 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001118 // Check for a fixed format string.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001119 std::string FormatStr;
1120 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001121 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001122
1123 // Empty format string -> noop.
1124 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001125 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001126 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001127
Daniel Dunbard02be242011-02-12 18:19:57 +00001128 // Do not do any of the following transformations if the printf return value
1129 // is used, in general the printf return value is not compatible with either
1130 // putchar() or puts().
1131 if (!CI->use_empty())
1132 return 0;
1133
1134 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001135 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001136 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001137 if (CI->use_empty()) return CI;
1138 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001139 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001140
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001141 // printf("foo\n") --> puts("foo")
1142 if (FormatStr[FormatStr.size()-1] == '\n' &&
1143 FormatStr.find('%') == std::string::npos) { // no format characters.
1144 // Create a string literal with no \n on it. We expect the constant merge
1145 // pass to be run after this pass, to merge duplicate strings.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001146 FormatStr.erase(FormatStr.end()-1);
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001147 Value *GV = B.CreateGlobalString(FormatStr, "str");
1148 EmitPutS(GV, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +00001149 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001150 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001151 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001152
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001153 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001154 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001155 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001156 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1157 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001158
Chris Lattner74965f22009-11-09 04:57:04 +00001159 if (CI->use_empty()) return CI;
1160 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001161 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001162
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001163 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001164 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001165 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001166 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001167 return CI;
1168 }
1169 return 0;
1170 }
Richard Osborne36498242011-03-03 13:17:51 +00001171
1172 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1173 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001174 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001175 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1176 !(FT->getReturnType()->isIntegerTy() ||
1177 FT->getReturnType()->isVoidTy()))
1178 return 0;
1179
1180 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1181 return V;
1182 }
1183
1184 // printf(format, ...) -> iprintf(format, ...) if no floating point
1185 // arguments.
1186 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1187 Module *M = B.GetInsertBlock()->getParent()->getParent();
1188 Constant *IPrintFFn =
1189 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1190 CallInst *New = cast<CallInst>(CI->clone());
1191 New->setCalledFunction(IPrintFFn);
1192 B.Insert(New);
1193 return New;
1194 }
1195 return 0;
1196 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001197};
1198
1199//===---------------------------------------===//
1200// 'sprintf' Optimizations
1201
Chris Lattner3e8b6632009-09-02 06:11:42 +00001202struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001203 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1204 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001205 // Check for a fixed format string.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001206 std::string FormatStr;
1207 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001208 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001209
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001211 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001212 // Make sure there's no % in the constant array. We could try to handle
1213 // %% -> % in the future if we cared.
1214 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1215 if (FormatStr[i] == '%')
1216 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001217
1218 // These optimizations require TargetData.
1219 if (!TD) return 0;
1220
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001222 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1223 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1224 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001225 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001226 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001227
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001228 // The remaining optimizations require the format string to be "%s" or "%c"
1229 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001230 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1231 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001232 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001233
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001234 // Decode the second character of the format string.
1235 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001236 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001237 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001238 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001239 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001240 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001241 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1242 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001243
Owen Andersoneed707b2009-07-24 23:12:02 +00001244 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001245 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001246
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001247 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001248 // These optimizations require TargetData.
1249 if (!TD) return 0;
1250
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001251 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001252 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001253
Gabor Greifaee5dc12010-06-24 10:42:46 +00001254 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001255 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001256 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001257 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001258 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001259
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001260 // The sprintf result is the unincremented number of bytes in the string.
1261 return B.CreateIntCast(Len, CI->getType(), false);
1262 }
1263 return 0;
1264 }
Richard Osborne419454a2011-03-03 14:09:28 +00001265
1266 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1267 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001268 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001269 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1270 !FT->getParamType(1)->isPointerTy() ||
1271 !FT->getReturnType()->isIntegerTy())
1272 return 0;
1273
1274 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1275 return V;
1276 }
1277
Richard Osborneea2578c2011-03-03 14:21:22 +00001278 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001279 // point arguments.
1280 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1281 Module *M = B.GetInsertBlock()->getParent()->getParent();
1282 Constant *SIPrintFFn =
1283 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1284 CallInst *New = cast<CallInst>(CI->clone());
1285 New->setCalledFunction(SIPrintFFn);
1286 B.Insert(New);
1287 return New;
1288 }
1289 return 0;
1290 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001291};
1292
1293//===---------------------------------------===//
1294// 'fwrite' Optimizations
1295
Chris Lattner3e8b6632009-09-02 06:11:42 +00001296struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001297 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001298 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001299 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001300 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1301 !FT->getParamType(1)->isIntegerTy() ||
1302 !FT->getParamType(2)->isIntegerTy() ||
1303 !FT->getParamType(3)->isPointerTy() ||
1304 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001305 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001306
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001307 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001308 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1309 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001310 if (!SizeC || !CountC) return 0;
1311 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001312
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001313 // If this is writing zero records, remove the call (it's a noop).
1314 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001315 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001316
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001317 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001318 // This optimisation is only valid, if the return value is unused.
1319 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001320 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1321 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001322 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001323 }
1324
1325 return 0;
1326 }
1327};
1328
1329//===---------------------------------------===//
1330// 'fputs' Optimizations
1331
Chris Lattner3e8b6632009-09-02 06:11:42 +00001332struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001333 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001334 // These optimizations require TargetData.
1335 if (!TD) return 0;
1336
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001337 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001338 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001339 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1340 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001341 !CI->use_empty())
1342 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001343
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001344 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001345 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001346 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001347 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001348 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Eli Friedman9d434db2011-11-17 01:27:36 +00001349 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001350 return CI; // Known to have no uses (see above).
1351 }
1352};
1353
1354//===---------------------------------------===//
1355// 'fprintf' Optimizations
1356
Chris Lattner3e8b6632009-09-02 06:11:42 +00001357struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001358 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1359 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 // All the optimizations depend on the format string.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001361 std::string FormatStr;
1362 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001363 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001364
1365 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001366 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001367 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1368 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001369 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001370
1371 // These optimizations require TargetData.
1372 if (!TD) return 0;
1373
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001375 ConstantInt::get(TD->getIntPtrType(*Context),
1376 FormatStr.size()),
Eli Friedman9d434db2011-11-17 01:27:36 +00001377 CI->getArgOperand(0), B, TD, TLI);
Owen Andersoneed707b2009-07-24 23:12:02 +00001378 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001379 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001380
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001381 // The remaining optimizations require the format string to be "%s" or "%c"
1382 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001383 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1384 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001385 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001386
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001387 // Decode the second character of the format string.
1388 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001389 // fprintf(F, "%c", chr) --> fputc(chr, F)
1390 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1391 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001392 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001393 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001394
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001395 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001396 // fprintf(F, "%s", str) --> fputs(str, F)
1397 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001398 return 0;
Eli Friedman9d434db2011-11-17 01:27:36 +00001399 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001400 return CI;
1401 }
1402 return 0;
1403 }
Richard Osborne022708f2011-03-03 14:20:22 +00001404
1405 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1406 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001407 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001408 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1409 !FT->getParamType(1)->isPointerTy() ||
1410 !FT->getReturnType()->isIntegerTy())
1411 return 0;
1412
1413 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1414 return V;
1415 }
1416
1417 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1418 // floating point arguments.
1419 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1420 Module *M = B.GetInsertBlock()->getParent()->getParent();
1421 Constant *FIPrintFFn =
1422 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1423 CallInst *New = cast<CallInst>(CI->clone());
1424 New->setCalledFunction(FIPrintFFn);
1425 B.Insert(New);
1426 return New;
1427 }
1428 return 0;
1429 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001430};
1431
Anders Carlsson303023d2010-11-30 06:19:18 +00001432//===---------------------------------------===//
1433// 'puts' Optimizations
1434
1435struct PutsOpt : public LibCallOptimization {
1436 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1437 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001438 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001439 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1440 !(FT->getReturnType()->isIntegerTy() ||
1441 FT->getReturnType()->isVoidTy()))
1442 return 0;
1443
1444 // Check for a constant string.
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001445 std::string Str;
1446 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
Anders Carlsson303023d2010-11-30 06:19:18 +00001447 return 0;
1448
Daniel Dunbard02be242011-02-12 18:19:57 +00001449 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001450 // puts("") -> putchar('\n')
1451 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1452 if (CI->use_empty()) return CI;
1453 return B.CreateIntCast(Res, CI->getType(), true);
1454 }
1455
1456 return 0;
1457 }
1458};
1459
Bill Wendlingac178222008-05-05 21:37:59 +00001460} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001461
1462//===----------------------------------------------------------------------===//
1463// SimplifyLibCalls Pass Implementation
1464//===----------------------------------------------------------------------===//
1465
1466namespace {
1467 /// This pass optimizes well known library functions from libc and libm.
1468 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001469 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001470 TargetLibraryInfo *TLI;
1471
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001472 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001473 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001474 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1475 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001476 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001477 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001478 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001479 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001480 CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001481 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001482 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1483 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001484 // Formatting and IO Optimizations
1485 SPrintFOpt SPrintF; PrintFOpt PrintF;
1486 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001487 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001488
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001489 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001490 public:
1491 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +00001492 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1493 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1494 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001495 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001496 void InitOptimizations();
1497 bool runOnFunction(Function &F);
1498
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001499 void setDoesNotAccessMemory(Function &F);
1500 void setOnlyReadsMemory(Function &F);
1501 void setDoesNotThrow(Function &F);
1502 void setDoesNotCapture(Function &F, unsigned n);
1503 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001504 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001505
Chris Lattnere265ad82011-02-24 07:12:12 +00001506 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001507 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001508 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001509 }
1510 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001511} // end anonymous namespace.
1512
Chris Lattnerafbf4832011-02-24 07:16:14 +00001513char SimplifyLibCalls::ID = 0;
1514
1515INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1516 "Simplify well-known library calls", false, false)
1517INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1518INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1519 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001520
1521// Public interface to the Simplify LibCalls pass.
1522FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001523 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001524}
1525
Eli Friedman9d434db2011-11-17 01:27:36 +00001526void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1527 if (TLI->has(F))
1528 Optimizations[TLI->getName(F)] = Opt;
1529}
1530
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001531/// Optimizations - Populate the Optimizations map with all the optimizations
1532/// we know.
1533void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001534 // String and Memory LibCall Optimizations
1535 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001536 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001537 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001538 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001539 Optimizations["strcmp"] = &StrCmp;
1540 Optimizations["strncmp"] = &StrNCmp;
1541 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001542 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001543 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001544 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001545 Optimizations["strtol"] = &StrTo;
1546 Optimizations["strtod"] = &StrTo;
1547 Optimizations["strtof"] = &StrTo;
1548 Optimizations["strtoul"] = &StrTo;
1549 Optimizations["strtoll"] = &StrTo;
1550 Optimizations["strtold"] = &StrTo;
1551 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001552 Optimizations["strspn"] = &StrSpn;
1553 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001554 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001555 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001556 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001557 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001558 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001559
Evan Cheng0289b412010-03-23 15:48:04 +00001560 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001561 Optimizations["__strcpy_chk"] = &StrCpyChk;
1562
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001563 // Math Library Optimizations
Nick Lewyckya6b21ea2011-12-27 18:25:50 +00001564 Optimizations["cosf"] = &Cos;
1565 Optimizations["cos"] = &Cos;
1566 Optimizations["cosl"] = &Cos;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001567 Optimizations["powf"] = &Pow;
1568 Optimizations["pow"] = &Pow;
1569 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001570 Optimizations["llvm.pow.f32"] = &Pow;
1571 Optimizations["llvm.pow.f64"] = &Pow;
1572 Optimizations["llvm.pow.f80"] = &Pow;
1573 Optimizations["llvm.pow.f128"] = &Pow;
1574 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001575 Optimizations["exp2l"] = &Exp2;
1576 Optimizations["exp2"] = &Exp2;
1577 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001578 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1579 Optimizations["llvm.exp2.f128"] = &Exp2;
1580 Optimizations["llvm.exp2.f80"] = &Exp2;
1581 Optimizations["llvm.exp2.f64"] = &Exp2;
1582 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001583
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584#ifdef HAVE_FLOORF
1585 Optimizations["floor"] = &UnaryDoubleFP;
1586#endif
1587#ifdef HAVE_CEILF
1588 Optimizations["ceil"] = &UnaryDoubleFP;
1589#endif
1590#ifdef HAVE_ROUNDF
1591 Optimizations["round"] = &UnaryDoubleFP;
1592#endif
1593#ifdef HAVE_RINTF
1594 Optimizations["rint"] = &UnaryDoubleFP;
1595#endif
1596#ifdef HAVE_NEARBYINTF
1597 Optimizations["nearbyint"] = &UnaryDoubleFP;
1598#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001599
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001600 // Integer Optimizations
1601 Optimizations["ffs"] = &FFS;
1602 Optimizations["ffsl"] = &FFS;
1603 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001604 Optimizations["abs"] = &Abs;
1605 Optimizations["labs"] = &Abs;
1606 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001607 Optimizations["isdigit"] = &IsDigit;
1608 Optimizations["isascii"] = &IsAscii;
1609 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001610
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001611 // Formatting and IO Optimizations
1612 Optimizations["sprintf"] = &SPrintF;
1613 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001614 AddOpt(LibFunc::fwrite, &FWrite);
1615 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001616 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001617 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001618}
1619
1620
1621/// runOnFunction - Top level algorithm.
1622///
1623bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001624 TLI = &getAnalysis<TargetLibraryInfo>();
1625
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001626 if (Optimizations.empty())
1627 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001628
Dan Gohmanf14d9192009-08-18 00:48:13 +00001629 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001630
Owen Andersone922c022009-07-22 00:24:57 +00001631 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001632
1633 bool Changed = false;
1634 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1635 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1636 // Ignore non-calls.
1637 CallInst *CI = dyn_cast<CallInst>(I++);
1638 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001639
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001640 // Ignore indirect calls and calls to non-external functions.
1641 Function *Callee = CI->getCalledFunction();
1642 if (Callee == 0 || !Callee->isDeclaration() ||
1643 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1644 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001645
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001646 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001647 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1648 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001649
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001650 // Set the builder to the instruction after the call.
1651 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001652
Devang Patela2ab3992011-03-09 21:27:52 +00001653 // Use debug location of CI for all new instructions.
1654 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1655
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001656 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001657 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001658 if (Result == 0) continue;
1659
David Greene6a6b90e2010-01-05 01:27:21 +00001660 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1661 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001662
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001663 // Something changed!
1664 Changed = true;
1665 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001666
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001667 // Inspect the instruction after the call (which was potentially just
1668 // added) next.
1669 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001670
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001671 if (CI != Result && !CI->use_empty()) {
1672 CI->replaceAllUsesWith(Result);
1673 if (!Result->hasName())
1674 Result->takeName(CI);
1675 }
1676 CI->eraseFromParent();
1677 }
1678 }
1679 return Changed;
1680}
1681
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001682// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001683
1684void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1685 if (!F.doesNotAccessMemory()) {
1686 F.setDoesNotAccessMemory();
1687 ++NumAnnotated;
1688 Modified = true;
1689 }
1690}
1691void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1692 if (!F.onlyReadsMemory()) {
1693 F.setOnlyReadsMemory();
1694 ++NumAnnotated;
1695 Modified = true;
1696 }
1697}
1698void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1699 if (!F.doesNotThrow()) {
1700 F.setDoesNotThrow();
1701 ++NumAnnotated;
1702 Modified = true;
1703 }
1704}
1705void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1706 if (!F.doesNotCapture(n)) {
1707 F.setDoesNotCapture(n);
1708 ++NumAnnotated;
1709 Modified = true;
1710 }
1711}
1712void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1713 if (!F.doesNotAlias(n)) {
1714 F.setDoesNotAlias(n);
1715 ++NumAnnotated;
1716 Modified = true;
1717 }
1718}
1719
Chris Lattnere265ad82011-02-24 07:12:12 +00001720
1721void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001722 FunctionType *FTy = F.getFunctionType();
Chris Lattnere265ad82011-02-24 07:12:12 +00001723
1724 StringRef Name = F.getName();
1725 switch (Name[0]) {
1726 case 's':
1727 if (Name == "strlen") {
1728 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1729 return;
1730 setOnlyReadsMemory(F);
1731 setDoesNotThrow(F);
1732 setDoesNotCapture(F, 1);
1733 } else if (Name == "strchr" ||
1734 Name == "strrchr") {
1735 if (FTy->getNumParams() != 2 ||
1736 !FTy->getParamType(0)->isPointerTy() ||
1737 !FTy->getParamType(1)->isIntegerTy())
1738 return;
1739 setOnlyReadsMemory(F);
1740 setDoesNotThrow(F);
1741 } else if (Name == "strcpy" ||
1742 Name == "stpcpy" ||
1743 Name == "strcat" ||
1744 Name == "strtol" ||
1745 Name == "strtod" ||
1746 Name == "strtof" ||
1747 Name == "strtoul" ||
1748 Name == "strtoll" ||
1749 Name == "strtold" ||
1750 Name == "strncat" ||
1751 Name == "strncpy" ||
1752 Name == "strtoull") {
1753 if (FTy->getNumParams() < 2 ||
1754 !FTy->getParamType(1)->isPointerTy())
1755 return;
1756 setDoesNotThrow(F);
1757 setDoesNotCapture(F, 2);
1758 } else if (Name == "strxfrm") {
1759 if (FTy->getNumParams() != 3 ||
1760 !FTy->getParamType(0)->isPointerTy() ||
1761 !FTy->getParamType(1)->isPointerTy())
1762 return;
1763 setDoesNotThrow(F);
1764 setDoesNotCapture(F, 1);
1765 setDoesNotCapture(F, 2);
1766 } else if (Name == "strcmp" ||
1767 Name == "strspn" ||
1768 Name == "strncmp" ||
1769 Name == "strcspn" ||
1770 Name == "strcoll" ||
1771 Name == "strcasecmp" ||
1772 Name == "strncasecmp") {
1773 if (FTy->getNumParams() < 2 ||
1774 !FTy->getParamType(0)->isPointerTy() ||
1775 !FTy->getParamType(1)->isPointerTy())
1776 return;
1777 setOnlyReadsMemory(F);
1778 setDoesNotThrow(F);
1779 setDoesNotCapture(F, 1);
1780 setDoesNotCapture(F, 2);
1781 } else if (Name == "strstr" ||
1782 Name == "strpbrk") {
1783 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1784 return;
1785 setOnlyReadsMemory(F);
1786 setDoesNotThrow(F);
1787 setDoesNotCapture(F, 2);
1788 } else if (Name == "strtok" ||
1789 Name == "strtok_r") {
1790 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1791 return;
1792 setDoesNotThrow(F);
1793 setDoesNotCapture(F, 2);
1794 } else if (Name == "scanf" ||
1795 Name == "setbuf" ||
1796 Name == "setvbuf") {
1797 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1798 return;
1799 setDoesNotThrow(F);
1800 setDoesNotCapture(F, 1);
1801 } else if (Name == "strdup" ||
1802 Name == "strndup") {
1803 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1804 !FTy->getParamType(0)->isPointerTy())
1805 return;
1806 setDoesNotThrow(F);
1807 setDoesNotAlias(F, 0);
1808 setDoesNotCapture(F, 1);
1809 } else if (Name == "stat" ||
1810 Name == "sscanf" ||
1811 Name == "sprintf" ||
1812 Name == "statvfs") {
1813 if (FTy->getNumParams() < 2 ||
1814 !FTy->getParamType(0)->isPointerTy() ||
1815 !FTy->getParamType(1)->isPointerTy())
1816 return;
1817 setDoesNotThrow(F);
1818 setDoesNotCapture(F, 1);
1819 setDoesNotCapture(F, 2);
1820 } else if (Name == "snprintf") {
1821 if (FTy->getNumParams() != 3 ||
1822 !FTy->getParamType(0)->isPointerTy() ||
1823 !FTy->getParamType(2)->isPointerTy())
1824 return;
1825 setDoesNotThrow(F);
1826 setDoesNotCapture(F, 1);
1827 setDoesNotCapture(F, 3);
1828 } else if (Name == "setitimer") {
1829 if (FTy->getNumParams() != 3 ||
1830 !FTy->getParamType(1)->isPointerTy() ||
1831 !FTy->getParamType(2)->isPointerTy())
1832 return;
1833 setDoesNotThrow(F);
1834 setDoesNotCapture(F, 2);
1835 setDoesNotCapture(F, 3);
1836 } else if (Name == "system") {
1837 if (FTy->getNumParams() != 1 ||
1838 !FTy->getParamType(0)->isPointerTy())
1839 return;
1840 // May throw; "system" is a valid pthread cancellation point.
1841 setDoesNotCapture(F, 1);
1842 }
1843 break;
1844 case 'm':
1845 if (Name == "malloc") {
1846 if (FTy->getNumParams() != 1 ||
1847 !FTy->getReturnType()->isPointerTy())
1848 return;
1849 setDoesNotThrow(F);
1850 setDoesNotAlias(F, 0);
1851 } else if (Name == "memcmp") {
1852 if (FTy->getNumParams() != 3 ||
1853 !FTy->getParamType(0)->isPointerTy() ||
1854 !FTy->getParamType(1)->isPointerTy())
1855 return;
1856 setOnlyReadsMemory(F);
1857 setDoesNotThrow(F);
1858 setDoesNotCapture(F, 1);
1859 setDoesNotCapture(F, 2);
1860 } else if (Name == "memchr" ||
1861 Name == "memrchr") {
1862 if (FTy->getNumParams() != 3)
1863 return;
1864 setOnlyReadsMemory(F);
1865 setDoesNotThrow(F);
1866 } else if (Name == "modf" ||
1867 Name == "modff" ||
1868 Name == "modfl" ||
1869 Name == "memcpy" ||
1870 Name == "memccpy" ||
1871 Name == "memmove") {
1872 if (FTy->getNumParams() < 2 ||
1873 !FTy->getParamType(1)->isPointerTy())
1874 return;
1875 setDoesNotThrow(F);
1876 setDoesNotCapture(F, 2);
1877 } else if (Name == "memalign") {
1878 if (!FTy->getReturnType()->isPointerTy())
1879 return;
1880 setDoesNotAlias(F, 0);
1881 } else if (Name == "mkdir" ||
1882 Name == "mktime") {
1883 if (FTy->getNumParams() == 0 ||
1884 !FTy->getParamType(0)->isPointerTy())
1885 return;
1886 setDoesNotThrow(F);
1887 setDoesNotCapture(F, 1);
1888 }
1889 break;
1890 case 'r':
1891 if (Name == "realloc") {
1892 if (FTy->getNumParams() != 2 ||
1893 !FTy->getParamType(0)->isPointerTy() ||
1894 !FTy->getReturnType()->isPointerTy())
1895 return;
1896 setDoesNotThrow(F);
1897 setDoesNotAlias(F, 0);
1898 setDoesNotCapture(F, 1);
1899 } else if (Name == "read") {
1900 if (FTy->getNumParams() != 3 ||
1901 !FTy->getParamType(1)->isPointerTy())
1902 return;
1903 // May throw; "read" is a valid pthread cancellation point.
1904 setDoesNotCapture(F, 2);
1905 } else if (Name == "rmdir" ||
1906 Name == "rewind" ||
1907 Name == "remove" ||
1908 Name == "realpath") {
1909 if (FTy->getNumParams() < 1 ||
1910 !FTy->getParamType(0)->isPointerTy())
1911 return;
1912 setDoesNotThrow(F);
1913 setDoesNotCapture(F, 1);
1914 } else if (Name == "rename" ||
1915 Name == "readlink") {
1916 if (FTy->getNumParams() < 2 ||
1917 !FTy->getParamType(0)->isPointerTy() ||
1918 !FTy->getParamType(1)->isPointerTy())
1919 return;
1920 setDoesNotThrow(F);
1921 setDoesNotCapture(F, 1);
1922 setDoesNotCapture(F, 2);
1923 }
1924 break;
1925 case 'w':
1926 if (Name == "write") {
1927 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1928 return;
1929 // May throw; "write" is a valid pthread cancellation point.
1930 setDoesNotCapture(F, 2);
1931 }
1932 break;
1933 case 'b':
1934 if (Name == "bcopy") {
1935 if (FTy->getNumParams() != 3 ||
1936 !FTy->getParamType(0)->isPointerTy() ||
1937 !FTy->getParamType(1)->isPointerTy())
1938 return;
1939 setDoesNotThrow(F);
1940 setDoesNotCapture(F, 1);
1941 setDoesNotCapture(F, 2);
1942 } else if (Name == "bcmp") {
1943 if (FTy->getNumParams() != 3 ||
1944 !FTy->getParamType(0)->isPointerTy() ||
1945 !FTy->getParamType(1)->isPointerTy())
1946 return;
1947 setDoesNotThrow(F);
1948 setOnlyReadsMemory(F);
1949 setDoesNotCapture(F, 1);
1950 setDoesNotCapture(F, 2);
1951 } else if (Name == "bzero") {
1952 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1953 return;
1954 setDoesNotThrow(F);
1955 setDoesNotCapture(F, 1);
1956 }
1957 break;
1958 case 'c':
1959 if (Name == "calloc") {
1960 if (FTy->getNumParams() != 2 ||
1961 !FTy->getReturnType()->isPointerTy())
1962 return;
1963 setDoesNotThrow(F);
1964 setDoesNotAlias(F, 0);
1965 } else if (Name == "chmod" ||
1966 Name == "chown" ||
1967 Name == "ctermid" ||
1968 Name == "clearerr" ||
1969 Name == "closedir") {
1970 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1971 return;
1972 setDoesNotThrow(F);
1973 setDoesNotCapture(F, 1);
1974 }
1975 break;
1976 case 'a':
1977 if (Name == "atoi" ||
1978 Name == "atol" ||
1979 Name == "atof" ||
1980 Name == "atoll") {
1981 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1982 return;
1983 setDoesNotThrow(F);
1984 setOnlyReadsMemory(F);
1985 setDoesNotCapture(F, 1);
1986 } else if (Name == "access") {
1987 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1988 return;
1989 setDoesNotThrow(F);
1990 setDoesNotCapture(F, 1);
1991 }
1992 break;
1993 case 'f':
1994 if (Name == "fopen") {
1995 if (FTy->getNumParams() != 2 ||
1996 !FTy->getReturnType()->isPointerTy() ||
1997 !FTy->getParamType(0)->isPointerTy() ||
1998 !FTy->getParamType(1)->isPointerTy())
1999 return;
2000 setDoesNotThrow(F);
2001 setDoesNotAlias(F, 0);
2002 setDoesNotCapture(F, 1);
2003 setDoesNotCapture(F, 2);
2004 } else if (Name == "fdopen") {
2005 if (FTy->getNumParams() != 2 ||
2006 !FTy->getReturnType()->isPointerTy() ||
2007 !FTy->getParamType(1)->isPointerTy())
2008 return;
2009 setDoesNotThrow(F);
2010 setDoesNotAlias(F, 0);
2011 setDoesNotCapture(F, 2);
2012 } else if (Name == "feof" ||
2013 Name == "free" ||
2014 Name == "fseek" ||
2015 Name == "ftell" ||
2016 Name == "fgetc" ||
2017 Name == "fseeko" ||
2018 Name == "ftello" ||
2019 Name == "fileno" ||
2020 Name == "fflush" ||
2021 Name == "fclose" ||
2022 Name == "fsetpos" ||
2023 Name == "flockfile" ||
2024 Name == "funlockfile" ||
2025 Name == "ftrylockfile") {
2026 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2027 return;
2028 setDoesNotThrow(F);
2029 setDoesNotCapture(F, 1);
2030 } else if (Name == "ferror") {
2031 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2032 return;
2033 setDoesNotThrow(F);
2034 setDoesNotCapture(F, 1);
2035 setOnlyReadsMemory(F);
2036 } else if (Name == "fputc" ||
2037 Name == "fstat" ||
2038 Name == "frexp" ||
2039 Name == "frexpf" ||
2040 Name == "frexpl" ||
2041 Name == "fstatvfs") {
2042 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2043 return;
2044 setDoesNotThrow(F);
2045 setDoesNotCapture(F, 2);
2046 } else if (Name == "fgets") {
2047 if (FTy->getNumParams() != 3 ||
2048 !FTy->getParamType(0)->isPointerTy() ||
2049 !FTy->getParamType(2)->isPointerTy())
2050 return;
2051 setDoesNotThrow(F);
2052 setDoesNotCapture(F, 3);
2053 } else if (Name == "fread" ||
2054 Name == "fwrite") {
2055 if (FTy->getNumParams() != 4 ||
2056 !FTy->getParamType(0)->isPointerTy() ||
2057 !FTy->getParamType(3)->isPointerTy())
2058 return;
2059 setDoesNotThrow(F);
2060 setDoesNotCapture(F, 1);
2061 setDoesNotCapture(F, 4);
2062 } else if (Name == "fputs" ||
2063 Name == "fscanf" ||
2064 Name == "fprintf" ||
2065 Name == "fgetpos") {
2066 if (FTy->getNumParams() < 2 ||
2067 !FTy->getParamType(0)->isPointerTy() ||
2068 !FTy->getParamType(1)->isPointerTy())
2069 return;
2070 setDoesNotThrow(F);
2071 setDoesNotCapture(F, 1);
2072 setDoesNotCapture(F, 2);
2073 }
2074 break;
2075 case 'g':
2076 if (Name == "getc" ||
2077 Name == "getlogin_r" ||
2078 Name == "getc_unlocked") {
2079 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2080 return;
2081 setDoesNotThrow(F);
2082 setDoesNotCapture(F, 1);
2083 } else if (Name == "getenv") {
2084 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2085 return;
2086 setDoesNotThrow(F);
2087 setOnlyReadsMemory(F);
2088 setDoesNotCapture(F, 1);
2089 } else if (Name == "gets" ||
2090 Name == "getchar") {
2091 setDoesNotThrow(F);
2092 } else if (Name == "getitimer") {
2093 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2094 return;
2095 setDoesNotThrow(F);
2096 setDoesNotCapture(F, 2);
2097 } else if (Name == "getpwnam") {
2098 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2099 return;
2100 setDoesNotThrow(F);
2101 setDoesNotCapture(F, 1);
2102 }
2103 break;
2104 case 'u':
2105 if (Name == "ungetc") {
2106 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2107 return;
2108 setDoesNotThrow(F);
2109 setDoesNotCapture(F, 2);
2110 } else if (Name == "uname" ||
2111 Name == "unlink" ||
2112 Name == "unsetenv") {
2113 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2114 return;
2115 setDoesNotThrow(F);
2116 setDoesNotCapture(F, 1);
2117 } else if (Name == "utime" ||
2118 Name == "utimes") {
2119 if (FTy->getNumParams() != 2 ||
2120 !FTy->getParamType(0)->isPointerTy() ||
2121 !FTy->getParamType(1)->isPointerTy())
2122 return;
2123 setDoesNotThrow(F);
2124 setDoesNotCapture(F, 1);
2125 setDoesNotCapture(F, 2);
2126 }
2127 break;
2128 case 'p':
2129 if (Name == "putc") {
2130 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2131 return;
2132 setDoesNotThrow(F);
2133 setDoesNotCapture(F, 2);
2134 } else if (Name == "puts" ||
2135 Name == "printf" ||
2136 Name == "perror") {
2137 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2138 return;
2139 setDoesNotThrow(F);
2140 setDoesNotCapture(F, 1);
2141 } else if (Name == "pread" ||
2142 Name == "pwrite") {
2143 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2144 return;
2145 // May throw; these are valid pthread cancellation points.
2146 setDoesNotCapture(F, 2);
2147 } else if (Name == "putchar") {
2148 setDoesNotThrow(F);
2149 } else if (Name == "popen") {
2150 if (FTy->getNumParams() != 2 ||
2151 !FTy->getReturnType()->isPointerTy() ||
2152 !FTy->getParamType(0)->isPointerTy() ||
2153 !FTy->getParamType(1)->isPointerTy())
2154 return;
2155 setDoesNotThrow(F);
2156 setDoesNotAlias(F, 0);
2157 setDoesNotCapture(F, 1);
2158 setDoesNotCapture(F, 2);
2159 } else if (Name == "pclose") {
2160 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2161 return;
2162 setDoesNotThrow(F);
2163 setDoesNotCapture(F, 1);
2164 }
2165 break;
2166 case 'v':
2167 if (Name == "vscanf") {
2168 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2169 return;
2170 setDoesNotThrow(F);
2171 setDoesNotCapture(F, 1);
2172 } else if (Name == "vsscanf" ||
2173 Name == "vfscanf") {
2174 if (FTy->getNumParams() != 3 ||
2175 !FTy->getParamType(1)->isPointerTy() ||
2176 !FTy->getParamType(2)->isPointerTy())
2177 return;
2178 setDoesNotThrow(F);
2179 setDoesNotCapture(F, 1);
2180 setDoesNotCapture(F, 2);
2181 } else if (Name == "valloc") {
2182 if (!FTy->getReturnType()->isPointerTy())
2183 return;
2184 setDoesNotThrow(F);
2185 setDoesNotAlias(F, 0);
2186 } else if (Name == "vprintf") {
2187 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2188 return;
2189 setDoesNotThrow(F);
2190 setDoesNotCapture(F, 1);
2191 } else if (Name == "vfprintf" ||
2192 Name == "vsprintf") {
2193 if (FTy->getNumParams() != 3 ||
2194 !FTy->getParamType(0)->isPointerTy() ||
2195 !FTy->getParamType(1)->isPointerTy())
2196 return;
2197 setDoesNotThrow(F);
2198 setDoesNotCapture(F, 1);
2199 setDoesNotCapture(F, 2);
2200 } else if (Name == "vsnprintf") {
2201 if (FTy->getNumParams() != 4 ||
2202 !FTy->getParamType(0)->isPointerTy() ||
2203 !FTy->getParamType(2)->isPointerTy())
2204 return;
2205 setDoesNotThrow(F);
2206 setDoesNotCapture(F, 1);
2207 setDoesNotCapture(F, 3);
2208 }
2209 break;
2210 case 'o':
2211 if (Name == "open") {
2212 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2213 return;
2214 // May throw; "open" is a valid pthread cancellation point.
2215 setDoesNotCapture(F, 1);
2216 } else if (Name == "opendir") {
2217 if (FTy->getNumParams() != 1 ||
2218 !FTy->getReturnType()->isPointerTy() ||
2219 !FTy->getParamType(0)->isPointerTy())
2220 return;
2221 setDoesNotThrow(F);
2222 setDoesNotAlias(F, 0);
2223 setDoesNotCapture(F, 1);
2224 }
2225 break;
2226 case 't':
2227 if (Name == "tmpfile") {
2228 if (!FTy->getReturnType()->isPointerTy())
2229 return;
2230 setDoesNotThrow(F);
2231 setDoesNotAlias(F, 0);
2232 } else if (Name == "times") {
2233 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2234 return;
2235 setDoesNotThrow(F);
2236 setDoesNotCapture(F, 1);
2237 }
2238 break;
2239 case 'h':
2240 if (Name == "htonl" ||
2241 Name == "htons") {
2242 setDoesNotThrow(F);
2243 setDoesNotAccessMemory(F);
2244 }
2245 break;
2246 case 'n':
2247 if (Name == "ntohl" ||
2248 Name == "ntohs") {
2249 setDoesNotThrow(F);
2250 setDoesNotAccessMemory(F);
2251 }
2252 break;
2253 case 'l':
2254 if (Name == "lstat") {
2255 if (FTy->getNumParams() != 2 ||
2256 !FTy->getParamType(0)->isPointerTy() ||
2257 !FTy->getParamType(1)->isPointerTy())
2258 return;
2259 setDoesNotThrow(F);
2260 setDoesNotCapture(F, 1);
2261 setDoesNotCapture(F, 2);
2262 } else if (Name == "lchown") {
2263 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2264 return;
2265 setDoesNotThrow(F);
2266 setDoesNotCapture(F, 1);
2267 }
2268 break;
2269 case 'q':
2270 if (Name == "qsort") {
2271 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2272 return;
2273 // May throw; places call through function pointer.
2274 setDoesNotCapture(F, 4);
2275 }
2276 break;
2277 case '_':
2278 if (Name == "__strdup" ||
2279 Name == "__strndup") {
2280 if (FTy->getNumParams() < 1 ||
2281 !FTy->getReturnType()->isPointerTy() ||
2282 !FTy->getParamType(0)->isPointerTy())
2283 return;
2284 setDoesNotThrow(F);
2285 setDoesNotAlias(F, 0);
2286 setDoesNotCapture(F, 1);
2287 } else if (Name == "__strtok_r") {
2288 if (FTy->getNumParams() != 3 ||
2289 !FTy->getParamType(1)->isPointerTy())
2290 return;
2291 setDoesNotThrow(F);
2292 setDoesNotCapture(F, 2);
2293 } else if (Name == "_IO_getc") {
2294 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2295 return;
2296 setDoesNotThrow(F);
2297 setDoesNotCapture(F, 1);
2298 } else if (Name == "_IO_putc") {
2299 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2300 return;
2301 setDoesNotThrow(F);
2302 setDoesNotCapture(F, 2);
2303 }
2304 break;
2305 case 1:
2306 if (Name == "\1__isoc99_scanf") {
2307 if (FTy->getNumParams() < 1 ||
2308 !FTy->getParamType(0)->isPointerTy())
2309 return;
2310 setDoesNotThrow(F);
2311 setDoesNotCapture(F, 1);
2312 } else if (Name == "\1stat64" ||
2313 Name == "\1lstat64" ||
2314 Name == "\1statvfs64" ||
2315 Name == "\1__isoc99_sscanf") {
2316 if (FTy->getNumParams() < 1 ||
2317 !FTy->getParamType(0)->isPointerTy() ||
2318 !FTy->getParamType(1)->isPointerTy())
2319 return;
2320 setDoesNotThrow(F);
2321 setDoesNotCapture(F, 1);
2322 setDoesNotCapture(F, 2);
2323 } else if (Name == "\1fopen64") {
2324 if (FTy->getNumParams() != 2 ||
2325 !FTy->getReturnType()->isPointerTy() ||
2326 !FTy->getParamType(0)->isPointerTy() ||
2327 !FTy->getParamType(1)->isPointerTy())
2328 return;
2329 setDoesNotThrow(F);
2330 setDoesNotAlias(F, 0);
2331 setDoesNotCapture(F, 1);
2332 setDoesNotCapture(F, 2);
2333 } else if (Name == "\1fseeko64" ||
2334 Name == "\1ftello64") {
2335 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2336 return;
2337 setDoesNotThrow(F);
2338 setDoesNotCapture(F, 1);
2339 } else if (Name == "\1tmpfile64") {
2340 if (!FTy->getReturnType()->isPointerTy())
2341 return;
2342 setDoesNotThrow(F);
2343 setDoesNotAlias(F, 0);
2344 } else if (Name == "\1fstat64" ||
2345 Name == "\1fstatvfs64") {
2346 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2347 return;
2348 setDoesNotThrow(F);
2349 setDoesNotCapture(F, 2);
2350 } else if (Name == "\1open64") {
2351 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2352 return;
2353 // May throw; "open" is a valid pthread cancellation point.
2354 setDoesNotCapture(F, 1);
2355 }
2356 break;
2357 }
2358}
2359
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002360/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002361///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002362bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002363 Modified = false;
2364 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2365 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002366 if (F.isDeclaration() && F.hasName())
2367 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002368 }
2369 return Modified;
2370}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002371
2372// TODO:
2373// Additional cases that we need to add to this file:
2374//
2375// cbrt:
2376// * cbrt(expN(X)) -> expN(x/3)
2377// * cbrt(sqrt(x)) -> pow(x,1/6)
2378// * cbrt(sqrt(x)) -> pow(x,1/9)
2379//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002380// exp, expf, expl:
2381// * exp(log(x)) -> x
2382//
2383// log, logf, logl:
2384// * log(exp(x)) -> x
2385// * log(x**y) -> y*log(x)
2386// * log(exp(y)) -> y*log(e)
2387// * log(exp2(y)) -> y*log(2)
2388// * log(exp10(y)) -> y*log(10)
2389// * log(sqrt(x)) -> 0.5*log(x)
2390// * log(pow(x,y)) -> y*log(x)
2391//
2392// lround, lroundf, lroundl:
2393// * lround(cnst) -> cnst'
2394//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002395// pow, powf, powl:
2396// * pow(exp(x),y) -> exp(x*y)
2397// * pow(sqrt(x),y) -> pow(x,y*0.5)
2398// * pow(pow(x,y),z)-> pow(x,y*z)
2399//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002400// round, roundf, roundl:
2401// * round(cnst) -> cnst'
2402//
2403// signbit:
2404// * signbit(cnst) -> cnst'
2405// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2406//
2407// sqrt, sqrtf, sqrtl:
2408// * sqrt(expN(x)) -> expN(x*0.5)
2409// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2410// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2411//
2412// stpcpy:
2413// * stpcpy(str, "literal") ->
2414// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002415//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002416// tan, tanf, tanl:
2417// * tan(atan(x)) -> x
2418//
2419// trunc, truncf, truncl:
2420// * trunc(cnst) -> cnst'
2421//
2422//