blob: 6247b0348f14e1828075ca9b6941a8f6506479e0 [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.
137 const FunctionType *FT = Callee->getFunctionType();
138 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.
187 const FunctionType *FT = Callee->getFunctionType();
188 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.
235 const FunctionType *FT = Callee->getFunctionType();
236 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 }
259
260 // Otherwise, the character is a constant, see if the first argument is
261 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +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
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000266 // strchr can find the nul character.
267 Str += '\0';
Eric Christopher37c8b862009-10-07 21:14:25 +0000268
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000269 // Compute the offset.
Benjamin Kramere2609902010-09-29 22:29:12 +0000270 size_t I = Str.find(CharC->getSExtValue());
271 if (I == std::string::npos) // Didn't find the char. strchr returns null.
272 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.
285 const FunctionType *FT = Callee->getFunctionType();
286 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
299 std::string Str;
300 if (!GetConstantStringInfo(SrcStr, Str)) {
301 // strrchr(s, 0) -> strchr(s, 0)
302 if (TD && CharC->isZero())
303 return EmitStrChr(SrcStr, '\0', B, TD);
304 return 0;
305 }
306
307 // strrchr can find the nul character.
308 Str += '\0';
309
310 // Compute the offset.
311 size_t I = Str.rfind(CharC->getSExtValue());
312 if (I == std::string::npos) // Didn't find the char. Return null.
313 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.
326 const 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
Bill Wendling0582ae92009-03-13 04:39:26 +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
Bill Wendling0582ae92009-03-13 04:39:26 +0000341 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000342 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000343
Bill Wendling0582ae92009-03-13 04:39:26 +0000344 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000345 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000346
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000347 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000348 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000349 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000350 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000351
352 // strcmp(P, "x") -> memcmp(P, "x", 2)
353 uint64_t Len1 = GetStringLength(Str1P);
354 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000355 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000356 // These optimizations require TargetData.
357 if (!TD) return 0;
358
Nick Lewycky13a09e22008-12-21 00:19:21 +0000359 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000360 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000361 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000362 }
363
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000364 return 0;
365 }
366};
367
368//===---------------------------------------===//
369// 'strncmp' Optimizations
370
Chris Lattner3e8b6632009-09-02 06:11:42 +0000371struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000372 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000373 // Verify the "strncmp" function prototype.
374 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000375 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000376 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000377 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000378 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000379 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000381
Gabor Greifaee5dc12010-06-24 10:42:46 +0000382 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000383 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000384 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000385
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 // Get the length argument if it is constant.
387 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000388 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000389 Length = LengthArg->getZExtValue();
390 else
391 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000392
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000393 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000394 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000395
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000396 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000397 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000398
Bill Wendling0582ae92009-03-13 04:39:26 +0000399 std::string Str1, Str2;
400 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
401 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000402
Bill Wendling0582ae92009-03-13 04:39:26 +0000403 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000404 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000405
Bill Wendling0582ae92009-03-13 04:39:26 +0000406 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000407 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000408
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000409 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000410 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000411 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000412 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000413 return 0;
414 }
415};
416
417
418//===---------------------------------------===//
419// 'strcpy' Optimizations
420
Chris Lattner3e8b6632009-09-02 06:11:42 +0000421struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000422 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
423
424 StrCpyOpt(bool c) : OptChkCall(c) {}
425
Eric Christopher7a61d702008-08-08 19:39:37 +0000426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000427 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000428 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000429 const FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000430 if (FT->getNumParams() != NumParams ||
431 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000432 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000433 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000434 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000435
Gabor Greifaee5dc12010-06-24 10:42:46 +0000436 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 if (Dst == Src) // strcpy(x,x) -> x
438 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000439
Dan Gohmanf14d9192009-08-18 00:48:13 +0000440 // These optimizations require TargetData.
441 if (!TD) return 0;
442
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000443 // See if we can get the length of the input string.
444 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000445 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000446
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000447 // We have enough information to now generate the memcpy call to do the
448 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000449 if (OptChkCall)
450 EmitMemCpyChk(Dst, Src,
451 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000452 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000453 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000454 B.CreateMemCpy(Dst, Src,
455 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000456 return Dst;
457 }
458};
459
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000460//===---------------------------------------===//
461// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000462
Chris Lattner3e8b6632009-09-02 06:11:42 +0000463struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000464 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
465 const FunctionType *FT = Callee->getFunctionType();
466 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
467 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000468 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000469 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000470 return 0;
471
Gabor Greifaee5dc12010-06-24 10:42:46 +0000472 Value *Dst = CI->getArgOperand(0);
473 Value *Src = CI->getArgOperand(1);
474 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000475
476 // See if we can get the length of the input string.
477 uint64_t SrcLen = GetStringLength(Src);
478 if (SrcLen == 0) return 0;
479 --SrcLen;
480
481 if (SrcLen == 0) {
482 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000483 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000484 return Dst;
485 }
486
487 uint64_t Len;
488 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
489 Len = LengthArg->getZExtValue();
490 else
491 return 0;
492
493 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
494
Dan Gohmanf14d9192009-08-18 00:48:13 +0000495 // These optimizations require TargetData.
496 if (!TD) return 0;
497
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000498 // Let strncpy handle the zero padding
499 if (Len > SrcLen+1) return 0;
500
501 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000502 B.CreateMemCpy(Dst, Src,
503 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000504
505 return Dst;
506 }
507};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000508
509//===---------------------------------------===//
510// 'strlen' Optimizations
511
Chris Lattner3e8b6632009-09-02 06:11:42 +0000512struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000513 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000514 const FunctionType *FT = Callee->getFunctionType();
515 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000516 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000517 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000518 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000519
Gabor Greifaee5dc12010-06-24 10:42:46 +0000520 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000521
522 // Constant folding: strlen("xyz") -> 3
523 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000524 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000525
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526 // strlen(x) != 0 --> *x != 0
527 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000528 if (IsOnlyUsedInZeroEqualityComparison(CI))
529 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
530 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000531 }
532};
533
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000534
535//===---------------------------------------===//
536// 'strpbrk' Optimizations
537
538struct StrPBrkOpt : public LibCallOptimization {
539 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
540 const FunctionType *FT = Callee->getFunctionType();
541 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000542 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000543 FT->getParamType(1) != FT->getParamType(0) ||
544 FT->getReturnType() != FT->getParamType(0))
545 return 0;
546
547 std::string S1, S2;
548 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
549 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
550
551 // strpbrk(s, "") -> NULL
552 // strpbrk("", s) -> NULL
553 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
554 return Constant::getNullValue(CI->getType());
555
556 // Constant folding.
557 if (HasS1 && HasS2) {
558 size_t I = S1.find_first_of(S2);
559 if (I == std::string::npos) // No match.
560 return Constant::getNullValue(CI->getType());
561
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000562 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000563 }
564
565 // strpbrk(s, "a") -> strchr(s, 'a')
566 if (TD && HasS2 && S2.size() == 1)
567 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
568
569 return 0;
570 }
571};
572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000573//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000574// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000575
Chris Lattner3e8b6632009-09-02 06:11:42 +0000576struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000577 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
578 const FunctionType *FT = Callee->getFunctionType();
579 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000580 !FT->getParamType(0)->isPointerTy() ||
581 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000582 return 0;
583
Gabor Greifaee5dc12010-06-24 10:42:46 +0000584 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000585 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000586 // With a null EndPtr, this function won't capture the main argument.
587 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000588 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000589 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000590
591 return 0;
592 }
593};
594
Chris Lattner24604112009-12-16 09:32:05 +0000595//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000596// 'strspn' Optimizations
597
598struct StrSpnOpt : public LibCallOptimization {
599 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
600 const FunctionType *FT = Callee->getFunctionType();
601 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000602 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000603 FT->getParamType(1) != FT->getParamType(0) ||
604 !FT->getReturnType()->isIntegerTy())
605 return 0;
606
607 std::string S1, S2;
608 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
609 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
610
611 // strspn(s, "") -> 0
612 // strspn("", s) -> 0
613 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
614 return Constant::getNullValue(CI->getType());
615
616 // Constant folding.
617 if (HasS1 && HasS2)
618 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
619
620 return 0;
621 }
622};
623
624//===---------------------------------------===//
625// 'strcspn' Optimizations
626
627struct StrCSpnOpt : public LibCallOptimization {
628 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
629 const FunctionType *FT = Callee->getFunctionType();
630 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000631 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000632 FT->getParamType(1) != FT->getParamType(0) ||
633 !FT->getReturnType()->isIntegerTy())
634 return 0;
635
636 std::string S1, S2;
637 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
638 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
639
640 // strcspn("", s) -> 0
641 if (HasS1 && S1.empty())
642 return Constant::getNullValue(CI->getType());
643
644 // Constant folding.
645 if (HasS1 && HasS2)
646 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
647
648 // strcspn(s, "") -> strlen(s)
649 if (TD && HasS2 && S2.empty())
650 return EmitStrLen(CI->getArgOperand(0), B, TD);
651
652 return 0;
653 }
654};
655
656//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000657// 'strstr' Optimizations
658
659struct StrStrOpt : public LibCallOptimization {
660 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
661 const FunctionType *FT = Callee->getFunctionType();
662 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000663 !FT->getParamType(0)->isPointerTy() ||
664 !FT->getParamType(1)->isPointerTy() ||
665 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000666 return 0;
667
668 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000669 if (CI->getArgOperand(0) == CI->getArgOperand(1))
670 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000671
Benjamin Kramer386e9182010-06-15 21:34:25 +0000672 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000673 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
674 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
675 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000676 StrLen, B, TD);
677 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
678 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000679 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000680 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
681 ConstantInt::getNullValue(StrNCmp->getType()),
682 "cmp");
683 Old->replaceAllUsesWith(Cmp);
684 Old->eraseFromParent();
685 }
686 return CI;
687 }
688
Chris Lattner24604112009-12-16 09:32:05 +0000689 // See if either input string is a constant string.
690 std::string SearchStr, ToFindStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000691 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
692 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000693
Chris Lattner24604112009-12-16 09:32:05 +0000694 // fold strstr(x, "") -> x.
695 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000696 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000697
Chris Lattner24604112009-12-16 09:32:05 +0000698 // If both strings are known, constant fold it.
699 if (HasStr1 && HasStr2) {
700 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000701
Chris Lattner24604112009-12-16 09:32:05 +0000702 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
703 return Constant::getNullValue(CI->getType());
704
705 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000706 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000707 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
708 return B.CreateBitCast(Result, CI->getType());
709 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000710
Chris Lattner24604112009-12-16 09:32:05 +0000711 // fold strstr(x, "y") -> strchr(x, 'y').
712 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000713 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
714 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000715 return 0;
716 }
717};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000718
Nick Lewycky4c498412009-02-13 15:31:46 +0000719
720//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000721// 'memcmp' Optimizations
722
Chris Lattner3e8b6632009-09-02 06:11:42 +0000723struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000724 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000725 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000726 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
727 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000728 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000729 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000730
Gabor Greifaee5dc12010-06-24 10:42:46 +0000731 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000732
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000733 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000734 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000735
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000736 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000737 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000738 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000739 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000740
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000741 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000742 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000743
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000744 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
745 if (Len == 1) {
746 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
747 CI->getType(), "lhsv");
748 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
749 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000750 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000751 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000752
Benjamin Kramer992a6372009-11-05 17:44:22 +0000753 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
754 std::string LHSStr, RHSStr;
755 if (GetConstantStringInfo(LHS, LHSStr) &&
756 GetConstantStringInfo(RHS, RHSStr)) {
757 // Make sure we're not reading out-of-bounds memory.
758 if (Len > LHSStr.length() || Len > RHSStr.length())
759 return 0;
760 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
761 return ConstantInt::get(CI->getType(), Ret);
762 }
763
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000764 return 0;
765 }
766};
767
768//===---------------------------------------===//
769// 'memcpy' Optimizations
770
Chris Lattner3e8b6632009-09-02 06:11:42 +0000771struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000772 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000773 // These optimizations require TargetData.
774 if (!TD) return 0;
775
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000776 const FunctionType *FT = Callee->getFunctionType();
777 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000778 !FT->getParamType(0)->isPointerTy() ||
779 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000780 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000781 return 0;
782
783 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000784 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
785 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000786 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000787 }
788};
789
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000790//===---------------------------------------===//
791// 'memmove' Optimizations
792
Chris Lattner3e8b6632009-09-02 06:11:42 +0000793struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000794 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000795 // These optimizations require TargetData.
796 if (!TD) return 0;
797
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000798 const FunctionType *FT = Callee->getFunctionType();
799 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000800 !FT->getParamType(0)->isPointerTy() ||
801 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000802 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000803 return 0;
804
805 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000806 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
807 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000808 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000809 }
810};
811
812//===---------------------------------------===//
813// 'memset' Optimizations
814
Chris Lattner3e8b6632009-09-02 06:11:42 +0000815struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000816 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000817 // These optimizations require TargetData.
818 if (!TD) return 0;
819
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000820 const FunctionType *FT = Callee->getFunctionType();
821 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000822 !FT->getParamType(0)->isPointerTy() ||
823 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000824 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000825 return 0;
826
827 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000828 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
829 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000830 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000831 }
832};
833
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000834//===----------------------------------------------------------------------===//
835// Math Library Optimizations
836//===----------------------------------------------------------------------===//
837
838//===---------------------------------------===//
839// 'pow*' Optimizations
840
Chris Lattner3e8b6632009-09-02 06:11:42 +0000841struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000842 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000843 const FunctionType *FT = Callee->getFunctionType();
844 // Just make sure this has 2 arguments of the same FP type, which match the
845 // result type.
846 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
847 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000848 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000849 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000850
Gabor Greifaee5dc12010-06-24 10:42:46 +0000851 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000852 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
853 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
854 return Op1C;
855 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000856 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000858
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000859 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
860 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000861
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000862 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000863 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000864
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000865 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000866 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
867 // This is faster than calling pow, and still handles negative zero
868 // and negative infinite correctly.
869 // TODO: In fast-math mode, this could be just sqrt(x).
870 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000871 Value *Inf = ConstantFP::getInfinity(CI->getType());
872 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000873 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
874 Callee->getAttributes());
875 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
876 Callee->getAttributes());
Dan Gohman79cb8402009-09-25 23:10:17 +0000877 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
878 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
879 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000880 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000881
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000882 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
883 return Op1;
884 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000885 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000886 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000887 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000888 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000889 return 0;
890 }
891};
892
893//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000894// 'exp2' Optimizations
895
Chris Lattner3e8b6632009-09-02 06:11:42 +0000896struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000897 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +0000898 const FunctionType *FT = Callee->getFunctionType();
899 // Just make sure this has 1 argument of FP type, which matches the
900 // result type.
901 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000902 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000903 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000904
Gabor Greifaee5dc12010-06-24 10:42:46 +0000905 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000906 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
907 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
908 Value *LdExpArg = 0;
909 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
910 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000911 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +0000912 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
913 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000914 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty(), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +0000915 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000916
Chris Lattnere818f772008-05-02 18:43:35 +0000917 if (LdExpArg) {
918 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000919 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000920 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000921 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000922 Name = "ldexp";
923 else
924 Name = "ldexpl";
925
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000926 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000927 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000928 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000929
930 Module *M = Caller->getParent();
931 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000932 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000933 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000934 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
935 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
936 CI->setCallingConv(F->getCallingConv());
937
938 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000939 }
940 return 0;
941 }
942};
Chris Lattnere818f772008-05-02 18:43:35 +0000943
944//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000945// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
946
Chris Lattner3e8b6632009-09-02 06:11:42 +0000947struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000948 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000949 const FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000950 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
951 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000952 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000953
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000954 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000955 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000956 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000957 return 0;
958
959 // floor((double)floatval) -> (double)floorf(floatval)
960 Value *V = Cast->getOperand(0);
Dan Gohman76926b62009-09-26 18:10:13 +0000961 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
962 Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000963 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000964 }
965};
966
967//===----------------------------------------------------------------------===//
968// Integer Optimizations
969//===----------------------------------------------------------------------===//
970
971//===---------------------------------------===//
972// 'ffs*' Optimizations
973
Chris Lattner3e8b6632009-09-02 06:11:42 +0000974struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000975 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000976 const FunctionType *FT = Callee->getFunctionType();
977 // Just make sure this has 2 arguments of the same FP type, which match the
978 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000979 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000980 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000981 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000982 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000983
Gabor Greifaee5dc12010-06-24 10:42:46 +0000984 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000985
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000986 // Constant fold.
987 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
988 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +0000989 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000990 // ffs(c) -> cttz(c)+1
991 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000992 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000993
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000994 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
995 const Type *ArgType = Op->getType();
996 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
997 Intrinsic::cttz, &ArgType, 1);
998 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +0000999 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001000 V = B.CreateIntCast(V, B.getInt32Ty(), false, "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001001
Owen Andersona7235ea2009-07-31 20:28:14 +00001002 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001003 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001004 }
1005};
1006
1007//===---------------------------------------===//
1008// 'isdigit' Optimizations
1009
Chris Lattner3e8b6632009-09-02 06:11:42 +00001010struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001011 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001012 const FunctionType *FT = Callee->getFunctionType();
1013 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001014 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001015 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001016 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001017
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001018 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001019 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001020 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1021 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001022 return B.CreateZExt(Op, CI->getType());
1023 }
1024};
1025
1026//===---------------------------------------===//
1027// 'isascii' Optimizations
1028
Chris Lattner3e8b6632009-09-02 06:11:42 +00001029struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001030 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001031 const FunctionType *FT = Callee->getFunctionType();
1032 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001033 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001034 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001035 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001036
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001037 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001038 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001039 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001040 return B.CreateZExt(Op, CI->getType());
1041 }
1042};
Eric Christopher37c8b862009-10-07 21:14:25 +00001043
Chris Lattner313f0e62008-06-09 08:26:51 +00001044//===---------------------------------------===//
1045// 'abs', 'labs', 'llabs' Optimizations
1046
Chris Lattner3e8b6632009-09-02 06:11:42 +00001047struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001048 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001049 const FunctionType *FT = Callee->getFunctionType();
1050 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001051 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001052 FT->getParamType(0) != FT->getReturnType())
1053 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001054
Chris Lattner313f0e62008-06-09 08:26:51 +00001055 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001056 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001057 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001058 "ispos");
1059 Value *Neg = B.CreateNeg(Op, "neg");
1060 return B.CreateSelect(Pos, Op, Neg);
1061 }
1062};
Eric Christopher37c8b862009-10-07 21:14:25 +00001063
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001064
1065//===---------------------------------------===//
1066// 'toascii' Optimizations
1067
Chris Lattner3e8b6632009-09-02 06:11:42 +00001068struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001069 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001070 const FunctionType *FT = Callee->getFunctionType();
1071 // We require i32(i32)
1072 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001073 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001074 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001075
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001076 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001077 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001078 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001079 }
1080};
1081
1082//===----------------------------------------------------------------------===//
1083// Formatting and IO Optimizations
1084//===----------------------------------------------------------------------===//
1085
1086//===---------------------------------------===//
1087// 'printf' Optimizations
1088
Chris Lattner3e8b6632009-09-02 06:11:42 +00001089struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001090 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1091 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001092 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001093 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001094 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001095 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001096
1097 // Empty format string -> noop.
1098 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001099 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001100 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001101
Daniel Dunbard02be242011-02-12 18:19:57 +00001102 // Do not do any of the following transformations if the printf return value
1103 // is used, in general the printf return value is not compatible with either
1104 // putchar() or puts().
1105 if (!CI->use_empty())
1106 return 0;
1107
1108 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001109 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001110 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001111 if (CI->use_empty()) return CI;
1112 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001113 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001114
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001115 // printf("foo\n") --> puts("foo")
1116 if (FormatStr[FormatStr.size()-1] == '\n' &&
1117 FormatStr.find('%') == std::string::npos) { // no format characters.
1118 // Create a string literal with no \n on it. We expect the constant merge
1119 // pass to be run after this pass, to merge duplicate strings.
1120 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001121 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001122 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1123 GlobalVariable::InternalLinkage, C, "str");
Eric Christopherb6174e32010-03-05 22:25:30 +00001124 EmitPutS(C, B, TD);
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(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001127 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001128
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001129 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001130 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001131 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001132 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1133 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001134
Chris Lattner74965f22009-11-09 04:57:04 +00001135 if (CI->use_empty()) return CI;
1136 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001137 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001138
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001139 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001140 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001141 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001142 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001143 return CI;
1144 }
1145 return 0;
1146 }
Richard Osborne36498242011-03-03 13:17:51 +00001147
1148 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1149 // Require one fixed pointer argument and an integer/void result.
1150 const FunctionType *FT = Callee->getFunctionType();
1151 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1152 !(FT->getReturnType()->isIntegerTy() ||
1153 FT->getReturnType()->isVoidTy()))
1154 return 0;
1155
1156 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1157 return V;
1158 }
1159
1160 // printf(format, ...) -> iprintf(format, ...) if no floating point
1161 // arguments.
1162 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1163 Module *M = B.GetInsertBlock()->getParent()->getParent();
1164 Constant *IPrintFFn =
1165 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1166 CallInst *New = cast<CallInst>(CI->clone());
1167 New->setCalledFunction(IPrintFFn);
1168 B.Insert(New);
1169 return New;
1170 }
1171 return 0;
1172 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001173};
1174
1175//===---------------------------------------===//
1176// 'sprintf' Optimizations
1177
Chris Lattner3e8b6632009-09-02 06:11:42 +00001178struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001179 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1180 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001181 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001182 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001183 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001184 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001185
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001186 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001187 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001188 // Make sure there's no % in the constant array. We could try to handle
1189 // %% -> % in the future if we cared.
1190 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1191 if (FormatStr[i] == '%')
1192 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001193
1194 // These optimizations require TargetData.
1195 if (!TD) return 0;
1196
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001197 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001198 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1199 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1200 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001201 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001202 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001203
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001204 // The remaining optimizations require the format string to be "%s" or "%c"
1205 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001206 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1207 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001208 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001209
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 // Decode the second character of the format string.
1211 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001212 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001213 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001214 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001215 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001216 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001217 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1218 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001219
Owen Andersoneed707b2009-07-24 23:12:02 +00001220 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001222
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001223 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001224 // These optimizations require TargetData.
1225 if (!TD) return 0;
1226
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001227 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001228 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229
Gabor Greifaee5dc12010-06-24 10:42:46 +00001230 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001231 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001232 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001233 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001234 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001235
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001236 // The sprintf result is the unincremented number of bytes in the string.
1237 return B.CreateIntCast(Len, CI->getType(), false);
1238 }
1239 return 0;
1240 }
Richard Osborne419454a2011-03-03 14:09:28 +00001241
1242 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1243 // Require two fixed pointer arguments and an integer result.
1244 const FunctionType *FT = Callee->getFunctionType();
1245 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1246 !FT->getParamType(1)->isPointerTy() ||
1247 !FT->getReturnType()->isIntegerTy())
1248 return 0;
1249
1250 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1251 return V;
1252 }
1253
Richard Osborneea2578c2011-03-03 14:21:22 +00001254 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001255 // point arguments.
1256 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1257 Module *M = B.GetInsertBlock()->getParent()->getParent();
1258 Constant *SIPrintFFn =
1259 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1260 CallInst *New = cast<CallInst>(CI->clone());
1261 New->setCalledFunction(SIPrintFFn);
1262 B.Insert(New);
1263 return New;
1264 }
1265 return 0;
1266 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001267};
1268
1269//===---------------------------------------===//
1270// 'fwrite' Optimizations
1271
Chris Lattner3e8b6632009-09-02 06:11:42 +00001272struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001273 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001274 // Require a pointer, an integer, an integer, a pointer, returning integer.
1275 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001276 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1277 !FT->getParamType(1)->isIntegerTy() ||
1278 !FT->getParamType(2)->isIntegerTy() ||
1279 !FT->getParamType(3)->isPointerTy() ||
1280 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001281 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001282
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001283 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001284 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1285 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286 if (!SizeC || !CountC) return 0;
1287 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001288
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001289 // If this is writing zero records, remove the call (it's a noop).
1290 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001291 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001292
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001293 // If this is writing one byte, turn it into fputc.
1294 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001295 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1296 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001297 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001298 }
1299
1300 return 0;
1301 }
1302};
1303
1304//===---------------------------------------===//
1305// 'fputs' Optimizations
1306
Chris Lattner3e8b6632009-09-02 06:11:42 +00001307struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001308 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001309 // These optimizations require TargetData.
1310 if (!TD) return 0;
1311
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001312 // Require two pointers. Also, we can't optimize if return value is used.
1313 const FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001314 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1315 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001316 !CI->use_empty())
1317 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001318
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001319 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001320 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001321 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001322 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001323 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001324 CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001325 return CI; // Known to have no uses (see above).
1326 }
1327};
1328
1329//===---------------------------------------===//
1330// 'fprintf' Optimizations
1331
Chris Lattner3e8b6632009-09-02 06:11:42 +00001332struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001333 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1334 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001335 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001336 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001337 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001338 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001339
1340 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001341 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1343 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001344 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001345
1346 // These optimizations require TargetData.
1347 if (!TD) return 0;
1348
Gabor Greifaee5dc12010-06-24 10:42:46 +00001349 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001350 ConstantInt::get(TD->getIntPtrType(*Context),
1351 FormatStr.size()),
Gabor Greifaee5dc12010-06-24 10:42:46 +00001352 CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001353 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001354 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001355
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001356 // The remaining optimizations require the format string to be "%s" or "%c"
1357 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001358 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1359 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001361
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 // Decode the second character of the format string.
1363 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001364 // fprintf(F, "%c", chr) --> fputc(chr, F)
1365 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1366 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001367 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001368 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001369
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001370 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001371 // fprintf(F, "%s", str) --> fputs(str, F)
1372 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001373 return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001375 return CI;
1376 }
1377 return 0;
1378 }
Richard Osborne022708f2011-03-03 14:20:22 +00001379
1380 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1381 // Require two fixed paramters as pointers and integer result.
1382 const FunctionType *FT = Callee->getFunctionType();
1383 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1384 !FT->getParamType(1)->isPointerTy() ||
1385 !FT->getReturnType()->isIntegerTy())
1386 return 0;
1387
1388 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1389 return V;
1390 }
1391
1392 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1393 // floating point arguments.
1394 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1395 Module *M = B.GetInsertBlock()->getParent()->getParent();
1396 Constant *FIPrintFFn =
1397 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1398 CallInst *New = cast<CallInst>(CI->clone());
1399 New->setCalledFunction(FIPrintFFn);
1400 B.Insert(New);
1401 return New;
1402 }
1403 return 0;
1404 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001405};
1406
Anders Carlsson303023d2010-11-30 06:19:18 +00001407//===---------------------------------------===//
1408// 'puts' Optimizations
1409
1410struct PutsOpt : public LibCallOptimization {
1411 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1412 // Require one fixed pointer argument and an integer/void result.
1413 const FunctionType *FT = Callee->getFunctionType();
1414 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1415 !(FT->getReturnType()->isIntegerTy() ||
1416 FT->getReturnType()->isVoidTy()))
1417 return 0;
1418
1419 // Check for a constant string.
1420 std::string Str;
1421 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1422 return 0;
1423
Daniel Dunbard02be242011-02-12 18:19:57 +00001424 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001425 // puts("") -> putchar('\n')
1426 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1427 if (CI->use_empty()) return CI;
1428 return B.CreateIntCast(Res, CI->getType(), true);
1429 }
1430
1431 return 0;
1432 }
1433};
1434
Bill Wendlingac178222008-05-05 21:37:59 +00001435} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001436
1437//===----------------------------------------------------------------------===//
1438// SimplifyLibCalls Pass Implementation
1439//===----------------------------------------------------------------------===//
1440
1441namespace {
1442 /// This pass optimizes well known library functions from libc and libm.
1443 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001444 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001445 TargetLibraryInfo *TLI;
1446
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001447 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001448 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001449 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1450 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001451 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001452 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001453 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001454 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001455 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001456 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001457 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1458 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001459 // Formatting and IO Optimizations
1460 SPrintFOpt SPrintF; PrintFOpt PrintF;
1461 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001462 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001463
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001464 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001465 public:
1466 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +00001467 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1468 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1469 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001470 void InitOptimizations();
1471 bool runOnFunction(Function &F);
1472
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001473 void setDoesNotAccessMemory(Function &F);
1474 void setOnlyReadsMemory(Function &F);
1475 void setDoesNotThrow(Function &F);
1476 void setDoesNotCapture(Function &F, unsigned n);
1477 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001478 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001479
Chris Lattnere265ad82011-02-24 07:12:12 +00001480 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001481 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001482 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001483 }
1484 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485} // end anonymous namespace.
1486
Chris Lattnerafbf4832011-02-24 07:16:14 +00001487char SimplifyLibCalls::ID = 0;
1488
1489INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1490 "Simplify well-known library calls", false, false)
1491INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1492INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1493 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001494
1495// Public interface to the Simplify LibCalls pass.
1496FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001497 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498}
1499
1500/// Optimizations - Populate the Optimizations map with all the optimizations
1501/// we know.
1502void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001503 // String and Memory LibCall Optimizations
1504 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001505 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001506 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001507 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001508 Optimizations["strcmp"] = &StrCmp;
1509 Optimizations["strncmp"] = &StrNCmp;
1510 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001511 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001512 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001513 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001514 Optimizations["strtol"] = &StrTo;
1515 Optimizations["strtod"] = &StrTo;
1516 Optimizations["strtof"] = &StrTo;
1517 Optimizations["strtoul"] = &StrTo;
1518 Optimizations["strtoll"] = &StrTo;
1519 Optimizations["strtold"] = &StrTo;
1520 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001521 Optimizations["strspn"] = &StrSpn;
1522 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001523 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001524 Optimizations["memcmp"] = &MemCmp;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001525 if (TLI->has(LibFunc::memcpy)) Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001526 Optimizations["memmove"] = &MemMove;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001527 if (TLI->has(LibFunc::memset)) Optimizations["memset"] = &MemSet;
Eric Christopher37c8b862009-10-07 21:14:25 +00001528
Evan Cheng0289b412010-03-23 15:48:04 +00001529 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001530 Optimizations["__strcpy_chk"] = &StrCpyChk;
1531
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001532 // Math Library Optimizations
1533 Optimizations["powf"] = &Pow;
1534 Optimizations["pow"] = &Pow;
1535 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001536 Optimizations["llvm.pow.f32"] = &Pow;
1537 Optimizations["llvm.pow.f64"] = &Pow;
1538 Optimizations["llvm.pow.f80"] = &Pow;
1539 Optimizations["llvm.pow.f128"] = &Pow;
1540 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001541 Optimizations["exp2l"] = &Exp2;
1542 Optimizations["exp2"] = &Exp2;
1543 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001544 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1545 Optimizations["llvm.exp2.f128"] = &Exp2;
1546 Optimizations["llvm.exp2.f80"] = &Exp2;
1547 Optimizations["llvm.exp2.f64"] = &Exp2;
1548 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001549
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001550#ifdef HAVE_FLOORF
1551 Optimizations["floor"] = &UnaryDoubleFP;
1552#endif
1553#ifdef HAVE_CEILF
1554 Optimizations["ceil"] = &UnaryDoubleFP;
1555#endif
1556#ifdef HAVE_ROUNDF
1557 Optimizations["round"] = &UnaryDoubleFP;
1558#endif
1559#ifdef HAVE_RINTF
1560 Optimizations["rint"] = &UnaryDoubleFP;
1561#endif
1562#ifdef HAVE_NEARBYINTF
1563 Optimizations["nearbyint"] = &UnaryDoubleFP;
1564#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001565
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001566 // Integer Optimizations
1567 Optimizations["ffs"] = &FFS;
1568 Optimizations["ffsl"] = &FFS;
1569 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001570 Optimizations["abs"] = &Abs;
1571 Optimizations["labs"] = &Abs;
1572 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001573 Optimizations["isdigit"] = &IsDigit;
1574 Optimizations["isascii"] = &IsAscii;
1575 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001576
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001577 // Formatting and IO Optimizations
1578 Optimizations["sprintf"] = &SPrintF;
1579 Optimizations["printf"] = &PrintF;
1580 Optimizations["fwrite"] = &FWrite;
1581 Optimizations["fputs"] = &FPuts;
1582 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001583 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001584}
1585
1586
1587/// runOnFunction - Top level algorithm.
1588///
1589bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001590 TLI = &getAnalysis<TargetLibraryInfo>();
1591
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001592 if (Optimizations.empty())
1593 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001594
Dan Gohmanf14d9192009-08-18 00:48:13 +00001595 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001596
Owen Andersone922c022009-07-22 00:24:57 +00001597 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001598
1599 bool Changed = false;
1600 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1601 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1602 // Ignore non-calls.
1603 CallInst *CI = dyn_cast<CallInst>(I++);
1604 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001605
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001606 // Ignore indirect calls and calls to non-external functions.
1607 Function *Callee = CI->getCalledFunction();
1608 if (Callee == 0 || !Callee->isDeclaration() ||
1609 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1610 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001611
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001612 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001613 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1614 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001615
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001616 // Set the builder to the instruction after the call.
1617 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001618
Devang Patela2ab3992011-03-09 21:27:52 +00001619 // Use debug location of CI for all new instructions.
1620 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1621
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001622 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001623 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001624 if (Result == 0) continue;
1625
David Greene6a6b90e2010-01-05 01:27:21 +00001626 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1627 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001628
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001629 // Something changed!
1630 Changed = true;
1631 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001632
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001633 // Inspect the instruction after the call (which was potentially just
1634 // added) next.
1635 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001636
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001637 if (CI != Result && !CI->use_empty()) {
1638 CI->replaceAllUsesWith(Result);
1639 if (!Result->hasName())
1640 Result->takeName(CI);
1641 }
1642 CI->eraseFromParent();
1643 }
1644 }
1645 return Changed;
1646}
1647
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001648// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001649
1650void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1651 if (!F.doesNotAccessMemory()) {
1652 F.setDoesNotAccessMemory();
1653 ++NumAnnotated;
1654 Modified = true;
1655 }
1656}
1657void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1658 if (!F.onlyReadsMemory()) {
1659 F.setOnlyReadsMemory();
1660 ++NumAnnotated;
1661 Modified = true;
1662 }
1663}
1664void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1665 if (!F.doesNotThrow()) {
1666 F.setDoesNotThrow();
1667 ++NumAnnotated;
1668 Modified = true;
1669 }
1670}
1671void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1672 if (!F.doesNotCapture(n)) {
1673 F.setDoesNotCapture(n);
1674 ++NumAnnotated;
1675 Modified = true;
1676 }
1677}
1678void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1679 if (!F.doesNotAlias(n)) {
1680 F.setDoesNotAlias(n);
1681 ++NumAnnotated;
1682 Modified = true;
1683 }
1684}
1685
Chris Lattnere265ad82011-02-24 07:12:12 +00001686
1687void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1688 const FunctionType *FTy = F.getFunctionType();
1689
1690 StringRef Name = F.getName();
1691 switch (Name[0]) {
1692 case 's':
1693 if (Name == "strlen") {
1694 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1695 return;
1696 setOnlyReadsMemory(F);
1697 setDoesNotThrow(F);
1698 setDoesNotCapture(F, 1);
1699 } else if (Name == "strchr" ||
1700 Name == "strrchr") {
1701 if (FTy->getNumParams() != 2 ||
1702 !FTy->getParamType(0)->isPointerTy() ||
1703 !FTy->getParamType(1)->isIntegerTy())
1704 return;
1705 setOnlyReadsMemory(F);
1706 setDoesNotThrow(F);
1707 } else if (Name == "strcpy" ||
1708 Name == "stpcpy" ||
1709 Name == "strcat" ||
1710 Name == "strtol" ||
1711 Name == "strtod" ||
1712 Name == "strtof" ||
1713 Name == "strtoul" ||
1714 Name == "strtoll" ||
1715 Name == "strtold" ||
1716 Name == "strncat" ||
1717 Name == "strncpy" ||
1718 Name == "strtoull") {
1719 if (FTy->getNumParams() < 2 ||
1720 !FTy->getParamType(1)->isPointerTy())
1721 return;
1722 setDoesNotThrow(F);
1723 setDoesNotCapture(F, 2);
1724 } else if (Name == "strxfrm") {
1725 if (FTy->getNumParams() != 3 ||
1726 !FTy->getParamType(0)->isPointerTy() ||
1727 !FTy->getParamType(1)->isPointerTy())
1728 return;
1729 setDoesNotThrow(F);
1730 setDoesNotCapture(F, 1);
1731 setDoesNotCapture(F, 2);
1732 } else if (Name == "strcmp" ||
1733 Name == "strspn" ||
1734 Name == "strncmp" ||
1735 Name == "strcspn" ||
1736 Name == "strcoll" ||
1737 Name == "strcasecmp" ||
1738 Name == "strncasecmp") {
1739 if (FTy->getNumParams() < 2 ||
1740 !FTy->getParamType(0)->isPointerTy() ||
1741 !FTy->getParamType(1)->isPointerTy())
1742 return;
1743 setOnlyReadsMemory(F);
1744 setDoesNotThrow(F);
1745 setDoesNotCapture(F, 1);
1746 setDoesNotCapture(F, 2);
1747 } else if (Name == "strstr" ||
1748 Name == "strpbrk") {
1749 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1750 return;
1751 setOnlyReadsMemory(F);
1752 setDoesNotThrow(F);
1753 setDoesNotCapture(F, 2);
1754 } else if (Name == "strtok" ||
1755 Name == "strtok_r") {
1756 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1757 return;
1758 setDoesNotThrow(F);
1759 setDoesNotCapture(F, 2);
1760 } else if (Name == "scanf" ||
1761 Name == "setbuf" ||
1762 Name == "setvbuf") {
1763 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1764 return;
1765 setDoesNotThrow(F);
1766 setDoesNotCapture(F, 1);
1767 } else if (Name == "strdup" ||
1768 Name == "strndup") {
1769 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1770 !FTy->getParamType(0)->isPointerTy())
1771 return;
1772 setDoesNotThrow(F);
1773 setDoesNotAlias(F, 0);
1774 setDoesNotCapture(F, 1);
1775 } else if (Name == "stat" ||
1776 Name == "sscanf" ||
1777 Name == "sprintf" ||
1778 Name == "statvfs") {
1779 if (FTy->getNumParams() < 2 ||
1780 !FTy->getParamType(0)->isPointerTy() ||
1781 !FTy->getParamType(1)->isPointerTy())
1782 return;
1783 setDoesNotThrow(F);
1784 setDoesNotCapture(F, 1);
1785 setDoesNotCapture(F, 2);
1786 } else if (Name == "snprintf") {
1787 if (FTy->getNumParams() != 3 ||
1788 !FTy->getParamType(0)->isPointerTy() ||
1789 !FTy->getParamType(2)->isPointerTy())
1790 return;
1791 setDoesNotThrow(F);
1792 setDoesNotCapture(F, 1);
1793 setDoesNotCapture(F, 3);
1794 } else if (Name == "setitimer") {
1795 if (FTy->getNumParams() != 3 ||
1796 !FTy->getParamType(1)->isPointerTy() ||
1797 !FTy->getParamType(2)->isPointerTy())
1798 return;
1799 setDoesNotThrow(F);
1800 setDoesNotCapture(F, 2);
1801 setDoesNotCapture(F, 3);
1802 } else if (Name == "system") {
1803 if (FTy->getNumParams() != 1 ||
1804 !FTy->getParamType(0)->isPointerTy())
1805 return;
1806 // May throw; "system" is a valid pthread cancellation point.
1807 setDoesNotCapture(F, 1);
1808 }
1809 break;
1810 case 'm':
1811 if (Name == "malloc") {
1812 if (FTy->getNumParams() != 1 ||
1813 !FTy->getReturnType()->isPointerTy())
1814 return;
1815 setDoesNotThrow(F);
1816 setDoesNotAlias(F, 0);
1817 } else if (Name == "memcmp") {
1818 if (FTy->getNumParams() != 3 ||
1819 !FTy->getParamType(0)->isPointerTy() ||
1820 !FTy->getParamType(1)->isPointerTy())
1821 return;
1822 setOnlyReadsMemory(F);
1823 setDoesNotThrow(F);
1824 setDoesNotCapture(F, 1);
1825 setDoesNotCapture(F, 2);
1826 } else if (Name == "memchr" ||
1827 Name == "memrchr") {
1828 if (FTy->getNumParams() != 3)
1829 return;
1830 setOnlyReadsMemory(F);
1831 setDoesNotThrow(F);
1832 } else if (Name == "modf" ||
1833 Name == "modff" ||
1834 Name == "modfl" ||
1835 Name == "memcpy" ||
1836 Name == "memccpy" ||
1837 Name == "memmove") {
1838 if (FTy->getNumParams() < 2 ||
1839 !FTy->getParamType(1)->isPointerTy())
1840 return;
1841 setDoesNotThrow(F);
1842 setDoesNotCapture(F, 2);
1843 } else if (Name == "memalign") {
1844 if (!FTy->getReturnType()->isPointerTy())
1845 return;
1846 setDoesNotAlias(F, 0);
1847 } else if (Name == "mkdir" ||
1848 Name == "mktime") {
1849 if (FTy->getNumParams() == 0 ||
1850 !FTy->getParamType(0)->isPointerTy())
1851 return;
1852 setDoesNotThrow(F);
1853 setDoesNotCapture(F, 1);
1854 }
1855 break;
1856 case 'r':
1857 if (Name == "realloc") {
1858 if (FTy->getNumParams() != 2 ||
1859 !FTy->getParamType(0)->isPointerTy() ||
1860 !FTy->getReturnType()->isPointerTy())
1861 return;
1862 setDoesNotThrow(F);
1863 setDoesNotAlias(F, 0);
1864 setDoesNotCapture(F, 1);
1865 } else if (Name == "read") {
1866 if (FTy->getNumParams() != 3 ||
1867 !FTy->getParamType(1)->isPointerTy())
1868 return;
1869 // May throw; "read" is a valid pthread cancellation point.
1870 setDoesNotCapture(F, 2);
1871 } else if (Name == "rmdir" ||
1872 Name == "rewind" ||
1873 Name == "remove" ||
1874 Name == "realpath") {
1875 if (FTy->getNumParams() < 1 ||
1876 !FTy->getParamType(0)->isPointerTy())
1877 return;
1878 setDoesNotThrow(F);
1879 setDoesNotCapture(F, 1);
1880 } else if (Name == "rename" ||
1881 Name == "readlink") {
1882 if (FTy->getNumParams() < 2 ||
1883 !FTy->getParamType(0)->isPointerTy() ||
1884 !FTy->getParamType(1)->isPointerTy())
1885 return;
1886 setDoesNotThrow(F);
1887 setDoesNotCapture(F, 1);
1888 setDoesNotCapture(F, 2);
1889 }
1890 break;
1891 case 'w':
1892 if (Name == "write") {
1893 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1894 return;
1895 // May throw; "write" is a valid pthread cancellation point.
1896 setDoesNotCapture(F, 2);
1897 }
1898 break;
1899 case 'b':
1900 if (Name == "bcopy") {
1901 if (FTy->getNumParams() != 3 ||
1902 !FTy->getParamType(0)->isPointerTy() ||
1903 !FTy->getParamType(1)->isPointerTy())
1904 return;
1905 setDoesNotThrow(F);
1906 setDoesNotCapture(F, 1);
1907 setDoesNotCapture(F, 2);
1908 } else if (Name == "bcmp") {
1909 if (FTy->getNumParams() != 3 ||
1910 !FTy->getParamType(0)->isPointerTy() ||
1911 !FTy->getParamType(1)->isPointerTy())
1912 return;
1913 setDoesNotThrow(F);
1914 setOnlyReadsMemory(F);
1915 setDoesNotCapture(F, 1);
1916 setDoesNotCapture(F, 2);
1917 } else if (Name == "bzero") {
1918 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1919 return;
1920 setDoesNotThrow(F);
1921 setDoesNotCapture(F, 1);
1922 }
1923 break;
1924 case 'c':
1925 if (Name == "calloc") {
1926 if (FTy->getNumParams() != 2 ||
1927 !FTy->getReturnType()->isPointerTy())
1928 return;
1929 setDoesNotThrow(F);
1930 setDoesNotAlias(F, 0);
1931 } else if (Name == "chmod" ||
1932 Name == "chown" ||
1933 Name == "ctermid" ||
1934 Name == "clearerr" ||
1935 Name == "closedir") {
1936 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1937 return;
1938 setDoesNotThrow(F);
1939 setDoesNotCapture(F, 1);
1940 }
1941 break;
1942 case 'a':
1943 if (Name == "atoi" ||
1944 Name == "atol" ||
1945 Name == "atof" ||
1946 Name == "atoll") {
1947 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1948 return;
1949 setDoesNotThrow(F);
1950 setOnlyReadsMemory(F);
1951 setDoesNotCapture(F, 1);
1952 } else if (Name == "access") {
1953 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1954 return;
1955 setDoesNotThrow(F);
1956 setDoesNotCapture(F, 1);
1957 }
1958 break;
1959 case 'f':
1960 if (Name == "fopen") {
1961 if (FTy->getNumParams() != 2 ||
1962 !FTy->getReturnType()->isPointerTy() ||
1963 !FTy->getParamType(0)->isPointerTy() ||
1964 !FTy->getParamType(1)->isPointerTy())
1965 return;
1966 setDoesNotThrow(F);
1967 setDoesNotAlias(F, 0);
1968 setDoesNotCapture(F, 1);
1969 setDoesNotCapture(F, 2);
1970 } else if (Name == "fdopen") {
1971 if (FTy->getNumParams() != 2 ||
1972 !FTy->getReturnType()->isPointerTy() ||
1973 !FTy->getParamType(1)->isPointerTy())
1974 return;
1975 setDoesNotThrow(F);
1976 setDoesNotAlias(F, 0);
1977 setDoesNotCapture(F, 2);
1978 } else if (Name == "feof" ||
1979 Name == "free" ||
1980 Name == "fseek" ||
1981 Name == "ftell" ||
1982 Name == "fgetc" ||
1983 Name == "fseeko" ||
1984 Name == "ftello" ||
1985 Name == "fileno" ||
1986 Name == "fflush" ||
1987 Name == "fclose" ||
1988 Name == "fsetpos" ||
1989 Name == "flockfile" ||
1990 Name == "funlockfile" ||
1991 Name == "ftrylockfile") {
1992 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1993 return;
1994 setDoesNotThrow(F);
1995 setDoesNotCapture(F, 1);
1996 } else if (Name == "ferror") {
1997 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1998 return;
1999 setDoesNotThrow(F);
2000 setDoesNotCapture(F, 1);
2001 setOnlyReadsMemory(F);
2002 } else if (Name == "fputc" ||
2003 Name == "fstat" ||
2004 Name == "frexp" ||
2005 Name == "frexpf" ||
2006 Name == "frexpl" ||
2007 Name == "fstatvfs") {
2008 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2009 return;
2010 setDoesNotThrow(F);
2011 setDoesNotCapture(F, 2);
2012 } else if (Name == "fgets") {
2013 if (FTy->getNumParams() != 3 ||
2014 !FTy->getParamType(0)->isPointerTy() ||
2015 !FTy->getParamType(2)->isPointerTy())
2016 return;
2017 setDoesNotThrow(F);
2018 setDoesNotCapture(F, 3);
2019 } else if (Name == "fread" ||
2020 Name == "fwrite") {
2021 if (FTy->getNumParams() != 4 ||
2022 !FTy->getParamType(0)->isPointerTy() ||
2023 !FTy->getParamType(3)->isPointerTy())
2024 return;
2025 setDoesNotThrow(F);
2026 setDoesNotCapture(F, 1);
2027 setDoesNotCapture(F, 4);
2028 } else if (Name == "fputs" ||
2029 Name == "fscanf" ||
2030 Name == "fprintf" ||
2031 Name == "fgetpos") {
2032 if (FTy->getNumParams() < 2 ||
2033 !FTy->getParamType(0)->isPointerTy() ||
2034 !FTy->getParamType(1)->isPointerTy())
2035 return;
2036 setDoesNotThrow(F);
2037 setDoesNotCapture(F, 1);
2038 setDoesNotCapture(F, 2);
2039 }
2040 break;
2041 case 'g':
2042 if (Name == "getc" ||
2043 Name == "getlogin_r" ||
2044 Name == "getc_unlocked") {
2045 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2046 return;
2047 setDoesNotThrow(F);
2048 setDoesNotCapture(F, 1);
2049 } else if (Name == "getenv") {
2050 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2051 return;
2052 setDoesNotThrow(F);
2053 setOnlyReadsMemory(F);
2054 setDoesNotCapture(F, 1);
2055 } else if (Name == "gets" ||
2056 Name == "getchar") {
2057 setDoesNotThrow(F);
2058 } else if (Name == "getitimer") {
2059 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2060 return;
2061 setDoesNotThrow(F);
2062 setDoesNotCapture(F, 2);
2063 } else if (Name == "getpwnam") {
2064 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2065 return;
2066 setDoesNotThrow(F);
2067 setDoesNotCapture(F, 1);
2068 }
2069 break;
2070 case 'u':
2071 if (Name == "ungetc") {
2072 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2073 return;
2074 setDoesNotThrow(F);
2075 setDoesNotCapture(F, 2);
2076 } else if (Name == "uname" ||
2077 Name == "unlink" ||
2078 Name == "unsetenv") {
2079 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2080 return;
2081 setDoesNotThrow(F);
2082 setDoesNotCapture(F, 1);
2083 } else if (Name == "utime" ||
2084 Name == "utimes") {
2085 if (FTy->getNumParams() != 2 ||
2086 !FTy->getParamType(0)->isPointerTy() ||
2087 !FTy->getParamType(1)->isPointerTy())
2088 return;
2089 setDoesNotThrow(F);
2090 setDoesNotCapture(F, 1);
2091 setDoesNotCapture(F, 2);
2092 }
2093 break;
2094 case 'p':
2095 if (Name == "putc") {
2096 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2097 return;
2098 setDoesNotThrow(F);
2099 setDoesNotCapture(F, 2);
2100 } else if (Name == "puts" ||
2101 Name == "printf" ||
2102 Name == "perror") {
2103 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2104 return;
2105 setDoesNotThrow(F);
2106 setDoesNotCapture(F, 1);
2107 } else if (Name == "pread" ||
2108 Name == "pwrite") {
2109 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2110 return;
2111 // May throw; these are valid pthread cancellation points.
2112 setDoesNotCapture(F, 2);
2113 } else if (Name == "putchar") {
2114 setDoesNotThrow(F);
2115 } else if (Name == "popen") {
2116 if (FTy->getNumParams() != 2 ||
2117 !FTy->getReturnType()->isPointerTy() ||
2118 !FTy->getParamType(0)->isPointerTy() ||
2119 !FTy->getParamType(1)->isPointerTy())
2120 return;
2121 setDoesNotThrow(F);
2122 setDoesNotAlias(F, 0);
2123 setDoesNotCapture(F, 1);
2124 setDoesNotCapture(F, 2);
2125 } else if (Name == "pclose") {
2126 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2127 return;
2128 setDoesNotThrow(F);
2129 setDoesNotCapture(F, 1);
2130 }
2131 break;
2132 case 'v':
2133 if (Name == "vscanf") {
2134 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2135 return;
2136 setDoesNotThrow(F);
2137 setDoesNotCapture(F, 1);
2138 } else if (Name == "vsscanf" ||
2139 Name == "vfscanf") {
2140 if (FTy->getNumParams() != 3 ||
2141 !FTy->getParamType(1)->isPointerTy() ||
2142 !FTy->getParamType(2)->isPointerTy())
2143 return;
2144 setDoesNotThrow(F);
2145 setDoesNotCapture(F, 1);
2146 setDoesNotCapture(F, 2);
2147 } else if (Name == "valloc") {
2148 if (!FTy->getReturnType()->isPointerTy())
2149 return;
2150 setDoesNotThrow(F);
2151 setDoesNotAlias(F, 0);
2152 } else if (Name == "vprintf") {
2153 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2154 return;
2155 setDoesNotThrow(F);
2156 setDoesNotCapture(F, 1);
2157 } else if (Name == "vfprintf" ||
2158 Name == "vsprintf") {
2159 if (FTy->getNumParams() != 3 ||
2160 !FTy->getParamType(0)->isPointerTy() ||
2161 !FTy->getParamType(1)->isPointerTy())
2162 return;
2163 setDoesNotThrow(F);
2164 setDoesNotCapture(F, 1);
2165 setDoesNotCapture(F, 2);
2166 } else if (Name == "vsnprintf") {
2167 if (FTy->getNumParams() != 4 ||
2168 !FTy->getParamType(0)->isPointerTy() ||
2169 !FTy->getParamType(2)->isPointerTy())
2170 return;
2171 setDoesNotThrow(F);
2172 setDoesNotCapture(F, 1);
2173 setDoesNotCapture(F, 3);
2174 }
2175 break;
2176 case 'o':
2177 if (Name == "open") {
2178 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2179 return;
2180 // May throw; "open" is a valid pthread cancellation point.
2181 setDoesNotCapture(F, 1);
2182 } else if (Name == "opendir") {
2183 if (FTy->getNumParams() != 1 ||
2184 !FTy->getReturnType()->isPointerTy() ||
2185 !FTy->getParamType(0)->isPointerTy())
2186 return;
2187 setDoesNotThrow(F);
2188 setDoesNotAlias(F, 0);
2189 setDoesNotCapture(F, 1);
2190 }
2191 break;
2192 case 't':
2193 if (Name == "tmpfile") {
2194 if (!FTy->getReturnType()->isPointerTy())
2195 return;
2196 setDoesNotThrow(F);
2197 setDoesNotAlias(F, 0);
2198 } else if (Name == "times") {
2199 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2200 return;
2201 setDoesNotThrow(F);
2202 setDoesNotCapture(F, 1);
2203 }
2204 break;
2205 case 'h':
2206 if (Name == "htonl" ||
2207 Name == "htons") {
2208 setDoesNotThrow(F);
2209 setDoesNotAccessMemory(F);
2210 }
2211 break;
2212 case 'n':
2213 if (Name == "ntohl" ||
2214 Name == "ntohs") {
2215 setDoesNotThrow(F);
2216 setDoesNotAccessMemory(F);
2217 }
2218 break;
2219 case 'l':
2220 if (Name == "lstat") {
2221 if (FTy->getNumParams() != 2 ||
2222 !FTy->getParamType(0)->isPointerTy() ||
2223 !FTy->getParamType(1)->isPointerTy())
2224 return;
2225 setDoesNotThrow(F);
2226 setDoesNotCapture(F, 1);
2227 setDoesNotCapture(F, 2);
2228 } else if (Name == "lchown") {
2229 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2230 return;
2231 setDoesNotThrow(F);
2232 setDoesNotCapture(F, 1);
2233 }
2234 break;
2235 case 'q':
2236 if (Name == "qsort") {
2237 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2238 return;
2239 // May throw; places call through function pointer.
2240 setDoesNotCapture(F, 4);
2241 }
2242 break;
2243 case '_':
2244 if (Name == "__strdup" ||
2245 Name == "__strndup") {
2246 if (FTy->getNumParams() < 1 ||
2247 !FTy->getReturnType()->isPointerTy() ||
2248 !FTy->getParamType(0)->isPointerTy())
2249 return;
2250 setDoesNotThrow(F);
2251 setDoesNotAlias(F, 0);
2252 setDoesNotCapture(F, 1);
2253 } else if (Name == "__strtok_r") {
2254 if (FTy->getNumParams() != 3 ||
2255 !FTy->getParamType(1)->isPointerTy())
2256 return;
2257 setDoesNotThrow(F);
2258 setDoesNotCapture(F, 2);
2259 } else if (Name == "_IO_getc") {
2260 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2261 return;
2262 setDoesNotThrow(F);
2263 setDoesNotCapture(F, 1);
2264 } else if (Name == "_IO_putc") {
2265 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2266 return;
2267 setDoesNotThrow(F);
2268 setDoesNotCapture(F, 2);
2269 }
2270 break;
2271 case 1:
2272 if (Name == "\1__isoc99_scanf") {
2273 if (FTy->getNumParams() < 1 ||
2274 !FTy->getParamType(0)->isPointerTy())
2275 return;
2276 setDoesNotThrow(F);
2277 setDoesNotCapture(F, 1);
2278 } else if (Name == "\1stat64" ||
2279 Name == "\1lstat64" ||
2280 Name == "\1statvfs64" ||
2281 Name == "\1__isoc99_sscanf") {
2282 if (FTy->getNumParams() < 1 ||
2283 !FTy->getParamType(0)->isPointerTy() ||
2284 !FTy->getParamType(1)->isPointerTy())
2285 return;
2286 setDoesNotThrow(F);
2287 setDoesNotCapture(F, 1);
2288 setDoesNotCapture(F, 2);
2289 } else if (Name == "\1fopen64") {
2290 if (FTy->getNumParams() != 2 ||
2291 !FTy->getReturnType()->isPointerTy() ||
2292 !FTy->getParamType(0)->isPointerTy() ||
2293 !FTy->getParamType(1)->isPointerTy())
2294 return;
2295 setDoesNotThrow(F);
2296 setDoesNotAlias(F, 0);
2297 setDoesNotCapture(F, 1);
2298 setDoesNotCapture(F, 2);
2299 } else if (Name == "\1fseeko64" ||
2300 Name == "\1ftello64") {
2301 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2302 return;
2303 setDoesNotThrow(F);
2304 setDoesNotCapture(F, 1);
2305 } else if (Name == "\1tmpfile64") {
2306 if (!FTy->getReturnType()->isPointerTy())
2307 return;
2308 setDoesNotThrow(F);
2309 setDoesNotAlias(F, 0);
2310 } else if (Name == "\1fstat64" ||
2311 Name == "\1fstatvfs64") {
2312 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2313 return;
2314 setDoesNotThrow(F);
2315 setDoesNotCapture(F, 2);
2316 } else if (Name == "\1open64") {
2317 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2318 return;
2319 // May throw; "open" is a valid pthread cancellation point.
2320 setDoesNotCapture(F, 1);
2321 }
2322 break;
2323 }
2324}
2325
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002326/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002327///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002328bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002329 Modified = false;
2330 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2331 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002332 if (F.isDeclaration() && F.hasName())
2333 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002334 }
2335 return Modified;
2336}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002337
2338// TODO:
2339// Additional cases that we need to add to this file:
2340//
2341// cbrt:
2342// * cbrt(expN(X)) -> expN(x/3)
2343// * cbrt(sqrt(x)) -> pow(x,1/6)
2344// * cbrt(sqrt(x)) -> pow(x,1/9)
2345//
2346// cos, cosf, cosl:
2347// * cos(-x) -> cos(x)
2348//
2349// exp, expf, expl:
2350// * exp(log(x)) -> x
2351//
2352// log, logf, logl:
2353// * log(exp(x)) -> x
2354// * log(x**y) -> y*log(x)
2355// * log(exp(y)) -> y*log(e)
2356// * log(exp2(y)) -> y*log(2)
2357// * log(exp10(y)) -> y*log(10)
2358// * log(sqrt(x)) -> 0.5*log(x)
2359// * log(pow(x,y)) -> y*log(x)
2360//
2361// lround, lroundf, lroundl:
2362// * lround(cnst) -> cnst'
2363//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002364// pow, powf, powl:
2365// * pow(exp(x),y) -> exp(x*y)
2366// * pow(sqrt(x),y) -> pow(x,y*0.5)
2367// * pow(pow(x,y),z)-> pow(x,y*z)
2368//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002369// round, roundf, roundl:
2370// * round(cnst) -> cnst'
2371//
2372// signbit:
2373// * signbit(cnst) -> cnst'
2374// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2375//
2376// sqrt, sqrtf, sqrtl:
2377// * sqrt(expN(x)) -> expN(x*0.5)
2378// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2379// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2380//
2381// stpcpy:
2382// * stpcpy(str, "literal") ->
2383// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002384//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002385// tan, tanf, tanl:
2386// * tan(atan(x)) -> x
2387//
2388// trunc, truncf, truncl:
2389// * trunc(cnst) -> cnst'
2390//
2391//