blob: f3184ecc860103d75177daae813a23f4547def7f [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
Eric Christopherb6174e32010-03-05 22:25:30 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000021#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000022#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000026#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000027#include "llvm/Target/TargetData.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000028#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000029#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000032#include "llvm/ADT/STLExtras.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000033#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattnerafbf4832011-02-24 07:16:14 +000035#include "llvm/Config/config.h" // FIXME: Shouldn't depend on host!
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000036using namespace llvm;
37
38STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000039STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000040
41//===----------------------------------------------------------------------===//
42// Optimizer Base Class
43//===----------------------------------------------------------------------===//
44
45/// This class is the abstract base class for the set of optimizations that
46/// corresponds to one library call.
47namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000049protected:
50 Function *Caller;
51 const TargetData *TD;
Richard Osborne36498242011-03-03 13:17:51 +000052 const TargetLibraryInfo *TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000053 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000054public:
Evan Chengeb8c6452010-03-24 20:19:04 +000055 LibCallOptimization() { }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000056 virtual ~LibCallOptimization() {}
57
58 /// CallOptimizer - This pure virtual method is implemented by base classes to
59 /// do various optimizations. If this returns null then no transformation was
60 /// performed. If it returns CI, then it transformed the call and CI is to be
61 /// deleted. If it returns something else, replace CI with the new value and
62 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000063 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000064 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000065
Richard Osborne36498242011-03-03 13:17:51 +000066 Value *OptimizeCall(CallInst *CI, const TargetData *TD,
67 const TargetLibraryInfo *TLI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000068 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000069 this->TD = TD;
Richard Osborne36498242011-03-03 13:17:51 +000070 this->TLI = TLI;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000071 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000072 Context = &CI->getCalledFunction()->getContext();
Rafael Espindolae96af562010-06-16 19:34:01 +000073
74 // We never change the calling convention.
75 if (CI->getCallingConv() != llvm::CallingConv::C)
76 return NULL;
77
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000078 return CallOptimizer(CI->getCalledFunction(), CI, B);
79 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000080};
81} // End anonymous namespace.
82
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083
84//===----------------------------------------------------------------------===//
85// Helper Functions
86//===----------------------------------------------------------------------===//
87
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000088/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +000089/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000090static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
91 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
92 UI != E; ++UI) {
93 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
94 if (IC->isEquality())
95 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
96 if (C->isNullValue())
97 continue;
98 // Unknown instruction.
99 return false;
100 }
101 return true;
102}
Richard Osborne36498242011-03-03 13:17:51 +0000103
104static bool CallHasFloatingPointArgument(const CallInst *CI) {
105 for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
106 it != e; ++it) {
107 if ((*it)->getType()->isFloatingPointTy())
108 return true;
109 }
110 return false;
111}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112
Benjamin Kramer386e9182010-06-15 21:34:25 +0000113/// IsOnlyUsedInEqualityComparison - Return true if it is only used in equality
114/// comparisons with With.
115static bool IsOnlyUsedInEqualityComparison(Value *V, Value *With) {
116 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
117 UI != E; ++UI) {
118 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
119 if (IC->isEquality() && IC->getOperand(1) == With)
120 continue;
121 // Unknown instruction.
122 return false;
123 }
124 return true;
125}
126
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000127//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128// String and Memory LibCall Optimizations
129//===----------------------------------------------------------------------===//
130
131//===---------------------------------------===//
132// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000133namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000134struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000136 // Verify the "strcat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000137 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000138 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000139 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000140 FT->getParamType(0) != FT->getReturnType() ||
141 FT->getParamType(1) != FT->getReturnType())
142 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000143
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000145 Value *Dst = CI->getArgOperand(0);
146 Value *Src = CI->getArgOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000147
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148 // See if we can get the length of the input string.
149 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000150 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000151 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000152
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000153 // Handle the simple, do-nothing case: strcat(x, "") -> x
154 if (Len == 0)
155 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000156
157 // These optimizations require TargetData.
158 if (!TD) return 0;
159
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000160 EmitStrLenMemCpy(Src, Dst, Len, B);
161 return Dst;
162 }
163
164 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000165 // We need to find the end of the destination string. That's where the
166 // memory is to be moved to. We just generate a call to strlen.
Eric Christopherb6174e32010-03-05 22:25:30 +0000167 Value *DstLen = EmitStrLen(Dst, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +0000168
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000169 // Now that we have the destination's length, we must index into the
170 // destination's pointer to get the actual memcpy destination (end of
171 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000172 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000173
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000174 // We have enough information to now generate the memcpy call to do the
175 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000176 B.CreateMemCpy(CpyDst, Src,
177 ConstantInt::get(TD->getIntPtrType(*Context), Len + 1), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000178 }
179};
180
181//===---------------------------------------===//
182// 'strncat' Optimizations
183
Chris Lattner3e8b6632009-09-02 06:11:42 +0000184struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000185 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
186 // Verify the "strncat" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000187 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000188 if (FT->getNumParams() != 3 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000189 FT->getReturnType() != B.getInt8PtrTy() ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000190 FT->getParamType(0) != FT->getReturnType() ||
191 FT->getParamType(1) != FT->getReturnType() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000192 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000193 return 0;
194
195 // Extract some information from the instruction
Gabor Greifaee5dc12010-06-24 10:42:46 +0000196 Value *Dst = CI->getArgOperand(0);
197 Value *Src = CI->getArgOperand(1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000198 uint64_t Len;
199
200 // We don't do anything if length is not constant
Gabor Greifaee5dc12010-06-24 10:42:46 +0000201 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000202 Len = LengthArg->getZExtValue();
203 else
204 return 0;
205
206 // See if we can get the length of the input string.
207 uint64_t SrcLen = GetStringLength(Src);
208 if (SrcLen == 0) return 0;
209 --SrcLen; // Unbias length.
210
211 // Handle the simple, do-nothing cases:
212 // strncat(x, "", c) -> x
213 // strncat(x, c, 0) -> x
214 if (SrcLen == 0 || Len == 0) return Dst;
215
Dan Gohmanf14d9192009-08-18 00:48:13 +0000216 // These optimizations require TargetData.
217 if (!TD) return 0;
218
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000219 // We don't optimize this case
220 if (Len < SrcLen) return 0;
221
222 // strncat(x, s, c) -> strcat(x, s)
223 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000224 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000225 return Dst;
226 }
227};
228
229//===---------------------------------------===//
230// 'strchr' Optimizations
231
Chris Lattner3e8b6632009-09-02 06:11:42 +0000232struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000233 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234 // Verify the "strchr" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000235 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000236 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000237 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000238 FT->getParamType(0) != FT->getReturnType() ||
239 !FT->getParamType(1)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000240 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000241
Gabor Greifaee5dc12010-06-24 10:42:46 +0000242 Value *SrcStr = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000243
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000244 // If the second operand is non-constant, see if we can compute the length
245 // of the input string and turn this into memchr.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000246 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000247 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000248 // These optimizations require TargetData.
249 if (!TD) return 0;
250
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000251 uint64_t Len = GetStringLength(SrcStr);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000252 if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000253 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000254
Gabor Greifaee5dc12010-06-24 10:42:46 +0000255 return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
Eric Christopherb6174e32010-03-05 22:25:30 +0000256 ConstantInt::get(TD->getIntPtrType(*Context), Len),
257 B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258 }
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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000285 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000286 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000287 FT->getReturnType() != B.getInt8PtrTy() ||
Benjamin Kramer4c756792010-09-30 11:21:59 +0000288 FT->getParamType(0) != FT->getReturnType() ||
289 !FT->getParamType(1)->isIntegerTy(32))
Benjamin Kramer06f25cf2010-09-29 21:50:51 +0000290 return 0;
291
292 Value *SrcStr = CI->getArgOperand(0);
293 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
294
295 // Cannot fold anything if we're not looking for a constant.
296 if (!CharC)
297 return 0;
298
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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000327 if (FT->getNumParams() != 2 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000328 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000329 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000330 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000332
Gabor Greifaee5dc12010-06-24 10:42:46 +0000333 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000334 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000335 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000336
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
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000341 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000342 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000343 return ConstantInt::get(CI->getType(),
Eli Friedman79286082011-10-05 22:27:16 +0000344 StringRef(Str1).compare(Str2));
345
346 if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
347 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
348 CI->getType()));
349
350 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
351 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Nick Lewycky13a09e22008-12-21 00:19:21 +0000352
353 // strcmp(P, "x") -> memcmp(P, "x", 2)
354 uint64_t Len1 = GetStringLength(Str1P);
355 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000356 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000357 // These optimizations require TargetData.
358 if (!TD) return 0;
359
Nick Lewycky13a09e22008-12-21 00:19:21 +0000360 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000361 ConstantInt::get(TD->getIntPtrType(*Context),
Eric Christopherb6174e32010-03-05 22:25:30 +0000362 std::min(Len1, Len2)), B, TD);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000363 }
364
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000365 return 0;
366 }
367};
368
369//===---------------------------------------===//
370// 'strncmp' Optimizations
371
Chris Lattner3e8b6632009-09-02 06:11:42 +0000372struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000374 // Verify the "strncmp" function prototype.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000375 FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000376 if (FT->getNumParams() != 3 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000377 !FT->getReturnType()->isIntegerTy(32) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000378 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000379 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000380 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000381 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000382
Gabor Greifaee5dc12010-06-24 10:42:46 +0000383 Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000384 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000385 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000386
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000387 // Get the length argument if it is constant.
388 uint64_t Length;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000389 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000390 Length = LengthArg->getZExtValue();
391 else
392 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000393
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000394 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000395 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000396
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000397 if (TD && Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000398 return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
Benjamin Kramerea9ca022010-06-16 10:30:29 +0000399
Bill Wendling0582ae92009-03-13 04:39:26 +0000400 std::string Str1, Str2;
401 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
402 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000403
Eli Friedman79286082011-10-05 22:27:16 +0000404 // strncmp(x, y) -> cnst (if both x and y are constant strings)
405 if (HasStr1 && HasStr2) {
406 StringRef SubStr1 = StringRef(Str1).substr(0, Length);
407 StringRef SubStr2 = StringRef(Str2).substr(0, Length);
408 return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
409 }
410
411 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
412 return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
413 CI->getType()));
Eric Christopher37c8b862009-10-07 21:14:25 +0000414
Bill Wendling0582ae92009-03-13 04:39:26 +0000415 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000416 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000417
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000418 return 0;
419 }
420};
421
422
423//===---------------------------------------===//
424// 'strcpy' Optimizations
425
Chris Lattner3e8b6632009-09-02 06:11:42 +0000426struct StrCpyOpt : public LibCallOptimization {
Evan Chengeb8c6452010-03-24 20:19:04 +0000427 bool OptChkCall; // True if it's optimizing a __strcpy_chk libcall.
428
429 StrCpyOpt(bool c) : OptChkCall(c) {}
430
Eric Christopher7a61d702008-08-08 19:39:37 +0000431 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000432 // Verify the "strcpy" function prototype.
Evan Cheng0289b412010-03-23 15:48:04 +0000433 unsigned NumParams = OptChkCall ? 3 : 2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000434 FunctionType *FT = Callee->getFunctionType();
Evan Cheng0289b412010-03-23 15:48:04 +0000435 if (FT->getNumParams() != NumParams ||
436 FT->getReturnType() != FT->getParamType(0) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000438 FT->getParamType(0) != B.getInt8PtrTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000439 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000440
Gabor Greifaee5dc12010-06-24 10:42:46 +0000441 Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000442 if (Dst == Src) // strcpy(x,x) -> x
443 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000444
Dan Gohmanf14d9192009-08-18 00:48:13 +0000445 // These optimizations require TargetData.
446 if (!TD) return 0;
447
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000448 // See if we can get the length of the input string.
449 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000450 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000451
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000452 // We have enough information to now generate the memcpy call to do the
453 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Evan Cheng0289b412010-03-23 15:48:04 +0000454 if (OptChkCall)
455 EmitMemCpyChk(Dst, Src,
456 ConstantInt::get(TD->getIntPtrType(*Context), Len),
Gabor Greifaee5dc12010-06-24 10:42:46 +0000457 CI->getArgOperand(2), B, TD);
Evan Cheng0289b412010-03-23 15:48:04 +0000458 else
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000459 B.CreateMemCpy(Dst, Src,
460 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000461 return Dst;
462 }
463};
464
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000465//===---------------------------------------===//
466// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000467
Chris Lattner3e8b6632009-09-02 06:11:42 +0000468struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000470 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000471 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
472 FT->getParamType(0) != FT->getParamType(1) ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000473 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000474 !FT->getParamType(2)->isIntegerTy())
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000475 return 0;
476
Gabor Greifaee5dc12010-06-24 10:42:46 +0000477 Value *Dst = CI->getArgOperand(0);
478 Value *Src = CI->getArgOperand(1);
479 Value *LenOp = CI->getArgOperand(2);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000480
481 // See if we can get the length of the input string.
482 uint64_t SrcLen = GetStringLength(Src);
483 if (SrcLen == 0) return 0;
484 --SrcLen;
485
486 if (SrcLen == 0) {
487 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000488 B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000489 return Dst;
490 }
491
492 uint64_t Len;
493 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
494 Len = LengthArg->getZExtValue();
495 else
496 return 0;
497
498 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
499
Dan Gohmanf14d9192009-08-18 00:48:13 +0000500 // These optimizations require TargetData.
501 if (!TD) return 0;
502
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000503 // Let strncpy handle the zero padding
504 if (Len > SrcLen+1) return 0;
505
506 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000507 B.CreateMemCpy(Dst, Src,
508 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000509
510 return Dst;
511 }
512};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000513
514//===---------------------------------------===//
515// 'strlen' Optimizations
516
Chris Lattner3e8b6632009-09-02 06:11:42 +0000517struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000518 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000519 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000520 if (FT->getNumParams() != 1 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000521 FT->getParamType(0) != B.getInt8PtrTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +0000522 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000523 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000524
Gabor Greifaee5dc12010-06-24 10:42:46 +0000525 Value *Src = CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526
527 // Constant folding: strlen("xyz") -> 3
528 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000529 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000530
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000531 // strlen(x) != 0 --> *x != 0
532 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000533 if (IsOnlyUsedInZeroEqualityComparison(CI))
534 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
535 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000536 }
537};
538
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000539
540//===---------------------------------------===//
541// 'strpbrk' Optimizations
542
543struct StrPBrkOpt : public LibCallOptimization {
544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000545 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000546 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000547 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000548 FT->getParamType(1) != FT->getParamType(0) ||
549 FT->getReturnType() != FT->getParamType(0))
550 return 0;
551
552 std::string S1, S2;
553 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
554 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
555
556 // strpbrk(s, "") -> NULL
557 // strpbrk("", s) -> NULL
558 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
559 return Constant::getNullValue(CI->getType());
560
561 // Constant folding.
562 if (HasS1 && HasS2) {
563 size_t I = S1.find_first_of(S2);
564 if (I == std::string::npos) // No match.
565 return Constant::getNullValue(CI->getType());
566
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000567 return B.CreateGEP(CI->getArgOperand(0), B.getInt64(I), "strpbrk");
Benjamin Kramer05f585e2010-09-29 23:52:12 +0000568 }
569
570 // strpbrk(s, "a") -> strchr(s, 'a')
571 if (TD && HasS2 && S2.size() == 1)
572 return EmitStrChr(CI->getArgOperand(0), S2[0], B, TD);
573
574 return 0;
575 }
576};
577
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000578//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000579// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000580
Chris Lattner3e8b6632009-09-02 06:11:42 +0000581struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000583 FunctionType *FT = Callee->getFunctionType();
Nick Lewycky4c498412009-02-13 15:31:46 +0000584 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000585 !FT->getParamType(0)->isPointerTy() ||
586 !FT->getParamType(1)->isPointerTy())
Nick Lewycky4c498412009-02-13 15:31:46 +0000587 return 0;
588
Gabor Greifaee5dc12010-06-24 10:42:46 +0000589 Value *EndPtr = CI->getArgOperand(1);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000590 if (isa<ConstantPointerNull>(EndPtr)) {
Dan Gohmanc32046e2010-12-17 01:09:43 +0000591 // With a null EndPtr, this function won't capture the main argument.
592 // It would be readonly too, except that it still may write to errno.
Nick Lewycky4c498412009-02-13 15:31:46 +0000593 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000594 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000595
596 return 0;
597 }
598};
599
Chris Lattner24604112009-12-16 09:32:05 +0000600//===---------------------------------------===//
Benjamin Kramer9510a252010-09-30 00:58:35 +0000601// 'strspn' Optimizations
602
603struct StrSpnOpt : public LibCallOptimization {
604 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000606 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000607 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000608 FT->getParamType(1) != FT->getParamType(0) ||
609 !FT->getReturnType()->isIntegerTy())
610 return 0;
611
612 std::string S1, S2;
613 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
614 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
615
616 // strspn(s, "") -> 0
617 // strspn("", s) -> 0
618 if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
619 return Constant::getNullValue(CI->getType());
620
621 // Constant folding.
622 if (HasS1 && HasS2)
623 return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()));
624
625 return 0;
626 }
627};
628
629//===---------------------------------------===//
630// 'strcspn' Optimizations
631
632struct StrCSpnOpt : public LibCallOptimization {
633 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000634 FunctionType *FT = Callee->getFunctionType();
Benjamin Kramer9510a252010-09-30 00:58:35 +0000635 if (FT->getNumParams() != 2 ||
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000636 FT->getParamType(0) != B.getInt8PtrTy() ||
Benjamin Kramer9510a252010-09-30 00:58:35 +0000637 FT->getParamType(1) != FT->getParamType(0) ||
638 !FT->getReturnType()->isIntegerTy())
639 return 0;
640
641 std::string S1, S2;
642 bool HasS1 = GetConstantStringInfo(CI->getArgOperand(0), S1);
643 bool HasS2 = GetConstantStringInfo(CI->getArgOperand(1), S2);
644
645 // strcspn("", s) -> 0
646 if (HasS1 && S1.empty())
647 return Constant::getNullValue(CI->getType());
648
649 // Constant folding.
650 if (HasS1 && HasS2)
651 return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str()));
652
653 // strcspn(s, "") -> strlen(s)
654 if (TD && HasS2 && S2.empty())
655 return EmitStrLen(CI->getArgOperand(0), B, TD);
656
657 return 0;
658 }
659};
660
661//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000662// 'strstr' Optimizations
663
664struct StrStrOpt : public LibCallOptimization {
665 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000666 FunctionType *FT = Callee->getFunctionType();
Chris Lattner24604112009-12-16 09:32:05 +0000667 if (FT->getNumParams() != 2 ||
Duncan Sands1df98592010-02-16 11:11:14 +0000668 !FT->getParamType(0)->isPointerTy() ||
669 !FT->getParamType(1)->isPointerTy() ||
670 !FT->getReturnType()->isPointerTy())
Chris Lattner24604112009-12-16 09:32:05 +0000671 return 0;
672
673 // fold strstr(x, x) -> x.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000674 if (CI->getArgOperand(0) == CI->getArgOperand(1))
675 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000676
Benjamin Kramer386e9182010-06-15 21:34:25 +0000677 // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
Gabor Greif8e1ebff2010-06-30 12:42:43 +0000678 if (TD && IsOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
679 Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, TD);
680 Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
Benjamin Kramer386e9182010-06-15 21:34:25 +0000681 StrLen, B, TD);
682 for (Value::use_iterator UI = CI->use_begin(), UE = CI->use_end();
683 UI != UE; ) {
Gabor Greif96f1d8e2010-07-22 13:36:47 +0000684 ICmpInst *Old = cast<ICmpInst>(*UI++);
Benjamin Kramer386e9182010-06-15 21:34:25 +0000685 Value *Cmp = B.CreateICmp(Old->getPredicate(), StrNCmp,
686 ConstantInt::getNullValue(StrNCmp->getType()),
687 "cmp");
688 Old->replaceAllUsesWith(Cmp);
689 Old->eraseFromParent();
690 }
691 return CI;
692 }
693
Chris Lattner24604112009-12-16 09:32:05 +0000694 // See if either input string is a constant string.
695 std::string SearchStr, ToFindStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +0000696 bool HasStr1 = GetConstantStringInfo(CI->getArgOperand(0), SearchStr);
697 bool HasStr2 = GetConstantStringInfo(CI->getArgOperand(1), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000698
Chris Lattner24604112009-12-16 09:32:05 +0000699 // fold strstr(x, "") -> x.
700 if (HasStr2 && ToFindStr.empty())
Gabor Greifaee5dc12010-06-24 10:42:46 +0000701 return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000702
Chris Lattner24604112009-12-16 09:32:05 +0000703 // If both strings are known, constant fold it.
704 if (HasStr1 && HasStr2) {
705 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000706
Chris Lattner24604112009-12-16 09:32:05 +0000707 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
708 return Constant::getNullValue(CI->getType());
709
710 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +0000711 Value *Result = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner24604112009-12-16 09:32:05 +0000712 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
713 return B.CreateBitCast(Result, CI->getType());
714 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000715
Chris Lattner24604112009-12-16 09:32:05 +0000716 // fold strstr(x, "y") -> strchr(x, 'y').
717 if (HasStr2 && ToFindStr.size() == 1)
Gabor Greifa3997812010-07-22 10:37:47 +0000718 return B.CreateBitCast(EmitStrChr(CI->getArgOperand(0),
719 ToFindStr[0], B, TD), CI->getType());
Chris Lattner24604112009-12-16 09:32:05 +0000720 return 0;
721 }
722};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000723
Nick Lewycky4c498412009-02-13 15:31:46 +0000724
725//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726// 'memcmp' Optimizations
727
Chris Lattner3e8b6632009-09-02 06:11:42 +0000728struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000729 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000730 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +0000731 if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
732 !FT->getParamType(1)->isPointerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000733 !FT->getReturnType()->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000734 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000735
Gabor Greifaee5dc12010-06-24 10:42:46 +0000736 Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000737
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000738 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000739 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000740
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000741 // Make sure we have a constant length.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000742 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000743 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000744 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000745
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000746 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000747 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000748
Benjamin Kramer48aefe12010-05-25 22:53:43 +0000749 // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
750 if (Len == 1) {
751 Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
752 CI->getType(), "lhsv");
753 Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
754 CI->getType(), "rhsv");
Benjamin Kramer1464c1d2010-05-26 09:45:04 +0000755 return B.CreateSub(LHSV, RHSV, "chardiff");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000756 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000757
Benjamin Kramer992a6372009-11-05 17:44:22 +0000758 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
759 std::string LHSStr, RHSStr;
760 if (GetConstantStringInfo(LHS, LHSStr) &&
761 GetConstantStringInfo(RHS, RHSStr)) {
762 // Make sure we're not reading out-of-bounds memory.
763 if (Len > LHSStr.length() || Len > RHSStr.length())
764 return 0;
765 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
766 return ConstantInt::get(CI->getType(), Ret);
767 }
768
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000769 return 0;
770 }
771};
772
773//===---------------------------------------===//
774// 'memcpy' Optimizations
775
Chris Lattner3e8b6632009-09-02 06:11:42 +0000776struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000777 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000778 // These optimizations require TargetData.
779 if (!TD) return 0;
780
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000781 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000782 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000783 !FT->getParamType(0)->isPointerTy() ||
784 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000785 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000786 return 0;
787
788 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000789 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
790 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000791 return CI->getArgOperand(0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000792 }
793};
794
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000795//===---------------------------------------===//
796// 'memmove' Optimizations
797
Chris Lattner3e8b6632009-09-02 06:11:42 +0000798struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000799 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000800 // These optimizations require TargetData.
801 if (!TD) return 0;
802
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000803 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000804 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000805 !FT->getParamType(0)->isPointerTy() ||
806 !FT->getParamType(1)->isPointerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000807 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000808 return 0;
809
810 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000811 B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
812 CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000813 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000814 }
815};
816
817//===---------------------------------------===//
818// 'memset' Optimizations
819
Chris Lattner3e8b6632009-09-02 06:11:42 +0000820struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000821 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000822 // These optimizations require TargetData.
823 if (!TD) return 0;
824
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000825 FunctionType *FT = Callee->getFunctionType();
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000826 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000827 !FT->getParamType(0)->isPointerTy() ||
828 !FT->getParamType(1)->isIntegerTy() ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000829 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000830 return 0;
831
832 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000833 Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
834 B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
Gabor Greifaee5dc12010-06-24 10:42:46 +0000835 return CI->getArgOperand(0);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000836 }
837};
838
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839//===----------------------------------------------------------------------===//
840// Math Library Optimizations
841//===----------------------------------------------------------------------===//
842
843//===---------------------------------------===//
844// 'pow*' Optimizations
845
Chris Lattner3e8b6632009-09-02 06:11:42 +0000846struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000848 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000849 // Just make sure this has 2 arguments of the same FP type, which match the
850 // result type.
851 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
852 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000853 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000854 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000855
Gabor Greifaee5dc12010-06-24 10:42:46 +0000856 Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
858 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
859 return Op1C;
860 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +0000861 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000862 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000863
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000864 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
865 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000866
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000867 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000868 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000869
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000870 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +0000871 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
872 // This is faster than calling pow, and still handles negative zero
873 // and negative infinite correctly.
874 // TODO: In fast-math mode, this could be just sqrt(x).
875 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +0000876 Value *Inf = ConstantFP::getInfinity(CI->getType());
877 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +0000878 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
879 Callee->getAttributes());
880 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
881 Callee->getAttributes());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000882 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
883 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
Dan Gohman79cb8402009-09-25 23:10:17 +0000884 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000885 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000886
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000887 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
888 return Op1;
889 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000890 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000891 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000892 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000893 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000894 return 0;
895 }
896};
897
898//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000899// 'exp2' Optimizations
900
Chris Lattner3e8b6632009-09-02 06:11:42 +0000901struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000902 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000903 FunctionType *FT = Callee->getFunctionType();
Chris Lattnere818f772008-05-02 18:43:35 +0000904 // Just make sure this has 1 argument of FP type, which matches the
905 // result type.
906 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000907 !FT->getParamType(0)->isFloatingPointTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000908 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000909
Gabor Greifaee5dc12010-06-24 10:42:46 +0000910 Value *Op = CI->getArgOperand(0);
Chris Lattnere818f772008-05-02 18:43:35 +0000911 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
912 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
913 Value *LdExpArg = 0;
914 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
915 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000916 LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000917 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
918 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000919 LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
Chris Lattnere818f772008-05-02 18:43:35 +0000920 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000921
Chris Lattnere818f772008-05-02 18:43:35 +0000922 if (LdExpArg) {
923 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000924 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000925 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000926 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +0000927 Name = "ldexp";
928 else
929 Name = "ldexpl";
930
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000931 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000932 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000933 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +0000934
935 Module *M = Caller->getParent();
936 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +0000937 Op->getType(),
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000938 B.getInt32Ty(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000939 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
940 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
941 CI->setCallingConv(F->getCallingConv());
942
943 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +0000944 }
945 return 0;
946 }
947};
Chris Lattnere818f772008-05-02 18:43:35 +0000948
949//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000950// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
951
Chris Lattner3e8b6632009-09-02 06:11:42 +0000952struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000953 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000954 FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000955 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
956 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000957 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000958
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000959 // If this is something like 'floor((double)floatval)', convert to floorf.
Gabor Greifaee5dc12010-06-24 10:42:46 +0000960 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000961 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000962 return 0;
963
964 // floor((double)floatval) -> (double)floorf(floatval)
965 Value *V = Cast->getOperand(0);
Benjamin Kramerb5ccb252011-11-15 19:12:09 +0000966 V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000967 return B.CreateFPExt(V, B.getDoubleTy());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000968 }
969};
970
971//===----------------------------------------------------------------------===//
972// Integer Optimizations
973//===----------------------------------------------------------------------===//
974
975//===---------------------------------------===//
976// 'ffs*' Optimizations
977
Chris Lattner3e8b6632009-09-02 06:11:42 +0000978struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000979 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000980 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000981 // Just make sure this has 2 arguments of the same FP type, which match the
982 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +0000983 if (FT->getNumParams() != 1 ||
Nick Lewycky10d2f4d2010-07-06 03:53:43 +0000984 !FT->getReturnType()->isIntegerTy(32) ||
Duncan Sands1df98592010-02-16 11:11:14 +0000985 !FT->getParamType(0)->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000986 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000987
Gabor Greifaee5dc12010-06-24 10:42:46 +0000988 Value *Op = CI->getArgOperand(0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000989
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000990 // Constant fold.
991 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
992 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +0000993 return Constant::getNullValue(CI->getType());
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +0000994 // ffs(c) -> cttz(c)+1
995 return B.getInt32(CI->getValue().countTrailingZeros() + 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000996 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000997
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000998 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
Jay Foad5fdd6c82011-07-12 14:06:48 +0000999 Type *ArgType = Op->getType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001000 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
Benjamin Kramereb9a85f2011-07-14 17:45:39 +00001001 Intrinsic::cttz, ArgType);
Chandler Carruthccbf1e32011-12-12 04:26:04 +00001002 Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
Benjamin Kramera9390a42011-09-27 20:39:19 +00001003 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
1004 V = B.CreateIntCast(V, B.getInt32Ty(), false);
Eric Christopher37c8b862009-10-07 21:14:25 +00001005
Benjamin Kramera9390a42011-09-27 20:39:19 +00001006 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001007 return B.CreateSelect(Cond, V, B.getInt32(0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001008 }
1009};
1010
1011//===---------------------------------------===//
1012// 'isdigit' Optimizations
1013
Chris Lattner3e8b6632009-09-02 06:11:42 +00001014struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001015 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001016 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001017 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001018 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001019 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001020 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001021
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001022 // isdigit(c) -> (c-'0') <u 10
Gabor Greifaee5dc12010-06-24 10:42:46 +00001023 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001024 Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
1025 Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001026 return B.CreateZExt(Op, CI->getType());
1027 }
1028};
1029
1030//===---------------------------------------===//
1031// 'isascii' Optimizations
1032
Chris Lattner3e8b6632009-09-02 06:11:42 +00001033struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001034 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001035 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001036 // We require integer(i32)
Duncan Sands1df98592010-02-16 11:11:14 +00001037 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001038 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001039 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001040
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001041 // isascii(c) -> c <u 128
Gabor Greifaee5dc12010-06-24 10:42:46 +00001042 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001043 Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001044 return B.CreateZExt(Op, CI->getType());
1045 }
1046};
Eric Christopher37c8b862009-10-07 21:14:25 +00001047
Chris Lattner313f0e62008-06-09 08:26:51 +00001048//===---------------------------------------===//
1049// 'abs', 'labs', 'llabs' Optimizations
1050
Chris Lattner3e8b6632009-09-02 06:11:42 +00001051struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001052 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 FunctionType *FT = Callee->getFunctionType();
Chris Lattner313f0e62008-06-09 08:26:51 +00001054 // We require integer(integer) where the types agree.
Duncan Sands1df98592010-02-16 11:11:14 +00001055 if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
Chris Lattner313f0e62008-06-09 08:26:51 +00001056 FT->getParamType(0) != FT->getReturnType())
1057 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001058
Chris Lattner313f0e62008-06-09 08:26:51 +00001059 // abs(x) -> x >s -1 ? x : -x
Gabor Greifaee5dc12010-06-24 10:42:46 +00001060 Value *Op = CI->getArgOperand(0);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001061 Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001062 "ispos");
1063 Value *Neg = B.CreateNeg(Op, "neg");
1064 return B.CreateSelect(Pos, Op, Neg);
1065 }
1066};
Eric Christopher37c8b862009-10-07 21:14:25 +00001067
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001068
1069//===---------------------------------------===//
1070// 'toascii' Optimizations
1071
Chris Lattner3e8b6632009-09-02 06:11:42 +00001072struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001073 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001074 FunctionType *FT = Callee->getFunctionType();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001075 // We require i32(i32)
1076 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001077 !FT->getParamType(0)->isIntegerTy(32))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001078 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001079
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001080 // isascii(c) -> c & 0x7f
Gabor Greifaee5dc12010-06-24 10:42:46 +00001081 return B.CreateAnd(CI->getArgOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001082 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001083 }
1084};
1085
1086//===----------------------------------------------------------------------===//
1087// Formatting and IO Optimizations
1088//===----------------------------------------------------------------------===//
1089
1090//===---------------------------------------===//
1091// 'printf' Optimizations
1092
Chris Lattner3e8b6632009-09-02 06:11:42 +00001093struct PrintFOpt : public LibCallOptimization {
Richard Osborne36498242011-03-03 13:17:51 +00001094 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1095 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001096 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001097 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001098 if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001099 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001100
1101 // Empty format string -> noop.
1102 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001103 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001104 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001105
Daniel Dunbard02be242011-02-12 18:19:57 +00001106 // Do not do any of the following transformations if the printf return value
1107 // is used, in general the printf return value is not compatible with either
1108 // putchar() or puts().
1109 if (!CI->use_empty())
1110 return 0;
1111
1112 // printf("x") -> putchar('x'), even for '%'.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001113 if (FormatStr.size() == 1) {
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001114 Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD);
Chris Lattner74965f22009-11-09 04:57:04 +00001115 if (CI->use_empty()) return CI;
1116 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001117 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001118
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001119 // printf("foo\n") --> puts("foo")
1120 if (FormatStr[FormatStr.size()-1] == '\n' &&
1121 FormatStr.find('%') == std::string::npos) { // no format characters.
1122 // Create a string literal with no \n on it. We expect the constant merge
1123 // pass to be run after this pass, to merge duplicate strings.
1124 FormatStr.erase(FormatStr.end()-1);
Benjamin Kramer59e43bd2011-10-29 19:43:31 +00001125 Value *GV = B.CreateGlobalString(FormatStr, "str");
1126 EmitPutS(GV, B, TD);
Eric Christopher37c8b862009-10-07 21:14:25 +00001127 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001128 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001129 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001130
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001131 // Optimize specific format strings.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001132 // printf("%c", chr) --> putchar(chr)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001133 if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
Gabor Greifaee5dc12010-06-24 10:42:46 +00001134 CI->getArgOperand(1)->getType()->isIntegerTy()) {
1135 Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001136
Chris Lattner74965f22009-11-09 04:57:04 +00001137 if (CI->use_empty()) return CI;
1138 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001139 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001140
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001141 // printf("%s\n", str) --> puts(str)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001142 if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
Daniel Dunbard02be242011-02-12 18:19:57 +00001143 CI->getArgOperand(1)->getType()->isPointerTy()) {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001144 EmitPutS(CI->getArgOperand(1), B, TD);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001145 return CI;
1146 }
1147 return 0;
1148 }
Richard Osborne36498242011-03-03 13:17:51 +00001149
1150 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1151 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001152 FunctionType *FT = Callee->getFunctionType();
Richard Osborne36498242011-03-03 13:17:51 +00001153 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1154 !(FT->getReturnType()->isIntegerTy() ||
1155 FT->getReturnType()->isVoidTy()))
1156 return 0;
1157
1158 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1159 return V;
1160 }
1161
1162 // printf(format, ...) -> iprintf(format, ...) if no floating point
1163 // arguments.
1164 if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
1165 Module *M = B.GetInsertBlock()->getParent()->getParent();
1166 Constant *IPrintFFn =
1167 M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
1168 CallInst *New = cast<CallInst>(CI->clone());
1169 New->setCalledFunction(IPrintFFn);
1170 B.Insert(New);
1171 return New;
1172 }
1173 return 0;
1174 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001175};
1176
1177//===---------------------------------------===//
1178// 'sprintf' Optimizations
1179
Chris Lattner3e8b6632009-09-02 06:11:42 +00001180struct SPrintFOpt : public LibCallOptimization {
Richard Osborne419454a2011-03-03 14:09:28 +00001181 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1182 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001183 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001184 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001185 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001186 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001187
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001188 // If we just have a format string (nothing else crazy) transform it.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001189 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001190 // Make sure there's no % in the constant array. We could try to handle
1191 // %% -> % in the future if we cared.
1192 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1193 if (FormatStr[i] == '%')
1194 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001195
1196 // These optimizations require TargetData.
1197 if (!TD) return 0;
1198
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001199 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001200 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
1201 ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
1202 FormatStr.size() + 1), 1); // nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001203 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001204 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001205
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001206 // The remaining optimizations require the format string to be "%s" or "%c"
1207 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001208 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1209 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001211
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001212 // Decode the second character of the format string.
1213 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001214 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Gabor Greifaee5dc12010-06-24 10:42:46 +00001215 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001216 Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
Gabor Greifaee5dc12010-06-24 10:42:46 +00001217 Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001218 B.CreateStore(V, Ptr);
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001219 Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
1220 B.CreateStore(B.getInt8(0), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001221
Owen Andersoneed707b2009-07-24 23:12:02 +00001222 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001223 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001224
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001225 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001226 // These optimizations require TargetData.
1227 if (!TD) return 0;
1228
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001230 if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001231
Gabor Greifaee5dc12010-06-24 10:42:46 +00001232 Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001233 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001234 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001235 "leninc");
Benjamin Kramera1bf4ca2010-12-27 00:16:46 +00001236 B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001237
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001238 // The sprintf result is the unincremented number of bytes in the string.
1239 return B.CreateIntCast(Len, CI->getType(), false);
1240 }
1241 return 0;
1242 }
Richard Osborne419454a2011-03-03 14:09:28 +00001243
1244 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1245 // Require two fixed pointer arguments and an integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001246 FunctionType *FT = Callee->getFunctionType();
Richard Osborne419454a2011-03-03 14:09:28 +00001247 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1248 !FT->getParamType(1)->isPointerTy() ||
1249 !FT->getReturnType()->isIntegerTy())
1250 return 0;
1251
1252 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1253 return V;
1254 }
1255
Richard Osborneea2578c2011-03-03 14:21:22 +00001256 // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
Richard Osborne419454a2011-03-03 14:09:28 +00001257 // point arguments.
1258 if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
1259 Module *M = B.GetInsertBlock()->getParent()->getParent();
1260 Constant *SIPrintFFn =
1261 M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
1262 CallInst *New = cast<CallInst>(CI->clone());
1263 New->setCalledFunction(SIPrintFFn);
1264 B.Insert(New);
1265 return New;
1266 }
1267 return 0;
1268 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001269};
1270
1271//===---------------------------------------===//
1272// 'fwrite' Optimizations
1273
Chris Lattner3e8b6632009-09-02 06:11:42 +00001274struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001275 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001276 // Require a pointer, an integer, an integer, a pointer, returning integer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001277 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001278 if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1279 !FT->getParamType(1)->isIntegerTy() ||
1280 !FT->getParamType(2)->isIntegerTy() ||
1281 !FT->getParamType(3)->isPointerTy() ||
1282 !FT->getReturnType()->isIntegerTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001283 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001284
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001285 // Get the element size and count.
Gabor Greifaee5dc12010-06-24 10:42:46 +00001286 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
1287 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001288 if (!SizeC || !CountC) return 0;
1289 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001290
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001291 // If this is writing zero records, remove the call (it's a noop).
1292 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001293 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001294
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001295 // If this is writing one byte, turn it into fputc.
Joerg Sonnenberger127a6692011-12-12 20:18:31 +00001296 // This optimisation is only valid, if the return value is unused.
1297 if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001298 Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
1299 EmitFPutC(Char, CI->getArgOperand(3), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001300 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001301 }
1302
1303 return 0;
1304 }
1305};
1306
1307//===---------------------------------------===//
1308// 'fputs' Optimizations
1309
Chris Lattner3e8b6632009-09-02 06:11:42 +00001310struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001311 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001312 // These optimizations require TargetData.
1313 if (!TD) return 0;
1314
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001315 // Require two pointers. Also, we can't optimize if return value is used.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001316 FunctionType *FT = Callee->getFunctionType();
Duncan Sands1df98592010-02-16 11:11:14 +00001317 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1318 !FT->getParamType(1)->isPointerTy() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001319 !CI->use_empty())
1320 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001321
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001322 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
Gabor Greifaee5dc12010-06-24 10:42:46 +00001323 uint64_t Len = GetStringLength(CI->getArgOperand(0));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001324 if (!Len) return 0;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001325 EmitFWrite(CI->getArgOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00001326 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Eli Friedman9d434db2011-11-17 01:27:36 +00001327 CI->getArgOperand(1), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001328 return CI; // Known to have no uses (see above).
1329 }
1330};
1331
1332//===---------------------------------------===//
1333// 'fprintf' Optimizations
1334
Chris Lattner3e8b6632009-09-02 06:11:42 +00001335struct FPrintFOpt : public LibCallOptimization {
Richard Osborne022708f2011-03-03 14:20:22 +00001336 Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
1337 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001338 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001339 std::string FormatStr;
Gabor Greifaee5dc12010-06-24 10:42:46 +00001340 if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
Bill Wendling0582ae92009-03-13 04:39:26 +00001341 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001342
1343 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001344 if (CI->getNumArgOperands() == 2) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001345 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1346 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001347 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001348
1349 // These optimizations require TargetData.
1350 if (!TD) return 0;
1351
Gabor Greifaee5dc12010-06-24 10:42:46 +00001352 EmitFWrite(CI->getArgOperand(1),
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001353 ConstantInt::get(TD->getIntPtrType(*Context),
1354 FormatStr.size()),
Eli Friedman9d434db2011-11-17 01:27:36 +00001355 CI->getArgOperand(0), B, TD, TLI);
Owen Andersoneed707b2009-07-24 23:12:02 +00001356 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001357 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001358
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001359 // The remaining optimizations require the format string to be "%s" or "%c"
1360 // and have an extra operand.
Gabor Greif8e1ebff2010-06-30 12:42:43 +00001361 if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
1362 CI->getNumArgOperands() < 3)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001363 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001364
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001365 // Decode the second character of the format string.
1366 if (FormatStr[1] == 'c') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001367 // fprintf(F, "%c", chr) --> fputc(chr, F)
1368 if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
1369 EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
Owen Andersoneed707b2009-07-24 23:12:02 +00001370 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001371 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001372
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001373 if (FormatStr[1] == 's') {
Gabor Greifaee5dc12010-06-24 10:42:46 +00001374 // fprintf(F, "%s", str) --> fputs(str, F)
1375 if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001376 return 0;
Eli Friedman9d434db2011-11-17 01:27:36 +00001377 EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001378 return CI;
1379 }
1380 return 0;
1381 }
Richard Osborne022708f2011-03-03 14:20:22 +00001382
1383 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1384 // Require two fixed paramters as pointers and integer result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001385 FunctionType *FT = Callee->getFunctionType();
Richard Osborne022708f2011-03-03 14:20:22 +00001386 if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1387 !FT->getParamType(1)->isPointerTy() ||
1388 !FT->getReturnType()->isIntegerTy())
1389 return 0;
1390
1391 if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
1392 return V;
1393 }
1394
1395 // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
1396 // floating point arguments.
1397 if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
1398 Module *M = B.GetInsertBlock()->getParent()->getParent();
1399 Constant *FIPrintFFn =
1400 M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
1401 CallInst *New = cast<CallInst>(CI->clone());
1402 New->setCalledFunction(FIPrintFFn);
1403 B.Insert(New);
1404 return New;
1405 }
1406 return 0;
1407 }
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001408};
1409
Anders Carlsson303023d2010-11-30 06:19:18 +00001410//===---------------------------------------===//
1411// 'puts' Optimizations
1412
1413struct PutsOpt : public LibCallOptimization {
1414 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1415 // Require one fixed pointer argument and an integer/void result.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001416 FunctionType *FT = Callee->getFunctionType();
Anders Carlsson303023d2010-11-30 06:19:18 +00001417 if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1418 !(FT->getReturnType()->isIntegerTy() ||
1419 FT->getReturnType()->isVoidTy()))
1420 return 0;
1421
1422 // Check for a constant string.
1423 std::string Str;
1424 if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
1425 return 0;
1426
Daniel Dunbard02be242011-02-12 18:19:57 +00001427 if (Str.empty() && CI->use_empty()) {
Anders Carlsson303023d2010-11-30 06:19:18 +00001428 // puts("") -> putchar('\n')
1429 Value *Res = EmitPutChar(B.getInt32('\n'), B, TD);
1430 if (CI->use_empty()) return CI;
1431 return B.CreateIntCast(Res, CI->getType(), true);
1432 }
1433
1434 return 0;
1435 }
1436};
1437
Bill Wendlingac178222008-05-05 21:37:59 +00001438} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001439
1440//===----------------------------------------------------------------------===//
1441// SimplifyLibCalls Pass Implementation
1442//===----------------------------------------------------------------------===//
1443
1444namespace {
1445 /// This pass optimizes well known library functions from libc and libm.
1446 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001447 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001448 TargetLibraryInfo *TLI;
1449
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001450 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 // String and Memory LibCall Optimizations
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001452 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrRChrOpt StrRChr;
1453 StrCmpOpt StrCmp; StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrCpyOpt StrCpyChk;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001454 StrNCpyOpt StrNCpy; StrLenOpt StrLen; StrPBrkOpt StrPBrk;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001455 StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
Chris Lattner24604112009-12-16 09:32:05 +00001456 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001457 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001458 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001459 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001460 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1461 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001462 // Formatting and IO Optimizations
1463 SPrintFOpt SPrintF; PrintFOpt PrintF;
1464 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001465 PutsOpt Puts;
Chris Lattnerafbf4832011-02-24 07:16:14 +00001466
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001467 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001468 public:
1469 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +00001470 SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
1471 initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
1472 }
Eli Friedman9d434db2011-11-17 01:27:36 +00001473 void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001474 void InitOptimizations();
1475 bool runOnFunction(Function &F);
1476
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001477 void setDoesNotAccessMemory(Function &F);
1478 void setOnlyReadsMemory(Function &F);
1479 void setDoesNotThrow(Function &F);
1480 void setDoesNotCapture(Function &F, unsigned n);
1481 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001482 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001483
Chris Lattnere265ad82011-02-24 07:12:12 +00001484 void inferPrototypeAttributes(Function &F);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001486 AU.addRequired<TargetLibraryInfo>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001487 }
1488 };
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001489} // end anonymous namespace.
1490
Chris Lattnerafbf4832011-02-24 07:16:14 +00001491char SimplifyLibCalls::ID = 0;
1492
1493INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
1494 "Simplify well-known library calls", false, false)
1495INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1496INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
1497 "Simplify well-known library calls", false, false)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498
1499// Public interface to the Simplify LibCalls pass.
1500FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001501 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001502}
1503
Eli Friedman9d434db2011-11-17 01:27:36 +00001504void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
1505 if (TLI->has(F))
1506 Optimizations[TLI->getName(F)] = Opt;
1507}
1508
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001509/// Optimizations - Populate the Optimizations map with all the optimizations
1510/// we know.
1511void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001512 // String and Memory LibCall Optimizations
1513 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001514 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001515 Optimizations["strchr"] = &StrChr;
Benjamin Kramer06f25cf2010-09-29 21:50:51 +00001516 Optimizations["strrchr"] = &StrRChr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001517 Optimizations["strcmp"] = &StrCmp;
1518 Optimizations["strncmp"] = &StrNCmp;
1519 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001520 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001521 Optimizations["strlen"] = &StrLen;
Benjamin Kramer05f585e2010-09-29 23:52:12 +00001522 Optimizations["strpbrk"] = &StrPBrk;
Nick Lewycky4c498412009-02-13 15:31:46 +00001523 Optimizations["strtol"] = &StrTo;
1524 Optimizations["strtod"] = &StrTo;
1525 Optimizations["strtof"] = &StrTo;
1526 Optimizations["strtoul"] = &StrTo;
1527 Optimizations["strtoll"] = &StrTo;
1528 Optimizations["strtold"] = &StrTo;
1529 Optimizations["strtoull"] = &StrTo;
Benjamin Kramer9510a252010-09-30 00:58:35 +00001530 Optimizations["strspn"] = &StrSpn;
1531 Optimizations["strcspn"] = &StrCSpn;
Chris Lattner24604112009-12-16 09:32:05 +00001532 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001533 Optimizations["memcmp"] = &MemCmp;
Eli Friedman9d434db2011-11-17 01:27:36 +00001534 AddOpt(LibFunc::memcpy, &MemCpy);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001535 Optimizations["memmove"] = &MemMove;
Eli Friedman9d434db2011-11-17 01:27:36 +00001536 AddOpt(LibFunc::memset, &MemSet);
Eric Christopher37c8b862009-10-07 21:14:25 +00001537
Evan Cheng0289b412010-03-23 15:48:04 +00001538 // _chk variants of String and Memory LibCall Optimizations.
Evan Cheng0289b412010-03-23 15:48:04 +00001539 Optimizations["__strcpy_chk"] = &StrCpyChk;
1540
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001541 // Math Library Optimizations
1542 Optimizations["powf"] = &Pow;
1543 Optimizations["pow"] = &Pow;
1544 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001545 Optimizations["llvm.pow.f32"] = &Pow;
1546 Optimizations["llvm.pow.f64"] = &Pow;
1547 Optimizations["llvm.pow.f80"] = &Pow;
1548 Optimizations["llvm.pow.f128"] = &Pow;
1549 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001550 Optimizations["exp2l"] = &Exp2;
1551 Optimizations["exp2"] = &Exp2;
1552 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001553 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1554 Optimizations["llvm.exp2.f128"] = &Exp2;
1555 Optimizations["llvm.exp2.f80"] = &Exp2;
1556 Optimizations["llvm.exp2.f64"] = &Exp2;
1557 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001558
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001559#ifdef HAVE_FLOORF
1560 Optimizations["floor"] = &UnaryDoubleFP;
1561#endif
1562#ifdef HAVE_CEILF
1563 Optimizations["ceil"] = &UnaryDoubleFP;
1564#endif
1565#ifdef HAVE_ROUNDF
1566 Optimizations["round"] = &UnaryDoubleFP;
1567#endif
1568#ifdef HAVE_RINTF
1569 Optimizations["rint"] = &UnaryDoubleFP;
1570#endif
1571#ifdef HAVE_NEARBYINTF
1572 Optimizations["nearbyint"] = &UnaryDoubleFP;
1573#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001574
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001575 // Integer Optimizations
1576 Optimizations["ffs"] = &FFS;
1577 Optimizations["ffsl"] = &FFS;
1578 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001579 Optimizations["abs"] = &Abs;
1580 Optimizations["labs"] = &Abs;
1581 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001582 Optimizations["isdigit"] = &IsDigit;
1583 Optimizations["isascii"] = &IsAscii;
1584 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001585
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001586 // Formatting and IO Optimizations
1587 Optimizations["sprintf"] = &SPrintF;
1588 Optimizations["printf"] = &PrintF;
Eli Friedman9d434db2011-11-17 01:27:36 +00001589 AddOpt(LibFunc::fwrite, &FWrite);
1590 AddOpt(LibFunc::fputs, &FPuts);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001591 Optimizations["fprintf"] = &FPrintF;
Anders Carlsson303023d2010-11-30 06:19:18 +00001592 Optimizations["puts"] = &Puts;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001593}
1594
1595
1596/// runOnFunction - Top level algorithm.
1597///
1598bool SimplifyLibCalls::runOnFunction(Function &F) {
Chris Lattnerafbf4832011-02-24 07:16:14 +00001599 TLI = &getAnalysis<TargetLibraryInfo>();
1600
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001601 if (Optimizations.empty())
1602 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001603
Dan Gohmanf14d9192009-08-18 00:48:13 +00001604 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001605
Owen Andersone922c022009-07-22 00:24:57 +00001606 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001607
1608 bool Changed = false;
1609 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1610 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1611 // Ignore non-calls.
1612 CallInst *CI = dyn_cast<CallInst>(I++);
1613 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001614
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001615 // Ignore indirect calls and calls to non-external functions.
1616 Function *Callee = CI->getCalledFunction();
1617 if (Callee == 0 || !Callee->isDeclaration() ||
1618 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1619 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001620
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001621 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001622 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1623 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001624
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625 // Set the builder to the instruction after the call.
1626 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001627
Devang Patela2ab3992011-03-09 21:27:52 +00001628 // Use debug location of CI for all new instructions.
1629 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1630
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001631 // Try to optimize this call.
Richard Osborne36498242011-03-03 13:17:51 +00001632 Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001633 if (Result == 0) continue;
1634
David Greene6a6b90e2010-01-05 01:27:21 +00001635 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1636 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001637
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001638 // Something changed!
1639 Changed = true;
1640 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001641
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001642 // Inspect the instruction after the call (which was potentially just
1643 // added) next.
1644 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001645
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001646 if (CI != Result && !CI->use_empty()) {
1647 CI->replaceAllUsesWith(Result);
1648 if (!Result->hasName())
1649 Result->takeName(CI);
1650 }
1651 CI->eraseFromParent();
1652 }
1653 }
1654 return Changed;
1655}
1656
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001657// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001658
1659void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1660 if (!F.doesNotAccessMemory()) {
1661 F.setDoesNotAccessMemory();
1662 ++NumAnnotated;
1663 Modified = true;
1664 }
1665}
1666void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1667 if (!F.onlyReadsMemory()) {
1668 F.setOnlyReadsMemory();
1669 ++NumAnnotated;
1670 Modified = true;
1671 }
1672}
1673void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1674 if (!F.doesNotThrow()) {
1675 F.setDoesNotThrow();
1676 ++NumAnnotated;
1677 Modified = true;
1678 }
1679}
1680void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1681 if (!F.doesNotCapture(n)) {
1682 F.setDoesNotCapture(n);
1683 ++NumAnnotated;
1684 Modified = true;
1685 }
1686}
1687void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1688 if (!F.doesNotAlias(n)) {
1689 F.setDoesNotAlias(n);
1690 ++NumAnnotated;
1691 Modified = true;
1692 }
1693}
1694
Chris Lattnere265ad82011-02-24 07:12:12 +00001695
1696void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001697 FunctionType *FTy = F.getFunctionType();
Chris Lattnere265ad82011-02-24 07:12:12 +00001698
1699 StringRef Name = F.getName();
1700 switch (Name[0]) {
1701 case 's':
1702 if (Name == "strlen") {
1703 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1704 return;
1705 setOnlyReadsMemory(F);
1706 setDoesNotThrow(F);
1707 setDoesNotCapture(F, 1);
1708 } else if (Name == "strchr" ||
1709 Name == "strrchr") {
1710 if (FTy->getNumParams() != 2 ||
1711 !FTy->getParamType(0)->isPointerTy() ||
1712 !FTy->getParamType(1)->isIntegerTy())
1713 return;
1714 setOnlyReadsMemory(F);
1715 setDoesNotThrow(F);
1716 } else if (Name == "strcpy" ||
1717 Name == "stpcpy" ||
1718 Name == "strcat" ||
1719 Name == "strtol" ||
1720 Name == "strtod" ||
1721 Name == "strtof" ||
1722 Name == "strtoul" ||
1723 Name == "strtoll" ||
1724 Name == "strtold" ||
1725 Name == "strncat" ||
1726 Name == "strncpy" ||
1727 Name == "strtoull") {
1728 if (FTy->getNumParams() < 2 ||
1729 !FTy->getParamType(1)->isPointerTy())
1730 return;
1731 setDoesNotThrow(F);
1732 setDoesNotCapture(F, 2);
1733 } else if (Name == "strxfrm") {
1734 if (FTy->getNumParams() != 3 ||
1735 !FTy->getParamType(0)->isPointerTy() ||
1736 !FTy->getParamType(1)->isPointerTy())
1737 return;
1738 setDoesNotThrow(F);
1739 setDoesNotCapture(F, 1);
1740 setDoesNotCapture(F, 2);
1741 } else if (Name == "strcmp" ||
1742 Name == "strspn" ||
1743 Name == "strncmp" ||
1744 Name == "strcspn" ||
1745 Name == "strcoll" ||
1746 Name == "strcasecmp" ||
1747 Name == "strncasecmp") {
1748 if (FTy->getNumParams() < 2 ||
1749 !FTy->getParamType(0)->isPointerTy() ||
1750 !FTy->getParamType(1)->isPointerTy())
1751 return;
1752 setOnlyReadsMemory(F);
1753 setDoesNotThrow(F);
1754 setDoesNotCapture(F, 1);
1755 setDoesNotCapture(F, 2);
1756 } else if (Name == "strstr" ||
1757 Name == "strpbrk") {
1758 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1759 return;
1760 setOnlyReadsMemory(F);
1761 setDoesNotThrow(F);
1762 setDoesNotCapture(F, 2);
1763 } else if (Name == "strtok" ||
1764 Name == "strtok_r") {
1765 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1766 return;
1767 setDoesNotThrow(F);
1768 setDoesNotCapture(F, 2);
1769 } else if (Name == "scanf" ||
1770 Name == "setbuf" ||
1771 Name == "setvbuf") {
1772 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1773 return;
1774 setDoesNotThrow(F);
1775 setDoesNotCapture(F, 1);
1776 } else if (Name == "strdup" ||
1777 Name == "strndup") {
1778 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1779 !FTy->getParamType(0)->isPointerTy())
1780 return;
1781 setDoesNotThrow(F);
1782 setDoesNotAlias(F, 0);
1783 setDoesNotCapture(F, 1);
1784 } else if (Name == "stat" ||
1785 Name == "sscanf" ||
1786 Name == "sprintf" ||
1787 Name == "statvfs") {
1788 if (FTy->getNumParams() < 2 ||
1789 !FTy->getParamType(0)->isPointerTy() ||
1790 !FTy->getParamType(1)->isPointerTy())
1791 return;
1792 setDoesNotThrow(F);
1793 setDoesNotCapture(F, 1);
1794 setDoesNotCapture(F, 2);
1795 } else if (Name == "snprintf") {
1796 if (FTy->getNumParams() != 3 ||
1797 !FTy->getParamType(0)->isPointerTy() ||
1798 !FTy->getParamType(2)->isPointerTy())
1799 return;
1800 setDoesNotThrow(F);
1801 setDoesNotCapture(F, 1);
1802 setDoesNotCapture(F, 3);
1803 } else if (Name == "setitimer") {
1804 if (FTy->getNumParams() != 3 ||
1805 !FTy->getParamType(1)->isPointerTy() ||
1806 !FTy->getParamType(2)->isPointerTy())
1807 return;
1808 setDoesNotThrow(F);
1809 setDoesNotCapture(F, 2);
1810 setDoesNotCapture(F, 3);
1811 } else if (Name == "system") {
1812 if (FTy->getNumParams() != 1 ||
1813 !FTy->getParamType(0)->isPointerTy())
1814 return;
1815 // May throw; "system" is a valid pthread cancellation point.
1816 setDoesNotCapture(F, 1);
1817 }
1818 break;
1819 case 'm':
1820 if (Name == "malloc") {
1821 if (FTy->getNumParams() != 1 ||
1822 !FTy->getReturnType()->isPointerTy())
1823 return;
1824 setDoesNotThrow(F);
1825 setDoesNotAlias(F, 0);
1826 } else if (Name == "memcmp") {
1827 if (FTy->getNumParams() != 3 ||
1828 !FTy->getParamType(0)->isPointerTy() ||
1829 !FTy->getParamType(1)->isPointerTy())
1830 return;
1831 setOnlyReadsMemory(F);
1832 setDoesNotThrow(F);
1833 setDoesNotCapture(F, 1);
1834 setDoesNotCapture(F, 2);
1835 } else if (Name == "memchr" ||
1836 Name == "memrchr") {
1837 if (FTy->getNumParams() != 3)
1838 return;
1839 setOnlyReadsMemory(F);
1840 setDoesNotThrow(F);
1841 } else if (Name == "modf" ||
1842 Name == "modff" ||
1843 Name == "modfl" ||
1844 Name == "memcpy" ||
1845 Name == "memccpy" ||
1846 Name == "memmove") {
1847 if (FTy->getNumParams() < 2 ||
1848 !FTy->getParamType(1)->isPointerTy())
1849 return;
1850 setDoesNotThrow(F);
1851 setDoesNotCapture(F, 2);
1852 } else if (Name == "memalign") {
1853 if (!FTy->getReturnType()->isPointerTy())
1854 return;
1855 setDoesNotAlias(F, 0);
1856 } else if (Name == "mkdir" ||
1857 Name == "mktime") {
1858 if (FTy->getNumParams() == 0 ||
1859 !FTy->getParamType(0)->isPointerTy())
1860 return;
1861 setDoesNotThrow(F);
1862 setDoesNotCapture(F, 1);
1863 }
1864 break;
1865 case 'r':
1866 if (Name == "realloc") {
1867 if (FTy->getNumParams() != 2 ||
1868 !FTy->getParamType(0)->isPointerTy() ||
1869 !FTy->getReturnType()->isPointerTy())
1870 return;
1871 setDoesNotThrow(F);
1872 setDoesNotAlias(F, 0);
1873 setDoesNotCapture(F, 1);
1874 } else if (Name == "read") {
1875 if (FTy->getNumParams() != 3 ||
1876 !FTy->getParamType(1)->isPointerTy())
1877 return;
1878 // May throw; "read" is a valid pthread cancellation point.
1879 setDoesNotCapture(F, 2);
1880 } else if (Name == "rmdir" ||
1881 Name == "rewind" ||
1882 Name == "remove" ||
1883 Name == "realpath") {
1884 if (FTy->getNumParams() < 1 ||
1885 !FTy->getParamType(0)->isPointerTy())
1886 return;
1887 setDoesNotThrow(F);
1888 setDoesNotCapture(F, 1);
1889 } else if (Name == "rename" ||
1890 Name == "readlink") {
1891 if (FTy->getNumParams() < 2 ||
1892 !FTy->getParamType(0)->isPointerTy() ||
1893 !FTy->getParamType(1)->isPointerTy())
1894 return;
1895 setDoesNotThrow(F);
1896 setDoesNotCapture(F, 1);
1897 setDoesNotCapture(F, 2);
1898 }
1899 break;
1900 case 'w':
1901 if (Name == "write") {
1902 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1903 return;
1904 // May throw; "write" is a valid pthread cancellation point.
1905 setDoesNotCapture(F, 2);
1906 }
1907 break;
1908 case 'b':
1909 if (Name == "bcopy") {
1910 if (FTy->getNumParams() != 3 ||
1911 !FTy->getParamType(0)->isPointerTy() ||
1912 !FTy->getParamType(1)->isPointerTy())
1913 return;
1914 setDoesNotThrow(F);
1915 setDoesNotCapture(F, 1);
1916 setDoesNotCapture(F, 2);
1917 } else if (Name == "bcmp") {
1918 if (FTy->getNumParams() != 3 ||
1919 !FTy->getParamType(0)->isPointerTy() ||
1920 !FTy->getParamType(1)->isPointerTy())
1921 return;
1922 setDoesNotThrow(F);
1923 setOnlyReadsMemory(F);
1924 setDoesNotCapture(F, 1);
1925 setDoesNotCapture(F, 2);
1926 } else if (Name == "bzero") {
1927 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1928 return;
1929 setDoesNotThrow(F);
1930 setDoesNotCapture(F, 1);
1931 }
1932 break;
1933 case 'c':
1934 if (Name == "calloc") {
1935 if (FTy->getNumParams() != 2 ||
1936 !FTy->getReturnType()->isPointerTy())
1937 return;
1938 setDoesNotThrow(F);
1939 setDoesNotAlias(F, 0);
1940 } else if (Name == "chmod" ||
1941 Name == "chown" ||
1942 Name == "ctermid" ||
1943 Name == "clearerr" ||
1944 Name == "closedir") {
1945 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1946 return;
1947 setDoesNotThrow(F);
1948 setDoesNotCapture(F, 1);
1949 }
1950 break;
1951 case 'a':
1952 if (Name == "atoi" ||
1953 Name == "atol" ||
1954 Name == "atof" ||
1955 Name == "atoll") {
1956 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1957 return;
1958 setDoesNotThrow(F);
1959 setOnlyReadsMemory(F);
1960 setDoesNotCapture(F, 1);
1961 } else if (Name == "access") {
1962 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1963 return;
1964 setDoesNotThrow(F);
1965 setDoesNotCapture(F, 1);
1966 }
1967 break;
1968 case 'f':
1969 if (Name == "fopen") {
1970 if (FTy->getNumParams() != 2 ||
1971 !FTy->getReturnType()->isPointerTy() ||
1972 !FTy->getParamType(0)->isPointerTy() ||
1973 !FTy->getParamType(1)->isPointerTy())
1974 return;
1975 setDoesNotThrow(F);
1976 setDoesNotAlias(F, 0);
1977 setDoesNotCapture(F, 1);
1978 setDoesNotCapture(F, 2);
1979 } else if (Name == "fdopen") {
1980 if (FTy->getNumParams() != 2 ||
1981 !FTy->getReturnType()->isPointerTy() ||
1982 !FTy->getParamType(1)->isPointerTy())
1983 return;
1984 setDoesNotThrow(F);
1985 setDoesNotAlias(F, 0);
1986 setDoesNotCapture(F, 2);
1987 } else if (Name == "feof" ||
1988 Name == "free" ||
1989 Name == "fseek" ||
1990 Name == "ftell" ||
1991 Name == "fgetc" ||
1992 Name == "fseeko" ||
1993 Name == "ftello" ||
1994 Name == "fileno" ||
1995 Name == "fflush" ||
1996 Name == "fclose" ||
1997 Name == "fsetpos" ||
1998 Name == "flockfile" ||
1999 Name == "funlockfile" ||
2000 Name == "ftrylockfile") {
2001 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2002 return;
2003 setDoesNotThrow(F);
2004 setDoesNotCapture(F, 1);
2005 } else if (Name == "ferror") {
2006 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2007 return;
2008 setDoesNotThrow(F);
2009 setDoesNotCapture(F, 1);
2010 setOnlyReadsMemory(F);
2011 } else if (Name == "fputc" ||
2012 Name == "fstat" ||
2013 Name == "frexp" ||
2014 Name == "frexpf" ||
2015 Name == "frexpl" ||
2016 Name == "fstatvfs") {
2017 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2018 return;
2019 setDoesNotThrow(F);
2020 setDoesNotCapture(F, 2);
2021 } else if (Name == "fgets") {
2022 if (FTy->getNumParams() != 3 ||
2023 !FTy->getParamType(0)->isPointerTy() ||
2024 !FTy->getParamType(2)->isPointerTy())
2025 return;
2026 setDoesNotThrow(F);
2027 setDoesNotCapture(F, 3);
2028 } else if (Name == "fread" ||
2029 Name == "fwrite") {
2030 if (FTy->getNumParams() != 4 ||
2031 !FTy->getParamType(0)->isPointerTy() ||
2032 !FTy->getParamType(3)->isPointerTy())
2033 return;
2034 setDoesNotThrow(F);
2035 setDoesNotCapture(F, 1);
2036 setDoesNotCapture(F, 4);
2037 } else if (Name == "fputs" ||
2038 Name == "fscanf" ||
2039 Name == "fprintf" ||
2040 Name == "fgetpos") {
2041 if (FTy->getNumParams() < 2 ||
2042 !FTy->getParamType(0)->isPointerTy() ||
2043 !FTy->getParamType(1)->isPointerTy())
2044 return;
2045 setDoesNotThrow(F);
2046 setDoesNotCapture(F, 1);
2047 setDoesNotCapture(F, 2);
2048 }
2049 break;
2050 case 'g':
2051 if (Name == "getc" ||
2052 Name == "getlogin_r" ||
2053 Name == "getc_unlocked") {
2054 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2055 return;
2056 setDoesNotThrow(F);
2057 setDoesNotCapture(F, 1);
2058 } else if (Name == "getenv") {
2059 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2060 return;
2061 setDoesNotThrow(F);
2062 setOnlyReadsMemory(F);
2063 setDoesNotCapture(F, 1);
2064 } else if (Name == "gets" ||
2065 Name == "getchar") {
2066 setDoesNotThrow(F);
2067 } else if (Name == "getitimer") {
2068 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2069 return;
2070 setDoesNotThrow(F);
2071 setDoesNotCapture(F, 2);
2072 } else if (Name == "getpwnam") {
2073 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2074 return;
2075 setDoesNotThrow(F);
2076 setDoesNotCapture(F, 1);
2077 }
2078 break;
2079 case 'u':
2080 if (Name == "ungetc") {
2081 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2082 return;
2083 setDoesNotThrow(F);
2084 setDoesNotCapture(F, 2);
2085 } else if (Name == "uname" ||
2086 Name == "unlink" ||
2087 Name == "unsetenv") {
2088 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2089 return;
2090 setDoesNotThrow(F);
2091 setDoesNotCapture(F, 1);
2092 } else if (Name == "utime" ||
2093 Name == "utimes") {
2094 if (FTy->getNumParams() != 2 ||
2095 !FTy->getParamType(0)->isPointerTy() ||
2096 !FTy->getParamType(1)->isPointerTy())
2097 return;
2098 setDoesNotThrow(F);
2099 setDoesNotCapture(F, 1);
2100 setDoesNotCapture(F, 2);
2101 }
2102 break;
2103 case 'p':
2104 if (Name == "putc") {
2105 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2106 return;
2107 setDoesNotThrow(F);
2108 setDoesNotCapture(F, 2);
2109 } else if (Name == "puts" ||
2110 Name == "printf" ||
2111 Name == "perror") {
2112 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2113 return;
2114 setDoesNotThrow(F);
2115 setDoesNotCapture(F, 1);
2116 } else if (Name == "pread" ||
2117 Name == "pwrite") {
2118 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
2119 return;
2120 // May throw; these are valid pthread cancellation points.
2121 setDoesNotCapture(F, 2);
2122 } else if (Name == "putchar") {
2123 setDoesNotThrow(F);
2124 } else if (Name == "popen") {
2125 if (FTy->getNumParams() != 2 ||
2126 !FTy->getReturnType()->isPointerTy() ||
2127 !FTy->getParamType(0)->isPointerTy() ||
2128 !FTy->getParamType(1)->isPointerTy())
2129 return;
2130 setDoesNotThrow(F);
2131 setDoesNotAlias(F, 0);
2132 setDoesNotCapture(F, 1);
2133 setDoesNotCapture(F, 2);
2134 } else if (Name == "pclose") {
2135 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2136 return;
2137 setDoesNotThrow(F);
2138 setDoesNotCapture(F, 1);
2139 }
2140 break;
2141 case 'v':
2142 if (Name == "vscanf") {
2143 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2144 return;
2145 setDoesNotThrow(F);
2146 setDoesNotCapture(F, 1);
2147 } else if (Name == "vsscanf" ||
2148 Name == "vfscanf") {
2149 if (FTy->getNumParams() != 3 ||
2150 !FTy->getParamType(1)->isPointerTy() ||
2151 !FTy->getParamType(2)->isPointerTy())
2152 return;
2153 setDoesNotThrow(F);
2154 setDoesNotCapture(F, 1);
2155 setDoesNotCapture(F, 2);
2156 } else if (Name == "valloc") {
2157 if (!FTy->getReturnType()->isPointerTy())
2158 return;
2159 setDoesNotThrow(F);
2160 setDoesNotAlias(F, 0);
2161 } else if (Name == "vprintf") {
2162 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
2163 return;
2164 setDoesNotThrow(F);
2165 setDoesNotCapture(F, 1);
2166 } else if (Name == "vfprintf" ||
2167 Name == "vsprintf") {
2168 if (FTy->getNumParams() != 3 ||
2169 !FTy->getParamType(0)->isPointerTy() ||
2170 !FTy->getParamType(1)->isPointerTy())
2171 return;
2172 setDoesNotThrow(F);
2173 setDoesNotCapture(F, 1);
2174 setDoesNotCapture(F, 2);
2175 } else if (Name == "vsnprintf") {
2176 if (FTy->getNumParams() != 4 ||
2177 !FTy->getParamType(0)->isPointerTy() ||
2178 !FTy->getParamType(2)->isPointerTy())
2179 return;
2180 setDoesNotThrow(F);
2181 setDoesNotCapture(F, 1);
2182 setDoesNotCapture(F, 3);
2183 }
2184 break;
2185 case 'o':
2186 if (Name == "open") {
2187 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2188 return;
2189 // May throw; "open" is a valid pthread cancellation point.
2190 setDoesNotCapture(F, 1);
2191 } else if (Name == "opendir") {
2192 if (FTy->getNumParams() != 1 ||
2193 !FTy->getReturnType()->isPointerTy() ||
2194 !FTy->getParamType(0)->isPointerTy())
2195 return;
2196 setDoesNotThrow(F);
2197 setDoesNotAlias(F, 0);
2198 setDoesNotCapture(F, 1);
2199 }
2200 break;
2201 case 't':
2202 if (Name == "tmpfile") {
2203 if (!FTy->getReturnType()->isPointerTy())
2204 return;
2205 setDoesNotThrow(F);
2206 setDoesNotAlias(F, 0);
2207 } else if (Name == "times") {
2208 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2209 return;
2210 setDoesNotThrow(F);
2211 setDoesNotCapture(F, 1);
2212 }
2213 break;
2214 case 'h':
2215 if (Name == "htonl" ||
2216 Name == "htons") {
2217 setDoesNotThrow(F);
2218 setDoesNotAccessMemory(F);
2219 }
2220 break;
2221 case 'n':
2222 if (Name == "ntohl" ||
2223 Name == "ntohs") {
2224 setDoesNotThrow(F);
2225 setDoesNotAccessMemory(F);
2226 }
2227 break;
2228 case 'l':
2229 if (Name == "lstat") {
2230 if (FTy->getNumParams() != 2 ||
2231 !FTy->getParamType(0)->isPointerTy() ||
2232 !FTy->getParamType(1)->isPointerTy())
2233 return;
2234 setDoesNotThrow(F);
2235 setDoesNotCapture(F, 1);
2236 setDoesNotCapture(F, 2);
2237 } else if (Name == "lchown") {
2238 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
2239 return;
2240 setDoesNotThrow(F);
2241 setDoesNotCapture(F, 1);
2242 }
2243 break;
2244 case 'q':
2245 if (Name == "qsort") {
2246 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
2247 return;
2248 // May throw; places call through function pointer.
2249 setDoesNotCapture(F, 4);
2250 }
2251 break;
2252 case '_':
2253 if (Name == "__strdup" ||
2254 Name == "__strndup") {
2255 if (FTy->getNumParams() < 1 ||
2256 !FTy->getReturnType()->isPointerTy() ||
2257 !FTy->getParamType(0)->isPointerTy())
2258 return;
2259 setDoesNotThrow(F);
2260 setDoesNotAlias(F, 0);
2261 setDoesNotCapture(F, 1);
2262 } else if (Name == "__strtok_r") {
2263 if (FTy->getNumParams() != 3 ||
2264 !FTy->getParamType(1)->isPointerTy())
2265 return;
2266 setDoesNotThrow(F);
2267 setDoesNotCapture(F, 2);
2268 } else if (Name == "_IO_getc") {
2269 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
2270 return;
2271 setDoesNotThrow(F);
2272 setDoesNotCapture(F, 1);
2273 } else if (Name == "_IO_putc") {
2274 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2275 return;
2276 setDoesNotThrow(F);
2277 setDoesNotCapture(F, 2);
2278 }
2279 break;
2280 case 1:
2281 if (Name == "\1__isoc99_scanf") {
2282 if (FTy->getNumParams() < 1 ||
2283 !FTy->getParamType(0)->isPointerTy())
2284 return;
2285 setDoesNotThrow(F);
2286 setDoesNotCapture(F, 1);
2287 } else if (Name == "\1stat64" ||
2288 Name == "\1lstat64" ||
2289 Name == "\1statvfs64" ||
2290 Name == "\1__isoc99_sscanf") {
2291 if (FTy->getNumParams() < 1 ||
2292 !FTy->getParamType(0)->isPointerTy() ||
2293 !FTy->getParamType(1)->isPointerTy())
2294 return;
2295 setDoesNotThrow(F);
2296 setDoesNotCapture(F, 1);
2297 setDoesNotCapture(F, 2);
2298 } else if (Name == "\1fopen64") {
2299 if (FTy->getNumParams() != 2 ||
2300 !FTy->getReturnType()->isPointerTy() ||
2301 !FTy->getParamType(0)->isPointerTy() ||
2302 !FTy->getParamType(1)->isPointerTy())
2303 return;
2304 setDoesNotThrow(F);
2305 setDoesNotAlias(F, 0);
2306 setDoesNotCapture(F, 1);
2307 setDoesNotCapture(F, 2);
2308 } else if (Name == "\1fseeko64" ||
2309 Name == "\1ftello64") {
2310 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
2311 return;
2312 setDoesNotThrow(F);
2313 setDoesNotCapture(F, 1);
2314 } else if (Name == "\1tmpfile64") {
2315 if (!FTy->getReturnType()->isPointerTy())
2316 return;
2317 setDoesNotThrow(F);
2318 setDoesNotAlias(F, 0);
2319 } else if (Name == "\1fstat64" ||
2320 Name == "\1fstatvfs64") {
2321 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
2322 return;
2323 setDoesNotThrow(F);
2324 setDoesNotCapture(F, 2);
2325 } else if (Name == "\1open64") {
2326 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
2327 return;
2328 // May throw; "open" is a valid pthread cancellation point.
2329 setDoesNotCapture(F, 1);
2330 }
2331 break;
2332 }
2333}
2334
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002335/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002336///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002337bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002338 Modified = false;
2339 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
2340 Function &F = *I;
Chris Lattnere265ad82011-02-24 07:12:12 +00002341 if (F.isDeclaration() && F.hasName())
2342 inferPrototypeAttributes(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002343 }
2344 return Modified;
2345}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002346
2347// TODO:
2348// Additional cases that we need to add to this file:
2349//
2350// cbrt:
2351// * cbrt(expN(X)) -> expN(x/3)
2352// * cbrt(sqrt(x)) -> pow(x,1/6)
2353// * cbrt(sqrt(x)) -> pow(x,1/9)
2354//
2355// cos, cosf, cosl:
2356// * cos(-x) -> cos(x)
2357//
2358// exp, expf, expl:
2359// * exp(log(x)) -> x
2360//
2361// log, logf, logl:
2362// * log(exp(x)) -> x
2363// * log(x**y) -> y*log(x)
2364// * log(exp(y)) -> y*log(e)
2365// * log(exp2(y)) -> y*log(2)
2366// * log(exp10(y)) -> y*log(10)
2367// * log(sqrt(x)) -> 0.5*log(x)
2368// * log(pow(x,y)) -> y*log(x)
2369//
2370// lround, lroundf, lroundl:
2371// * lround(cnst) -> cnst'
2372//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002373// pow, powf, powl:
2374// * pow(exp(x),y) -> exp(x*y)
2375// * pow(sqrt(x),y) -> pow(x,y*0.5)
2376// * pow(pow(x,y),z)-> pow(x,y*z)
2377//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002378// round, roundf, roundl:
2379// * round(cnst) -> cnst'
2380//
2381// signbit:
2382// * signbit(cnst) -> cnst'
2383// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2384//
2385// sqrt, sqrtf, sqrtl:
2386// * sqrt(expN(x)) -> expN(x*0.5)
2387// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2388// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2389//
2390// stpcpy:
2391// * stpcpy(str, "literal") ->
2392// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002393//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002394// tan, tanf, tanl:
2395// * tan(atan(x)) -> x
2396//
2397// trunc, truncf, truncl:
2398// * trunc(cnst) -> cnst'
2399//
2400//